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.
Related
This is probably a silly beginner question and i don't think it's limited to mysqli_fetch_assoc() so it's probably a general programming question.
Anyways, i have this PHP code for getting data from a database using mysqli
$sql = "SELECT name FROM table1";
$result = mysqli_query($conn, $sql);
if($result){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
echo "Name: " . $row["name"]. "<br>";
}
}
}
What i don't understand is how the while loop there works. How does it iterates to the next element and know when to end? mysqli_fetch_assoc() returns a associative array which is stored in row variable which means it is not null therefore true and let's the while loop run. What i don't understand is how it iterates through the rows and ends when there are no more rows left. I'm not specifically doing anything to change the row to the next one so how does it do it on it's own?
Also mysqli_fetch_assoc() returns a associative array so shouldn't "name" key contain 1 element? Or is it a array of all the rows in that column?
(I hope you can understand what i'm trying to say, i'm not the best at explaining .-.)
Edit: What i don't understand is how this code iterates through all the rows. Is it part of the "inbuilt code" in this function? (I couldn't find it anywhere to confirm)
Each time when
mysqli_fetch_assoc($result) is accessed, the pointer moves to the next record. At last when no records are found, it returns null which breaks the while condition.
Eventually, when mysqli_fetch_assoc($result) runs out of rows it will return NULL, which evaluates to false, which breaks out of the loop.
$row results in a single row in the database, so $row['name'] would be the value of 'name' for a particular row.
Let's break it down, with perhaps a dumbed down example of how it works internally (Please note, this works a lot more efficiently, and wont actually run multiple queries):
$result = ['currentRow' => 0, 'query' => 'SELECT name FROM table1'];
while ($row = mysqli_fetch_result($result)) {
}
//First iteration
mysqli_fetch_result queries 'SELECT name FROM table1 LIMIT 0, 1'
it increments internally $result['currentRow'] to 1
it returns the row that was found
//Second iteration
mysqli_fetch_result queries 'SELECT name FROM table1 LIMIT 1, 1'
it increments internally $result['currentRow'] to 2
it returns the row that was found
//Third iteration
mysqli_fetch_result queries 'SELECT name FROM table1 LIMIT 2, 1'
no rows returned! Just simply return null (This will cause your while loop to break out)
You always pass $result as an argument to mysqli_fetch_assoc. This argument holds the iterator information, which will be used by mysqli_fetch_assoc to advance each time you call this function to the next row.
During each iteration, $row['name'] will be a single string.
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.
$q = "SELECT * FROM user";
$res = mysqli_query($conn, $q) or die(mysql_error());
$userList = "";
while($user = mysqli_fetch_array($res))
{
$userList .= $user['userList'].";;";
}
echo $userList;
I don't understand the while part:
Why assign the mysqli_fetch_array to $user using while?
How can the $user have index of userList?
Why concatenate with ;;?
To answer your questions:
i) mysqli_fetch_array() has two possible return values. It either returns an array of the current row that the database result set pointer points to, then advances the pointer to the next row, or it returns false if you have reached the end of the result set. The while() evaluates the value that is set to $row either continuing the loop if it is an array or stopping the loop if $row equals false
ii) The $user array has both numerical indexes for each field (i.e. 0,1,2,... [#fields - 1]) and associative indexes of the column names for the table (i.e. 'field1', 'field2', etc.). In this case one of the fields in the database is userList, so accessing $user['userList'] returns that column value for the row being worked with. BNote that the query itself would have beeter been written as SELECT userList FROM user since that is the only field you are interested in. There is no reason whatsoever to select and transfer all field data if you have no need for it. It is also rarely useful to use just mysqli_fetch_array(), as you rarely need both numerical and associative indexes on the record.It is usually best to specifically request ther associative or numerical array result depending on which you need.
iii) This code is simply building a string rather than an array of results which might be more common. For whatever reason the code writer decided values in the string should be separated by ;;.
I am querying a database for the latest row entered and get the id column only, so I am sure I will get one value. However, I am unable to print the variable unless it is in a foreach loop, not even accessing the 0th element is giving me any output.
I use this line of code for querying the latest row's id added: $id = $db->query("SELECT MAX(id) FROM FM;");
When I use the foreach loop, I get the following output:
Loop:
foreach ($id as $i)
print_r($i);
Output:
Array ( [MAX(id)] => 20 [0] => 20 )
However, when I use print $id[0]; or print $id["MAX(id)"]; I get the HTTP Error 500.
How can I get the single value id and put it in a variable, the id itself that is?
Thanks
I looked up in the PDOStatement reference which is returned fromt the query function, and found the fetchAll() method which returns an array of rows, and got the latest id by the following line of code: $id->fetchAll()[0][0];
Instead of selecting max(id) you have to use lastInsertId() method
$id = $db->lastInsertId();
right after calling insert query
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
}