When using this PHP code
$random = 00000; //a random int
$gameCode = $random;
$players = 0; //An example number
echo "<h4>$players Players</h4>";
while(true) {
sleep(1);
$sql = "SELECT id FROM gamecode WHERE gamecode = '$gameCode'";
$result = $conn->query($sql);
if ($result->num_rows != $players) {
$players = $result->num_rows;
echo "<h4>$players Players</h4>";
flush();
}
}
I am 99% the variables cant be found as i get an error saying that it is not an object and it works when i define the variable in the while loop. (Which i cant do for reasons)
Notice: Trying to get property of non-object in /storage/ssd4/654/2919654/public_html/createcode.php on line (Lines trying to use $players and $gamecode)
Thanks
The only thing that should be an object in there is $result, I expect that the query has failed and $result == false
When you call $result->num_rows that will fail with the error message you are seeing.
Try adding this test in
$result = $conn->query($sql);
if (!$result) {
die('Something broke');
}
Related
Image for reference I just dont get where I am wrong. Can somebody help me with this? I feel stupid right now
function total_price() {
$total = 0;
global $con;
$ip = getIp();
$select_price = $con->query("SELECT * from shoppingcart WHERE IP_address='$ip'");
while($row = $select_price->fetch_assoc()) {
$pro_id = $row['Product_id'];
$quan = $row['Quantity'];
$query = $con->query("SELECT * FROM products WHERE prod_id='$pro_id'");
while($row2 = $query->fetch_assoc()) {
$row2['product_price'] *= $quan;
$productprice = array($row2['product_price']);
$values = array_sum($productprice);
$total += $values;
}
}
echo "₱: ".$total;
}
I think there your $con->query(...) fails and so you $select_price is FALSE and not an object with some member functions.
Check Out the documentation of $mysqli::query
http://php.net/manual/en/mysqli.query.php
If you want to get the sql error print the Result of $con->error.
For example:
$select_price = $con->query("SELECT * from shoppingcart WHERE IP_address='$ip'");
if($select_price == FALSE) {
echo "SQL-Error:".$con->error
exit;
}
while($row = $select_price->fetch_assoc()) {
...
if fetch_assoc fails there is a problem with your result set.
Problem ist that:
$query
or
$select_price
is not a valid Result-Set.
Reason could be that the Querys to the database fails.
you can check this by doing:
print_r($select_price);
print_r($query);
Should Output: Ressource ID #XX -> if not, check your Query direct agains SQL.
hope this helps
I have an error Undefined variable return data.
<?php
function getData() {
$query = "SELECT * FROM `$this->tablename` ORDER BY `id` DESC";
if(!$sql = mysql_query($query))
{
echo mysql_errno();
}
else
{
$num = mysql_num_rows($sql);
if($num > 0)
{
for($i = 0; $i < $num; $i++)
{
$data[$i] = mysql_fetch_array($sql);
}
}
}
return $data;
}
?>
Define $data outside of the for loop.
function getData() {
$query = "SELECT * FROM `$this->tablename` ORDER BY `id` DESC";
$data = array();
if(!$sql = mysql_query($query))
...
PS: Stop using mysql_* functions. Switch to either MySQLi or PDO.
The problem is pretty clear. $data is not initialized properly under specific circumstances:
When the if statement "if(!$sql = mysql_query($query))" is true $data is never set
When the if statement "if($num > 0)" is false (aka $num <= 0) $data is never set.
Thus you get a notice that data is undefined as it only gets set if the first if is false and the second if is true.
To correct this and get rid of the message you need to initialize $data at the beginning of the function.
I'm working on a function that displays data but I keep getting warning "Variable 'data' might have not been defined"
function getAllData() {
$query = "SELECT * FROM patient, person WHERE patient.Patient = person.Personnummer ";
if(!$sql = mysql_query($query)) {
throw new exception("Error: CAn not execute the query.");
} else {
$num = mysql_num_rows($sql);
if($num>0)
{
for($i=0; $i<$num; $i++)
{
$data[$i] = mysql_fetch_array($sql);
}
}
}
return $data; //<--Variable 'data' might have not been defined
}
I guess it is your IDE that is giving you that warning, not php when you execute your script (it might, but the warning would be different).
To avoid it, make sure it is always defined:
function getAllData() {
$data = array();
$query = "SELECT * FROM patient, person WHERE patient.Patient = person.Personnummer ";
...
Now an empty array will be returned from your function if for example no rows are found. In your current code, php would generate a warning at run-time about an undefined variable when you run your script and no rows are found.
These lines are from a php function on a web server, the client is an ios app,
I get an error on the result2 query
$result = query("SELECT field1 FROM table1 WHERE field2='%s' limit 1", $value);
$row = mysql_fetch_array($result);
$result2 = query("SELECT field2 FROM table1 WHERE field3='%s' limit 1", $row['field1']);
on Xcode I get the error (in json):
{
error = "The operation couldn't be completed. (Cocoa error 3840.)";
}
here is the definition of the function query
//executes a given sql query with the params and returns an array as result
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
what's wrong with that query?
thanks
You are using mysqli_ functions in your query() function yet you are trying to use mysql_fetch_array() to get the results. You need to use: mysqli_fetch_array()
http://www.php.net/manual/en/mysqli-result.fetch-array.php
Actually it looks like your query() function does it for you. You shouldn't need to use a function at all. Look at this section of your query() function:
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
However not sure why it says it is json cause it is just a normal array not a json array. So you should just use this in your code:
$row = $result['result'][0];
This will get the first row.
maybe you have to json_encode the result?
//return json
return json_encode(array('result'=>$rows));
I've been trying to get a series of nested loops working to select the database name from one table then query the selected table in that database, and add up the results and display the number of them and the database name.
I have gotten the code to work but it keeps displaying:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in
I have tried every way possible I have found online to help, but none work.
$resulta = mysql_query("SELECT dbname AF012 FROM Customer");
while($data = mysql_fetch_array($resulta))
{
$db = $data[' dbname '];
$result = null;
$result2 = mysql_query("SELECT changemade FROM $db.orders");
//looping through the results
while($row = mysql_fetch_array($result2))
{
//checking if any record is 1,2 or 3
if( ($row[‘changemade’]== 1) || ($row[‘changemade’]== 2) || ($row[‘changemade’]== 3) ) {
//if any match the if adding 1 to the counter
$counter ++;
}
}
unset($result2);
echo $db." ".$counter;
echo "<br>";
$counter = 0;
$result = null;
$result2 = null;
}
All the database connections are made and work fine, so it has nothing to do with that. Any help would be great.
You need to introduce error handling, also you can streamline your code. The current point of failure is querying the database and fetching from it, so you can encapsulate it into a function of it's own which will also reduce your code:
function mysql_query_array($query)
{
if (!$result = mysql_query($query)) {
throw new Exception(sprintf('Invalid query "%s", error: %s.', $query, mysql_error()));
}
return function () use ($result) {
return mysql_fetch_array($result);
};
}
With that little helper function, your code is now more compact and it has actual error handling:
$queryA = mysql_query_array("SELECT dbname AF012 FROM Customer");
while ($data = $queryA())
{
$counter = 0;
$queryB = mysql_query_array("SELECT changemade FROM {$data['dbname']}.orders");
while ($row = $queryB())
{
if (in_array($row['changemade'], range(1, 3))) {
$counter++;
}
}
printf("%s %s<br>\n", $db, $counter);
}
This is caused by the fact that mysql_query return false if the query fails, so one of your query fails and mysql_fetch_array() gets a boolean. Try changing $db = $data[' dbname ']; to $db = $data['dbname'];