The following snippet of SQL returns the results that I want for any number of entries until I insert a row with the value 0 for cumulative score. Once I do this I get no results returned. cumulativescore is an INT field with no constraints on it.
$stmt = $dbh->prepare("
select
cumulativescore
from
reporting
order by
cumulativescore asc
");
UPDATE
I think what's happening is that when I use the following code, fetchColumn returns 0 for the first column as it's in ascending order and this breaks my loop. By no results I meant $arr was empty but from this example I have learned that that wasn't the best way to test the query. How can I use fethchColumn and have 0 values? Or do I need to fetch as an associated array and get the value that way? As a sidenote, what's the most appropriate way to test PDO result sets for values/etc?
while($tmp = $stmt->fetchColumn()){
$arr[] = $tmp;
}
while(($tmp = $stmt->fetchColumn()) !== false){
$arr[] = $tmp;
}
three equal signs also check the type of the variable. This is true if the function returns not false exactly. If it returns 0 this is true.
Related
When I'm trying to get the number of rows on a SQL request and if not, the connection that follow fails.
But in any case (also if the request should return 0), it returns 1.
Here's my code :
$str = 'SELECT count(*) FROM admins WHERE mail = ? AND mdp = ?';
$arr = array($mail, $pass);
$rqt = sendRqt($str, $arr);
$tab = $rqt->fetchColumn();
$cnt = count($tab);
echo $cnt;
I don't understand why there's no time it returns 0
The problem is the use of the php function count().
You already have the correct number in your $tab variable as a string (probably, depends on php configuration / version) so you can echo it or cast it to an integer to make sure it is a number.
However, in php:
count(0) === 1
count('0') === 1
See here for example.
You should remove count($tab).
the SQL "COUNT(*)" allways returns a row with the count (quantity) of values, so if you apply the php count() function, always will return 1 because there is one row that contains the value of the COUNT sql function
I believe COUNT() needs a column name.WRONG!! count(*) should count all rows, but I still reccomend a column name like id or something. You could also use an AS to make life a little easier
$str = 'SELECT count(`COLUMNNAME`) AS cnt FROM table WHERE ....
I am trying to get a count, using this query:
$count = $entityManager->getRepository('Model:Machine')
->createQueryBuilder('m')
->select('COUNT(m.id)')
->where('m.number = :number')
->setParameter('number', $value)
->getQuery()
->getSingleScalarResult();
If I use a $value that I know exists, then $count returns as 1.
If I use a value that I know does NOT exist, then $count is empty.
Why isn't it set to 0?
Thanks
getSingleScalarResult works different that you might think.
It expects to get a simple data from query and cast it to an integer.
When query couldn't get machines with number equal to parameter, there are no results, so results variable is empty.
I'm using the following code to find the number of rows returned:
global $wpdb;
$results = $wpdb->get_results("SELECT * FROM list WHERE queue = 1 ORDER BY id ASC LIMIT 0,1");
$rowcount = $results->num_rows;
echo $rowcount;
As you can see, the results are limited to 1 row, and when I run this query in SQL it returns 1 row just fine. But in PHP the $rowcount doesn't return any value at all.
Any ideas what might be wrong? I get no error.
I think you need to use count($results) since the method $wpdb->get_results returns a array of objects/arrays.
Another way to get the number of rows is to use $wpdb->num_rows. Apparently this works for
$wpdb->get_results.
From the docs (http://codex.wordpress.org/Class_Reference/wpdb), it says the following about get_results:
Generic, multiple row results can be pulled from the database with
get_results. The function returns the entire query result as an array.
Each element of this array corresponds to one row of the query result
and, like get_row, can be an object, an associative array, or a
numbered array. If no matching rows are found, or if there is a
database error, the return value will be an empty array. If your
$query string is empty, or you pass an invalid $output_type, NULL will
be returned.
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
}
I am trying to get a count and I am getting 1 instead of 0 from it. I have looked thoroughly though the web and this site. I have even been trying to figure it out on my own for a long time. I keep coming empty handed here.
So Basically what I am trying to do is make a like system for my users. I can get everything to work correctly the count works except for one thing. When they have liked it it returns 1 not 0 which it should be.
Here is my code for the count. I am not posting all the coding for security reasons and it really doesn't need to since its about the counting part not the rest.
$sql_like = mysql_query("SELECT * FROM posts WHERE mem2_id='$id' ORDER BY post_date DESC LIMIT 40");
while($row = mysql_fetch_array($sql_like)){
$like1 = $row['like_array'];
$like3 = explode(",", $like1);
$likeCount = count($like3);
}
So here is the code that determines the number. Any ideas what is wrong with this? Why its returning 1 not 0 when the item is empty?
// you do escape your id right??? (sql injection prevention)
$sql_like = mysql_query("SELECT * FROM posts WHERE mem2_id='$id' ORDER BY post_date DESC LIMIT 40");
while($row = mysql_fetch_array($sql_like)){
$likeCount = 0;
$like1 = trim($row['like_array']);
if ($like1) {
$like3 = explode(",", $like1); // exploding emtpy string would result in array('')
$likeCount = count($like3);
}
}
Calling explode on an empty string gives an array containing the empty string. This is one element, not zero.
I would suggest that you change your database design if possible so that you don't store the values separated by commas. Use a separate table instead.
If you can't change the database design you can handle the empty string separately.
count() returns the number of indexes in an array or something in an object (PHP: count - Manual).
if a string var is used rather than an array or object it returns 1. it has to get a null value in order to return 0.
you can give it a go by trying:
print count("");
and
print count(null);
You'll have better luck if you use explode() to break the sql output into an array and then run a check with an if statement. Something like the following:
$like3 = explode(',',$like1);
if (count($like1)=1 && $like1[0] == '')
// etc ..
I hope this helps