PHP mysqli_fetch_array supposedly getting a boolean - php

$result = mysqli_query($conn,"SELECT * FROM Players");
if ($result !== FALSE) {
while($row = mysqli_fetch_array($result)) {
$result = mysqli_query($conn,"UPDATE Players SET Score='$score' WHERE ID='$id'");
}
}
This works. That is, the databse is indeed updated and everything is all cool.
But it throws a warning:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result,
boolean given
If you search around, the explanation is that the query is failing - hence, it is returning FALSE, so you get the warning.
... But this doesn't make sense in my case. The query is not failing. When I run this script, my database is updated just fine. Besides, there is also a conditional checking if the result is a boolean before using mysqli_fetch_array, so technically this warning should never happen in the first place.
Whatever, the problem must be with $result. Let's do:
echo gettype($result);
Which results in
"object"
Well, this explains why is it passing the condition. However, this still won't explain why mysqli_fetch_array insists this is a boolean (because it isn't).
What is the problem, then?
Tested with PHP Version 5.3.24 and 5.4.19.

You're overwriting the resultset $result from your SELECT query with a new $result value from the UPDATE query inside your loop
while($row = mysqli_fetch_array($result)) {
$result2 = mysqli_query($conn,"UPDATE Players SET Score='$score' WHERE ID='$id'");
}

In while loop used Same variable name '$result' which are already used before. Change variable name inside loop.
while($row = mysqli_fetch_array($result)) {
$result = mysqli_query($conn,"UPDATE Players SET Score='$score' WHERE ID='$id'");
}

The $result array returns nothing when you are updating the table. That's why, you are getting this warning in the while loop when it is trying to fetch data from $result into $row.

Related

In PHP, why doesn't mysqli_num_rows return an integer for a query with 0 returned rows?

I am having a strange issue with mysqli_num_rows. Searching for this issue, I've only found people having issues where NULL is returned no matter what. I also checked the official documentation for the function, and it says it returns an integer of the number of rows returned by the query. Whenever my query returns 1 row (it never should return more), it behaves as I expect. When the query returns 0 rows, I expect the function to return 0, but it returns NULL. Why doesn't it return 0?
I know that my database connection is good and my query works correctly, because when I look for a record that's in the database, I get an integer back. I just can't figure out why this is returning NULL rather than 0.
function getArtistID($name) {
global $conn;
$query = "SELECT artist_id FROM artist WHERE artist_name LIKE '${name}'";
$result = mysqli_query($conn, $query);
if ($result->num_rows) {
$row = mysqli_fetch_assoc($result);
return $row['artist_id'];
} else {
return 0;
}
}
Here's some code that I used to reproduce a case where num_rows seems to be NULL:
<?php
error_reporting(E_ALL);
$conn = new mysqli('127.0.0.1', 'root', null, 'test');
$sql = "SELECT * FROM dual";
$result = $conn->query($sql);
if ($result === false) {
print "Error: {$conn->error}\n";
}
$n = $result->num_rows;
echo "Dump the num_rows property: ";
var_dump($n);
Output:
Error: No tables used
Notice: Trying to get property of non-object in /Users/bkarwin/Documents/SO/my.php on line 14
Dump the num_rows property: NULL
The notice is because it's invalid to access an object-oriented property of a variable that is not an object. This is a frequent source of confusion for PHP developers, and it's a byproduct of the fact that PHP is a loosely typed language, and functions like query() can return either a result object, or a boolean scalar.
The query() function actually returned a false as $result because of some error. In my code, I checked for this error, and you didn't.
When you run mysqli::query() or mysqli::prepare() or mysqli_stmt::execute(), you must check for error conditions every time.
Something about your query caused an error. It's up to you to check for the error and report it.
Update: I edited some text above to make the explanation better, but it might make some comments below seem out of place.
I just can't figure out why this is returning NULL rather than 0.
We can only guess without seeing the log output; but, it is likely the return value is null because it raised an error instead.
You need to ensure that errors are handled when calling a function, before attempting to use the return value.

How can I fetch data from the database using mysqli_fetch_all?

if(isset($_POST['saveUserName'])){
$newUserName = $_POST['newUserName'];
$id = $_SESSION['id'];
$sql = "UPDATE users SET user='$newUserName' WHERE id='$id';";
$result = mysqli_query($conn, $sql);
$result = mysqli_fetch_all($result);
}
This code shows me the following error:
Warning: mysqli_fetch_all() expects parameter 1 to be mysqli_result, bool given in C:\xampp\htdocs\loginsystem\modify.php on line 13
Can you tell me what's wrong in this code ???
Thank you..
mysqli_query() function returns,
For successful SELECT, SHOW, DESCRIBE, or EXPLAIN queries it will return a mysqli_result object. For other successful queries it will return TRUE. FALSE on failure.
Here, $result contains true or false. That's why you got that particular error message.
The mysqli_fetch_all() function fetches all result rows and returns the result-set as an associative array, a numeric array, or both.
If you want to get a result set then you need to change the query to select or show something.

PHP - basic select query returning only the first row of mysql database

I've been running the query oh phpMyAdmin and it shows all the rows, but my query in php only returns the first row.
$result = $mydb -> query("SELECT * FROM music_sheet WHERE category='".$_REQUEST["submitter"]."'");
print(count($result)); //always returns 1
for ($x = 0; $x < count($result); $x++) {
$row = mysqli_fetch_row($result);
}
For reference, here's why count() is returning 1. From the manual:
If the parameter is not an array or not an object with implemented Countable interface, 1 will be returned. There is one exception, if array_or_countable [the parameter] is NULL, 0 will be returned.
Since $result is a resource (object) that is returned from your query, not an array which you would get within your loop getting the actual data out of the resource, count($resource) will return 1.
Your solution is of course to use mysqli_num_rows(). To retrieve data from this resource, you need to loop over it as you are doing, but either use mysqli_num_rows() in place of count(), or other (more common) ways of looping through a result set, like so:
while($row = mysqli_fetch_row($result)) {
// do stuff
}
You have to use mysqli_num_rows($result) function to count rows which are returned by MySQLi query.
Try this
echo mysqli_num_rows($result);
while($row = mysqli_fetch_row($result)) {
// write your code...
}
Use this instead of the for loop
the first thing that the query method returns to you is a resource/object. This query method always return a mysqli_result object for successful queries using SELECT, SHOW, DESCRIBE or EXPLAIN queries . For other successful queries mysqli_query() will return TRUE. For that reason it always count it as "1", what you should try is:
$result = $mydb -> query("SELECT * FROM music_sheet WHERE category='".$_REQUEST["submitter"]."'");
$numRows = $result->num_rows;
print(count($numRows)); //it should show you the total amount of rows
//verify the amount of rows before of tryng to loop over it
if ($numRows) {
while($object = mysqli_fetch_object($result)){
//for each loop you will have an object with the attributes of the row
echo $object->song_name;
}
}
This should work,
Regards.

Selecting a single field from a MySQL database for comparison of a variable

I need to get 'groupLeader' field from the table 'groups' in the database and store it in a variable and then compare to the current logged in username but I get the error:
Warning: mysql_numrows() expects parameter 1 to be resource, object given in /home/content/00/7923300/html/uber/tasks.php on line 31
The code I currently have is this:
$sq = "SELECT * FROM groups WHERE groupID='".$groupID."'";
$result=$db->query($sq);
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
$gLeader= mysql_result($result, $i, 'groupLeader');
$i++;
}
if($_COOKIE['$username'] == $gLeader) {
echo "User is leader.";
}
Forgive me if this seems like a rather simple request. I'm new to php and working with databases.
EDIT: Forgot to mention line 31 is the line that contains
$num=mysql_numrows($result);
You might need to use with PHP's mysql_query or your framework row number method.
$result = mysql_query($sq);
Or perhaps
$db->number_of_rows($sq);
The problem here is, the query is not executed properly for an unknown reason. That is why it is returning False to $result, which is really not a resource.
use:
$sq = "SELECT * FROM groups WHERE groupID='".$groupID."'";
$result = mysqli_query($connection, $sq);
or
$result = mysql_query($sq);
Most of that code is redundant and pointless. if all you want is a single field from a single row, then don't do SELECT *, and don't use a loop.
$sql = "SELECT groupLeader FROM ..."
$result = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($reuslt);
if ($row['groupLeader'] == $_COOKIE['username']) {
...
}
}
However, note that the mysql_*() function complex is officially deprecated in PHP and should not be used anymore. Consider switching to mysqli instead, which is generally drop-in compatible, or better yet, use PDO instead.

Basic PHP/MySQL Error with mysql_fetch_array()

The error I get:
...mysql_fetch_array() expects parameter 1 to be resource, boolean given...
awayid is in the address bar properly. I can print it out just fine, but for some reason the following code gives me the above error.
$result = mysql_query("select * from team where id=" . $_GET['awayid']);
$row = mysql_fetch_array($result);
EDIT Tried the mysql_error(). It seems I forgot to select a database... however, even why I use mysql_select_db('gamelydb'); I still get the mysql error No database selected
Your query is failing... Therefore $result is set to false.
$result = mysql_query("select * from team where id=" . $_GET['awayid']);
var_dump($result); // bool(false)
Call mysql_error() to get the error message for your query:
echo mysql_error();
Your query is failing and returning a boolean FALSE. Try this:
$result = mysql_query("select ...") or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^---- add this
This will kill the script and show you the exact reason the query is failing.
mysql_query() returns false if the query is unsuccessful, i.e. an error occured. That is why you need to check $result for being false first.
Use mysql_error() to output the error.
You need to be sure there is results from your query :
while ($row = mysql_fetch_array($result)) {
// echo $row[] ... ;
}
First of all, your query is very open to SQL injection attacks. Do not directly insert anything from $_GET or $_POST (or really anywhere) into your query. At the minimum, use mysql_real_escape_string on the variable.
mysql_query is returning false becuase there is something wrong with the query. You can use mysql_error to see what the last reported error is.
if ($result = mysql_query("select * from team where id='" . $_GET['awayid']) . "'") {
$row = mysql_fetch_array($result);
}
else {
echo mysql_error();
}
Anyway...you know that writing a $_GET parameter right into the SQL query is very very bad? Try it with PHP Data Objects.
Did you try and search around first Tory, we answer these questions over and over again, next time please search around.
The reason why this error occurs is because your running a query with mysql_query that fails, because it fails it returns false, you then pass the value of false to mysql_fetch_array, it's like doing mysql_fetch_array(false)
You need to make sure that mysql_query is successful:
try something like this:
if(false !== ($result = mysql_query("select * from team where id=" . $_GET['awayid'])))
{
$row = mysql_fetch_array($result);
}else
{
die("Query has failed: " . mysql_error())
}

Categories