Counting num_rows issue - php

I have a query like this:
SELECT * FROM configurations WHERE ID = userID
I then have logic like this:
if ($query->num_rows() > 0) {
foreach($query->result() as $row) {
// display data
}
else {
// display no data found message
}
But when I try to do this:
count($query->num_rows())
it is always 1, no matter how many results are returned. If 1 or more are returned the "if" is executed. If there are no results returned the "else" is executed. Yet, the count never changes. What is going on?

You can't count() a number, it works fine. If you only want number of records from table use COUNT() in SQL...
$sql = mysql_query("SELECT COUNT(0) AS count FROM configurations WHERE ID = userID");
$sql = mysql_fetch_assoc($sql);
$count = $sql["count"];
Otherwise just assign $count = $query->num_rows(); as #chriso stated.

Firstly else { should be } else { - you're missing a brace
Secondly, count() is used to count the number of elements in an array. Since $query->num_rows() returns a number rather than an array, you don't need to use count(). In your case, count() was telling you that there's one number, not what the actual number was!
Try:
$count = $query->num_rows();
echo $count;

You're getting an integer with $query->num_rows(), so when you run that integer through the count() function it is designed to return 1.
http://us2.php.net/manual/en/function.count.php
If var is not an array or an object
with implemented Countable interface,
1 will be returned. There is one
exception, if var is NULL, 0 will be
returned.

Related

I have an issue, and I cant figure it out.... Mysql COUNT() returns 0 but returns correct when run in phpmyadmin

I'm sorry to have to post this, I know it seems similar to other posts, so I ask you to please bear with me...
What I am trying to do: I have a sql query that is in a function, the point of the function is to find if there are TinyInts of a particular value (1 or 0), I am doing a count, and need to just return effectively if it found the value in the specified in the query. What should be coming back is 1 but I only get 0's back...
Here is the whole function:
//return count of VALUES
function getcountsroles($searchParams, $searchCrit){
/// does query, gets results, counts the number and returns that true or false
///this willbe used to show the dashboard user control more efficently.
// $searchParams == column
// $searchCrit == int 1 or 0
//should fetch back the count back from the query
global $db, $dashboard_message_users;
$count_Data=array();
$query = "SELECT COUNT(userID) AS countVal FROM roles WHERE ? = ?";
$stmnt = $db -> prepare($query);
if(!$stmnt){
echo var_dump($stmnt);
}
$stmnt -> bind_param("si", $searchParams, $searchCrit);
if(!$stmnt -> execute()){
$dashboard_message_users = "<p class='alert alert-danger'>The db query faulted.</p>";
}
$result = $stmnt -> get_result();
while ($data = $result->fetch_assoc()){
$count_Data[] = $data;
}
$test = 'userID';
$value = (int)($data['countVal']);
echo var_dump($test);
echo var_dump($searchCrit);
echo var_dump($searchParams);
echo var_dump($value);
echo var_dump($count_Data);
if ($value > 0){
return true;
}else{
return false;
}
}
The calling function sends the column to count the values of, and the the value that we are looking for. when I run the query against the database I get the correct values, I have tested with different columns and values (again 1 or 0)
SELECT COUNT(*) as 'countVal' FROM roles WHERE isUser = 1;
SELECT * FROM roles WHERE isUser = 1;
SELECT * FROM roles;
SELECT COALESCE(COUNT(isUser),0) AS totid FROM roles;
the first one returns 2, the second is all the rows where isUser is value of 1,
third grabs all rows... and the last one was a attempt to see if it was going work... but it still only returns 0 to the result... I have also tried to get the count of rows should be 1, either if true or false... This i getting annoying, Unfortunately I happen to be using mysqli lib and most exampled are for POD or old mysql_PHP, and in OO it seems to not like the prepared statements.
I am positive its something I am doing, I have looked over and over my code and I cant see what the issue is... Maybe if a fresh pair of eyes.
Any time or replies that help me and others out would be greatly appreciated.
Jesse Fender

what is the official value of an empty sql result(from a loop)

What I mean is, for example, if I search for something on an SQL table, and it returns 0 / nothing, is that null or empty or does it result in an empty ""?
I'm getting back into php and trying to loop through a db like so:
Pseudo code:
while($row = mysqli_fetch_array($var here that has the query to the db and connection)){
echo $row[//something pulled from table to be read back]
}
But let's say that the search query didn't return any results or that $row doesn't equal to anything because for whatever reason, the value searched for in the db doesn't exist,
How then can I check for the empty-ness of row?
if the searched for item doesn't exist in the db, then $rows value becomes what exactly? null/empty/or empty string or something else?
depending on the value of row, do I test for [isset / !isset] or [empty / !empty] ? Or is the only way to test for empty $row to do a (pseudo) $x =mysqli_num_rows(var here) / if ($x == 0 ) //do something?
If mysqli_fetch_array did not return anything, then the return value is NULL
The line while($row = mysqli_fetch_array is supposed to return the next available record in the record set, so if the query did not give any matching results, then the line echo $row['something'] does not get executed at all.
If there are multiple fields you are fetching, say field1, field2 and supposing field2 doesn't have a value, then what is returned for that field is what the default value for that field will be in MySQL (or whichever DB you are using). However the point to note is that $row will still have two keys defined correctly as $row['field1'] and $row['field2']
If you want to check if $row['field2'] does have any value you can check it using empty($row['field2']).
"", 0, NULL, FALSE, array() are all considered empty() so you should be able to safely determine if the field has any valid value in it using this function. However, if say 0 could be a valid value (for e.g. you are querying no_of_days a person was absent last month and some of them have full attendance), you will need to explicitly check the value in the field and cannot depend on empty().
You can check whether there is result using mysql_num_rows. If there is items exist in that row, the row should have show one or more or TRUE depending on the item you searched, if nothing exist in database when you executed the query means the mysql_now_rows will show you 0/NULL.
You can do like
$query = mysql_query("YOUR QUERY HERE");
$numrow = mysql_num_rows($query);
if ($numrow == 0)
{
ECHO "No result found.";
}
When there's nothing, $row == false
That's the correct test on the while loop!
You can use mysqli_num_rows to fetch the number of results found by a query.
$query = 'SELECT `blah`';
$result = mysqli_query($query);
if(mysqli_num_rows($result) > 0) {
// do stuff here if any rows are found
} else {
// do stuff here if NO rows are found
}

PHP mySQL 404 function

The following function is designed to check whether this row in this tables exists. I know that it does not yet whether I $row or !$row the if function it does not do anything.
function four_zero_four($name){
$four_zero_four = mysql_query("SELECT * FROM pages WHERE name = '$name'");
while($row = mysql_fetch_array($four_zero_four)) {
echo 'no'; die();
}
};
$name is the name field from the row and is working correctly in other functions.
Another way to check whether a row exists is by using the mysql_result function in conjunction with the COUNT function as such:
$query = mysql_query("SELECT COUNT(1) FROM `table` WHERE `field` = 'something'");
$result = mysql_result($query, 0);
When you now print out the $result variable, you will see the amount of rows that are actually being returned by the query. This is generally faster than using mysql_num_rows.
I'm not sure I understand the logic, aren't you printing "no"; die() when there IS a row found, instead of when now row is found? Either way, here's how I would check:
function four_zero_four($name){
$four_zero_four = mysql_query("SELECT * FROM pages WHERE name = '$name'");
if (mysql_num_rows($four_zero_four) == 0) {
// ROW DOES NOT EXIST
} else {
// ROW EXISTS
}
};
Your code does not work because it wont even be executed if there is no row returned by your query.
Use mysql_num_rows() instead:
$count = mysql_num_rows($four_zero_four);
if($count <= 0){
die("no rows in this table!");
}
Also, you should maybe consider to use MYSQLi commands instead of the old mysql_query() implementation and SELECT *, as they are deprecated.

mysql_fetch_array() timing out

I am trying to query a database, but it seems to just load for an age and not do anything. It's a simple query and shouldnt take longer than a millisecond.
while($row = mysql_fetch_array(getWallPosts($userid)))
{
}
Now when I replace this code with:
echo mysql_num_rows(getWallPosts($userid));
It just displays '1' in fact there's only one record in the DB and it's just a simple SELECT statement.
Here's the getWallPosts function:
function getWallPosts($userid, $limit = "10")
{
$result = dbquery("SELECT * FROM commentpost
WHERE userID = ".$userid."
ORDER BY commentPostID DESC LIMIT 0, ".$limit);
return $result;
}
Also, when I put the SQL string that it's executing into MySQL's query browser. It takes no time at all.
Any ideas?
You appear to be looping indefinitely because you're retrieving a new set (one record) of data each time.
$result = getWallPosts($userid);
while ($row = mysql_fetch_array($result)) {
//printf($row[0]);
}
You need to get the data once and loop through it. Your code is getting the data, running the loop and then getting the data again.
Try:
$posts = getWallPosts($userid);
while($row = mysql_fetch_array($posts))
{
//Code to execute
}
Its an infinite loop. The expression in the while always executes so it will always be true.
You're returning a new result set each time the while statement executes. You should call getWallPosts first, assign it to $results, and then loop over it.

Whats the proper way to check if mysql_query() returned any results?

I tried what seemed like the most intuitive approach
$query = "SELECT * FROM members
WHERE username = '$_CLEAN[username]'
AND password = '$_CLEAN[password]'";
$result = mysql_query($query);
if ($result)
{ ...
but that didn't work because mysql_query returns a true value even if 0 rows are returned.
I basically want to perform the logic in that condition only if a row is returned.
Use mysql_num_rows:
if (mysql_num_rows($result)) {
//do stuff
}
If you're checking for exactly one row:
if ($Row = mysql_fetch_object($result)) {
// do stuff
}
You can use mysql_fetch_array() instead, or whatever, but the principle is the same. If you're doing expecting 1 or more rows:
while ($Row = mysql_fetch_object($result)) {
// do stuff
}
This will loop until it runs out of rows, at which point it'll continue on.
mysql_num_rows
Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set.
If none match, then zero will be the return value and effectively FALSE.
$result = mysql_query($query);
if(mysql_num_rows($result))
{ //-- non-empty rows found fitting your SQL query
while($row = mysql_fetch_array($result))
{//-- loop through the rows,
//-- each time resetting an array, $row, with the values
}
}
Which is all good and fine if you only pull out of the database. If you change or delete rows from the database and want to know how many were affected by it...
To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
$result = mysql_query($query);
if(mysql_affected_rows())
{ //-- database has been changed
}
//-- if you want to know how many rows were affected:
echo 'Rows affected by last SQL query: ' .mysql_affected_rows();
mysql_query() will only return FALSE if the query failed. It will return TRUE even if you have no rows, but successfully queried the database.
$sql = "SELECT columns FROM table";
$results = mysql_query($sql, $conn);
$nResults = mysql_num_rows($results);
if ($nResults > 0) {
//Hurray
} else {
//Nah
}
This should work.
I used the following:
if ($result != 0 && mysql_num_rows($result)) {
If a query returns nothing it will be a boolean result and it's value will be 0.
So you check if it's a zero or not, and if not, we know there's something in there..
HOWEVER, sometimes it'll return a 1, even when there is nothing in there, so you THEN check if there are any rows and if there is a full row in there, you know for sure that a result has been returned.
What about this way:
$query = "SELECT * FROM members WHERE username = '$_CLEAN[username]'
AND password = '$_CLEAN[password]'";
$result = mysql_query($query);
$result = mysql_fetch_array($result);
//you could then define your variables like:
$username = $result['username'];
$password = $result['password'];
if ($result)
{ ...
I like it because I get to be very specific with the results returned from the mysql_query.
-Ivan Novak
well...
by definiton mysql_query:
mysql_query() returns a resource on
success, or FALSE on error.
but what you need to understand is if this function returns a value different than FALSE the query has been ran without problems (correct syntax, connect still alive,etc.) but this doesnt mean you query is returning some row.
for example
<?php
$result = mysql_query("SELECT * FROM a WHERE 1 = 0");
print_r($result); // => true
?>
so if you get FALSE you can use
mysql_errorno() and mysql_error() to know what happened..
following with this:
you can use mysql_fetch_array() to get row by row from a query
$result = mysql_query(...);
if(false !== $result)
{
//...
}

Categories