Trying to add array keys without array values - php

Ok, so I'm trying to write something which will analyze the US Presidential candidates.
I'm trying to add all of the values up on a given day - I'm part of the way through that.
Anyway, $romlinearray - I want to have two values inside, the date, and the value for a given day. I want to insert them inside the if ($romneydiff == 0) { block.
What I am having a problem with is generating an array with a key name (i.e. I want to be able to do $romlinearray["value"]) and have it pull a value, but the value isn't going to be inserted until later.
How can I create an array with a key, but without a value as of yet?
$resultromney = mysql_query("SELECT category, value, timestamp from results where name='".$chartname2."'");
if (!$resultromney) {
die('Invalid query, please contact administrator');
}
$posromney = 0;
$negromney = 0;
$dateromney = "1/1/2012";
$romray = array();
while ($twitromney = mysql_fetch_assoc($resultromney))
{
$romneytime = intval($twitromney["timestamp"]);
$romneydate = date('m/d/Y', $romneytime);
$romlinearray = array(); // THIS IS WHERE THE PROBLEM IS
$romneydiff = date_diff($dateromney, $romneytime);
$PLromney = 0;
$NLromney = 0;
$totalromney = 0;
if ($romneydiff == 0) {
switch ($twitromney["category"]) {
case "composed":
$PLromney = $PLromney + $twitromney["value"];
break;
case "elated":
$PLromney = $PLromney + $twitromney["value"];
break;
case "clearheaded":
$PLromney = $PLromney + $twitromney["value"];
break;
case "agreeable":
$PLromney = $PLromney + $twitromney["value"];
break;
case "energetic":
$PLromney = $PLromney + $twitromney["value"];
break;
case "unsure":
$NLromney = $NLromney + $twitromney["value"];
break;
case "tired":
$NLromney = $NLromney + $twitromney["value"];
break;
case "depressed":
$NLromney = $NLromney + $twitromney["value"];
break;
case "guilty":
$NLromney = $NLromney + $twitromney["value"];
break;
case "confused":
$NLromney = $NLromney + $twitromney["value"];
break;
case "anxious":
$NLromney = $NLromney + $twitromney["value"];
break;
case "hostile":
$NLromney = $NLromney + $twitromney["value"];
break;
case "confident":
$PLromney = $PLromney + $twitromney["value"];
break;
}
$totalromney = $PLromney - $NLromney;
$romlinearray["value"] = $totalromney + $romlinearray["value"];
}

Related

PHP, switch case returned undefined variable

Hy,
I got switch case inside function when but when i call it, i got error Undefined Variable and i don't know why (i use PHP 8)
private function getIDFromBrand() {
switch ($this->brand) {
case "Niky":
$id = 1;
break;
case "Pumo":
$id = 4;
break;
case "Coke":
if ($this->typecoke== 0) {
$id = 2;
} else {
if ($this->typecoke== 1) {
$id = 3;
}
}
break;
case "Tomato":
$id = 5;
break;
case "Riles":
$id = 6;
break;
case "TEST":
$id = 7;
break;
}
return $id; // Error Undefined variable $id
}
When i declare $id at the top of my function, like
$id = null
or
$id = 0
The switch doesn't update it, so it will return null or 0, it will return the declared value.
Your switch statement has no default branch, so if $this->brand is, say, "Stack Overflow", it will not run any of the statements, and $id will never be set.
See the PHP manual for the switch statement:
A special case is the default case. This case matches anything that wasn't matched by the other cases.
Similarly, if $this->brand is "Coke", but $this->typecoke is, say, 42, it will not match either of the conditions in that branch.
switch ($this->brand) {
case "Niky":
$id = 1;
break;
case "Pumo":
$id = 4;
break;
case "Coke":
if ($this->typecoke== 0) {
$id = 2;
} elseif ($this->typecoke== 1) {
$id = 3;
} else {
$id = -1; // WAS PREVIOUSLY NOT SET
}
break;
case "Tomato":
$id = 5;
break;
case "Riles":
$id = 6;
break;
case "TEST":
$id = 7;
break;
default:
$id = -1; // WAS PREVIOUSLY NOT SET
break;
}

Unable to insert data into database if I select only one day in a week

I am trying to insert data into database by checking the days in a week but I am unable to insert if I check only one day in a week, if I check two or more days I am able to insert.
<?php
//other parameters
$days_only = $_REQUEST['days_only'];
using an array to split days in a week
$day_array = explode(",",$days_only);
$count_sample = count($day_array);
if($count_sample==1) {
$in_sample='('.$days_only.')';
}
elseif($count_sample>0) {
$in_sample="('".str_replace(",","','" , $days_only)."')";
}
$test='IN'.$in_sample;
$sth = "SELECT e_id FROM `schedule` WHERE
user_id = '$user_id' AND
date BETWEEN '$start_date' AND '$end_date' AND
(
TIME(start_time) >= '$start_time' AND
TIME(start_time) <= '$end_time' OR
TIME(end_time) >= '$start_time' AND
TIME(end_time) <= '$end_time'
) AND days_only $test";
$res = $db->prepare($sth);
$res->execute();
$count = $res->fetchAll();
if ($count) {
echo "すでにスケジュールが登録されています";
} else {
for($i = strtotime($start_date); $i <= strtotime($end_date); $i +=86400 ){
$date = date("Y-m-d", $i);
$days_only = date('l', $i);
switch ($days_only) {
case 'Monday': $days_only = "月"; break;
case 'Tuesday': $days_only = "火"; break;
case 'Wednesday': $days_only = "水"; break;
case 'Thursday': $days_only = "木"; break;
case 'Friday': $days_only = "金"; break;
case 'Saturday': $days_only = "土"; break;
case 'Sunday': $days_only = "日"; break;
}
echo "$date";
echo "$days_only";
if (in_array($days_only,$day_array)){
query for inserting into database
}
else{
echo "wrong";
}
}
}
?>
Here's the issue:
if( $count_sample==1 ) {
$in_sample='('.$days_only.')';
}
The string that you're passing in $days_only is not being escaped here, but it is when the $count_sample value is greater than one. The above code will give you something like this: (金)
Perhaps you can replace the two outermost single-quotes with a double-quote and drop the concat period:
$in_sample= "('$days_only')";
Or you can replace a good bit of code with a single implode():
if ( $count_sample > 0) {
$in_sample="('" . implode("','", $days_only) . "')";
}
Be sure to remember to add validation to your inputs before sending this to the database, otherwise you leave yourself open to SQL injection 👍🏻

Mysql Stored Procedure - Return Table headers if no Data found

We are using magento and PHP. And have a stored Procedure which do some processing and its finally suppose to return multiple results set using select queries.
Eg : Select * FROM table1;
Select * FROM table2;
Select * FROM table3;
The issue is that, not all tables might have data in it. If there is no data in table stored procedure returns nothing. And in the PHP we are using a for loop to fetch data.
for($i= 0; $i<=3; $i++){
$rowset = $sql->fetchAll(PDO::FETCH_ASSOC);
if ($rowset) {
switch ($i) {
case 0:
$spStatus = $rowset;
break;
case 1:
$boqSections = $rowset;
break;
case 2:
$boqEntries = $rowset;
break;
case 3:
$boqItems = $rowset;
break;
}
}
$sql->nextRowset();
}
So if there is no data found in table3. Stored procedure will not return a 3rd rowset/resultset. So in the above loop a 3rd call to $sql->fetchAll(PDO::FETCH_ASSOC); will fail causing a General error.
Are there any work around to solve this issue?
Add below condition for rowCount
for($i= 0; $i<=3; $i++){
$rowset = $sql->fetchAll(PDO::FETCH_ASSOC);
if ($rowset && $sql->rowCount() >0) {
switch ($i) {
case 0:
$spStatus = $rowset;
break;
case 1:
$boqSections = $rowset;
break;
case 2:
$boqEntries = $rowset;
break;
case 3:
$boqItems = $rowset;
break;
}
} else {
$spStatus = [];
$boqSections = [];
$boqEntries = [];
$boqItems = [];
}
$sql->nextRowset();
}
Hope This will help.

php object oriented calculator

Hello im trying to make an object as learning task which takes a number and calculate it three times and echos every step.
<?
// neues Objekt der Klasse erzeugen
$stringManager = new StringManager();
// output String initialisieren
$meinString = "";
$zahl = "100";
$stringManager->setMeinString($meinString);
$stringManager->setZahl($zahl);
// Schritte ausführen
for ($i=1; $i<=3; $i++) {
$stringManager->machSchritt($i,$zahl);
}
// String ausgeben
echo $stringManager->getMeinString();
// Klasse StringManager
class StringManager {
var $meinString;
var $zahl;
function StringManager() {
}
function machSchritt($welchenSchritt,$zahl) {
switch ($welchenSchritt) {
case 1:
$zahl + 50;
break;
case 2:
$zahl / 2;
break;
case 3:
$zahl * 5;
break;
default:
break;
}
$this->append("schritt".$welchenSchritt." fertig...");
$this->append("Zahl:".$zahl." ");
}
function append($what) {
$this->meinString .= $what;
}
//function append($what) {
//$this->zahl .= $what;
//}
function setMeinString($value) {
$this->meinString = $value;
}
function getMeinString() {
return $this->meinString;
}
function setZahl($value) {
$this->zahl = $value;
}
function getZahl() {
return $this->zahl;
}
}
?>
My output is: "schritt1 fertig...Zahl:100 schritt2 fertig...Zahl:100 schritt3 fertig...Zahl:100"
But I expect it to be "schritt1 fertig...Zahl:150 schritt2 fertig...Zahl:75 schritt3 fertig...Zahl:375
Please help me find what im doing wrong.
your problem is between this lines:
$zahl + 50;
break;
case 2:
$zahl / 2;
break;
case 3:
$zahl * 5;
if you want to increase/manipulate the variable $zahl so you have to use it:
$zahl += 50;
break;
case 2:
$zahl /= 2;
break;
case 3:
$zahl *= 5;
btw: your code is deprecated.
class StringManager {
var $meinString;
var $zahl;
function StringManager() {
}
}
should replace with
class StringManager {
private $meinString;
private $zahl;
public function __construct() {
}
}
update:
ah, now i understand, you need to work with your value.
so use this instead:
$this->zahl += 50;
break;
case 2:
$this->zahl /= 2;
break;
case 3:
$this->zahl *= 5;
$this->append("Zahl:".$this->zahl." ");
But it would be better, to use your setter (with typecasting) and getter methods.
warning
your code looks like php4 code. php4 is not supported since 2008 (http://php.net/eol.php).

MySQL Select Not Returning resource

I am having a small problem with my PHP MySQL Select. The function is inside of a PHP class. Here is the error I get:
Warning: mysql_fetch_array() expects parameter 1 to be resource,
integer given in C:\xampp\htdocs\include\database.php on line 59
Warning: extract() expects parameter 1 to be array, null given in
C:\xampp\htdocs\include\database.php on line 59
The function just simply updates the database to show what browser and OS they visited the site with. The function is called from another file that is called by an AJAX call that uses POST to send the data about the OS and browser that was gathered from a Javascript file. It only fails if there is an entry of the IP address already in the database. If there is no IP Address entry in the database it succeeds in creating one.
Here is my code:
function addStat($browser, $os){
$IE = 0; $Firefox = 0; $Safari = 0; $Opera = 0; $Chrome = 0; $otherb = 0;
$Windows = 0; $Linux = 0; $Mac = 0; $Android = 0; $iOS = 0; $otheros = 0;
$ql = 0; $totalVisits = 0;
$ip = ip2long($_SERVER['REMOTE_ADDR']);
$q1 = mysql_query("SELECT * FROM " . DB_STATS . " WHERE ip='$ip'", $this->connection);
if (mysql_num_rows($q1)==0){
$browser = mysql_real_escape_string($browser);
$os = mysql_real_escape_string($os);
switch($browser){
case "Internet Explorer":
$IE += 1;
break;
case "Firefox":
$Firefox += 1;
break;
case "Safari":
$Safari += 1;
break;
case "Opera":
$Opera += 1;
break;
case "Chrome":
$Chrome += 1;
break;
default:
$otherb += 1;
break;
}
switch($os){
case "Windows":
$Windows += 1;
break;
case "Mac OS X":
$Mac += 1;
break;
case "Linux":
$Linux += 1;
break;
case "Android":
$Android += 1;
break;
case "iOS":
$iOS += 1;
break;
default:
$otheros += 1;
break;
}
$q = $this->query("INSERT INTO " . DB_STATS . " VALUES (null, '$ip', '$Chrome', '$IE', '$Firefox', '$Opera', '$Safari', '$otherb', '$Windows', '$Mac', '$Linux', '$Android' , '$iOS' , '$otheros', 1)");
if ($q == true){
return(1);
}
else{
return(0);
}
}
else if (mysql_num_rows($q1)==1){
extract(mysql_fetch_array($ql));
switch($browser){
case "Internet Explorer":
$IE += 1;
break;
case "Firefox":
$Firefox += 1;
break;
case "Safari":
$Safari += 1;
break;
case "Opera":
$Opera += 1;
break;
case "Chrome":
$Chrome += 1;
break;
default:
$otherb += 1;
break;
}
switch($os){
case "Windows":
$Windows += 1;
break;
case "Mac OS X":
$Mac += 1;
break;
case "Linux":
$Linux += 1;
break;
case "Android":
$Android += 1;
break;
case "iOS":
$iOS += 1;
break;
default:
$otheros += 1;
break;
}
$totalVisits += 1;
$q = $this->query("UPDATE " . DB_STATS . " set Chrome='$Chrome', IE='$IE', Firefox='$Firefox', Opera='$Opera', Safari='$Safari', otherb='$otherb', Windows='$Windows', Mac='$Mac', Linux='$Linux', Android='$Android' , iOS='$iOS' , otheros='$otheros', totalVisits='$totalVisits'");
if ($q == true){
return(1);
}
else{
return(0);
}
}
else{
return(-1);
}
}
I hope everything made sense and that someone will help.
I see it now -- you used $ql (lower case L) when you intend to use $q1. Let this be a lesson against using very short variable names or very similar names.
// $ql was initialized to 0
$ql = 0; $totalVisits = 0;
// $q1 holds the result resource
extract(mysql_fetch_array($q1));
It is not advisable to call extract() on the output of mysql_fetch_array() unless you also specify the second parameter MYSQL_ASSOC as the fetch type. By default it returns both numeric and associative indices for each column.
extract(mysql_fetch_array($q1, MYSQL_ASSOC));
// Or better
extract(mysql_fetch_assoc($q1));
In general, I would probably advise against using extract() in most any situation, since it results in numerous variables dumped into the global namespace, in particular when you have done SELECT * without being specific about which columns are selected. Better to access them via their array:
$row = mysql_fetch_assoc($q1);
echo $row['browser'];

Categories