If I have to query db and do something one the basis of number of rows , in mysql I simply query and I can simply query and use simply
if($result->num_rows >= 1){
but in PDO
I have to
make count query , the use fetchCloumn() to get count
query again to get the same result and do whatever I want
Rowcount is not helpful , it doesn't work on select
so I am making query twice, PDO doesn't sounds to be helpful here, is my approach wrong or I am right?
Thanks
IMHO, counting all the rows returned by the query (or issue a second query) just to find out if there are rows or not is kind of overkill.
$got_data = false;
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$got_data = true;
process_row($row);
}
if (!$got_data) {
no_results();
}
If you do need the rowcount, it's trivial to get it while reading the result set:
$num_rows = 0;
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$num_rows++;
process_row($row);
}
if ($num_rows==0) {
no_results();
}
YMMV.
Related
I have been doing MYSQL just fine for a while now but am trying to learn how to do all that i know with PDO; what I am struggling with now is a simple SQL select, and then I loop through all the rows and dump the corresponding column values into a variable; and then I can do something with the variables for that row while in the loop; here is the way I used to do it with mysql:
$result42 = mysql_query("SELECT * FROM members");
while($row = mysql_fetch_array($result42, MYSQL_BOTH))
{
$user_id=$row['user_id'];
$user_name=$row['user_name'];
$email=$row['email'];
// do something with info for each user; like maybe echo their info...
}
I am attempting to do the same thing with PDO but not finding anything quite like what I am trying to do…
I found some code which uses fetchall and fetchassoc and seems to be putting it in an array; but I have no idea how to loop through the array and get each value on the row like i did with mysql above; and I am not even sure if the PDO that i have here can do that…
this is what I have:
$stmt = $dbh->prepare("SELECT * FROM members");
$products = array();
if ($stmt->execute()) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$products[] = $row;
}
}
All i want to do is end up cycling through each row getting the values, doing something with them and then moving on to the next row…
Can anyone help with this? Thanks...
If I want to count one specific row (unread) in my database, how should i proceed with this MySQL query? As of now it counts the whole table.
$result_notifications = mysql_query("select count(1) FROM bhost_notifications where taker_id='$user_info[u_id]'");
$row_notifications = mysql_fetch_array($result_notifications);
$total_notifications = $row_notifications[0];
You need to alias the column.
SELECT COUNT(1) AS count ...
Then you would call $row_followers[count]. Be aware that mysql_ functions are deprecated. Learn about prepared statements when passing variables, and use PDO or MySQLi - this article will help you decide which.
I suspect you have an un-normalized database. While that is preferable in some situations, I doubt that they are in yours. As written you cannot be sure that the query will return the row you desire. SQL does not guarantee the order of rows, unless you use an order by clause.
It seems like this question indicates more problems the some syntax issues.
Over time I have written a nice function in PHP that allows me to easily look up records but still be dynamic enough to be useful in every type of query that I perform.
Usage:
if (get("select * from table", $query_array) > 0)
{
// There is at least one row returned
$result_array = mysql_fetch_array($query_array);
.
.
.
} else {
// No rows in the set
}
Function:
function get($sql, &$array)
{
$array = "";
$q = mysql_query($sql);
if (mysql_error())
{
$ret = -1;
print "<div><font style='font-family: arial; font-size: 12px;'><font style='color: red;'>Error:</font> " . mysql_error() . "<br>SQL: #sql</font></div>";
exit(1);
} else {
$ret = mysql_num_rows($q);
if ($ret > 0)
{
$array = $q;
}
}
return $ret;
}
This also gives a formatted error message in the case that there is something wron with the query. I use this all the time because it compresses the mysql_query and mysql_num_rows together into a single command.
Here is a simple scenario I am contemplating. I have a query that is executed on a MySQL database from PHP. I would like to check if any data was returned from the query. However, in order to perform that check, it pulls out one of the rows of returned data.
Look at this example, and its comments:
$booksGrabber = ("SELECT * FROM table");
if (!$booksGrabber) {
//Query failed, perhaps a syntax error
exit;
}
if (!mysql_result($booksGrabber, 0)) {
//No data was returned :(
exit;
}
while ($book = mysql_fetch_assoc($booksGrabber)) {
//mysql_result() stole the first row of returned data
//So if I was expecting the loop to display 4 results,
//I only get 3...
}
How can I check if data was returned from the database without running two queries (one to check, the other to display all of the data) or having one of the rows stolen?
Use mysql_num_rows. It was as simple as it looked.
EDIT: If you want more complicated, add mysql_data_seek($booksGrabber,0).
Simple: mysql_query() function that runs the query will return false on error and then you can use mysql_num_rows() for the count. So you can do something like:
$result = mysql_query('SELECT * FROM table');
if (!$result) {
print('Invalid query: ' . mysql_error());
} elseif (mysql_num_rows() == 0) {
print("no results");
} else {
// You can use safely data from the query :)
}
A while ago I was poking around with SQLite, trying to port some of my sites to use it instead of MySQL. I got hung up on the lack of a function to count results, like PHP's mysql_num_rows(). After searching a little I discovered this mail list, which says (as I understand it) that SQLite doesn't have that functionality because it's inefficient. It states that it is bad form to write code that needs to know how many rows are returned.
I generally use mysql_num_rows to check for empty return results. For example:
$query = "SELECT * FROM table WHERE thing = 'whatever'";
$results = mysql_query($query);
if (mysql_num_rows($results)) {
while ($row = mysql_fetch_array($results)) {
echo "<p>$row[whatever]</p>";
}
} else {
echo "<p>No results found</p>";
}
The vehement distaste for the concept of mysql_num_rows() in the SQLite community makes me wonder if it's that terribly efficient for regular MySQL in PHP.
Is there a better, more accepted way for checking the size of a MySQL result set in PHP besides mysql_num_rows()?
EDIT:
I'm not just using mysql_num_rows to get the count--I would use a COUNT query for that. I'm using it to check if there are any results before outputting everything. This is useful for something like displaying search results - it's not always guaranteed that there will be results. In SQLite world, I have to send one COUNT query, check if there is something, and then send a SELECT query to get everything.
You already have something that is telling you if you've got results in mysql_fetch_array(). It returns false if there are no more rows to fetch (from php.net).
$query = "SELECT * FROM table WHERE thing = 'whatever'";
$results = mysql_query($query);
if($results) {
$row = mysql_fetch_array($results);
if($row) {
do {
echo "<p>{$row[whatever]}</p>";
} while($row = mysql_fetch_array($results));
} else {
echo "<p>No results found</p>";
}
} else {
echo "<p>There was an error executing this query.</p>";
}
Regardless of whether or not you actually use what you SELECTed, all of the rows are still returned. This is terribly inefficient because you're just throwing away the results, but you're still making your database do all of the work for you. If all you're doing is counting, you're doing all that processing for nothing. Your solution is to simply use COUNT(*). Just swap COUNT(*) in where you would have your SELECT statement and you're good to go.
However, this mostly applies to people using it as a complete substitute for COUNT. In your case, the usage isn't really bad at all. You will just have to manually count them in your loop (this is the preferred solution for SQLite users).
The reason being is in the underlying SQLite API. It doesn't return the whole result set at once, so it has no way of knowing how many results there are.
As explained on the mailing list you found. It is inefficient to return the count of rows because you need to allocate a lot of memory to hold the entire (remaining) result set. What you could do, is to simply use a boolean to test if you have output anything.
$query = "SELECT * FROM table WHERE thing = 'whatever'";
$results = mysql_query($query);
$empty_result = true;
while ($row = mysql_fetch_array($results)) {
echo "<p>$row[whatever]</p>";
$empty_result = false;
}
if ($empty_result) {
echo "<p>No results found</p>";
}
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)
{
//...
}