$sql = "SELECT # FROM users WHERE onduty = 1 AND loc_id = '{$site}';";
$result = mysql_query($sql);
I simply want to test if this is true or false. If it returns 0 rows, I want next line to be something like:
if (!$result) { //do this; }
However, in my test, I am getting false when I know it should be true. Is this sound logic here?
(note, yes I know I should be using mysqli_query, that is not what I am asking here)**
ANSWER:
This is what I used:
$login_state = false;
if(mysql_num_rows(mysql_query("SELECT 1 FROM users WHERE onduty = 1 AND loc_id = '{$site}';"))) {
$login_state = true;
}
Use EXISTS:
SELECT EXISTS (SELECT 1 FROM users WHERE onduty = 1 AND loc_id = '{$site}') AS test;
Your original query would return "no row" if no row is found that matches the criteria. This one returns TRUE (1) or FALSE (0) every time.
In cases where there can be multiple rows matching the criteria and you are only interested whether at least one rows exists, performance of EXISTS is superior to a plain query. It can stop as soon as the first row is found and only returns 0 or 1.
db<>fiddle here
Old sqlfiddle
Use mysql_num_rows() to check number of rows returned on executing query.
$num_rows = mysql_num_rows($result);
if($num_rows==0)
{
//nothing returned
}
else
{
//rows returned
}
For corresponding mysqli implementation ,see mysqli_stmt_num_rows()
Related
This question already has an answer here:
PDO, MySQL SELECT statement returning boolean true?
(1 answer)
Closed 11 months ago.
I have seen similar posts to this one already existing but none of them have helped.
When I run this PHP code with $retrievestat = 1, I get a value of 1 return by the search query in php:
$retrievestat = $_POST["statIdentifier"];
echo $retrievestat;
// Retrieve The Player With The Most Rounds Won With Their Rounds
if ($retrievestat == 1)
{
$checkuniquequery = "SELECT COUNT(*) FROM playerstats WHERE roundswon = (SELECT MAX(roundswon) FROM playerstats);"; // Get number of rows that have a roundswon value equal to the max in the table
$stmt = $conn->prepare($checkuniquequery);
echo ($stmt->execute());
if ($stmt->execute() == 1) // If only one row has the max roundswon then get the username + roundswon
{
$mostroundswonquery = "SELECT username, MAX(roundswon) FROM players, playerstats WHERE players.id = playerstats.id";
$stmt = $conn->prepare($mostroundswonquery);
//echo ($stmt->execute());
}
However, when I run this query in phpMyAdmin:
"SELECT COUNT(*) FROM playerstats WHERE roundswon = (SELECT MAX(roundswon) FROM playerstats);"
I get 2 returned as the output.
Any ideas why this is happening and how to fix it?
The execute method on PDO statement ($stmt->execute()) does return either true (if execution was successful) or false if not. It does not return the return value of the SQL statement. On a side node: $stmt->execute() == 1 does behave the same as $stmt->execute() == true !
To get the actual return value you need to fetch the result after execution.
E.g. you can use $stmt->fetch() to get actual result.
Have a look at the documentation to learn more: https://www.php.net/manual/en/class.pdostatement.php
I have a table where I want to count total entries in one column. But if the entire column is empty, I want the count to return 0 (meaning there are zero entries)
This is what I tried, but when I use echo it returns blank. In the database it is blank, but I want it to return 0 when column recall is empty.
CODE:
$chartsql = "SELECT recall from report where child_id='$childId'";
$ChartRes = mysqli_query($con,$chartsql);
while ($ChartRow=mysqli_fetch_array($ChartRes)){
$recall[] = $ChartRow['recall1'];
}
foreach($recall as $index=>$value) {
if($value === null) unset($recall[$index]);
}
$count_recall = count($recall);
if($count_recall = ''){
$count_recall1 = 0;
}
echo $count_recall;
Also, in the recall column, there are null entries as well as blank entries. So I want to ignore the nulls, but if all other entries are blank then it should return zero. If there are some blank and some valid entries, then it should only count the valid entries and not what is blank.
It should only return 0 if it is completely empty, ignoring nulls.
Use SQL count function instead:
$chartsql = "SELECT count(child_id) as totalitems from report where child_id='$childId' and recall is not null and recall != ''";
$ChartRes = mysqli_query($con,$chartsql);
$ChartRow = mysqli_fetch_array($ChartRes);
$count_recall = $ChartRow['totalitems'];
Never use PHP for counting, when you can use SQL for your result, because:
When you have many rows, you will have performance issue.
You can easily do it inside your query and have cleaner codes.
Debugging is much easier.
How about count(*)
https://dev.mysql.com/doc/refman/8.0/en/counting-rows.html
$chartsql = "SELECT count(*) from report where child_id='$childId'" and recall is not null and recall != ''";
<?php
$chartsql =
"SELECT (count(id) - (
SELECT count(id)
FROM report
WHERE attributeName LIKE ''))
FROM report";
?>
All you need to do is substract the total of rows to the amout of empty rows. It should do the job
In PHP you could simplify it by:
assign only valid value to $recall array
add zero to returned value from count() to make it an integer
<?php
$chartsql = "SELECT recall from report where child_id='$childId'";
$ChartRes = mysqli_query($con,$chartsql);
while ($ChartRow=mysqli_fetch_array($ChartRes)){
if(!is_null($ChartRow['recall1'])){
$recall[] = $ChartRow['recall1'];
}
}
$count_recall = count($recall) + 0;
echo $count_recall;
Problem: I have several rows of results, for a single survey. Each survey can have any number of rows in the "Results" Table. There's a column called key_value. It's either 0 or -1. What is the fastest way in PHP to enumerate over several rows in a MySQL database, access each object, and flag a Boolean in PHP to tell me whether or not this particular survey has any rows with a key_value of 0?
something like this, except not brute forcing it...
for (i = 0; i < mysqlrows.length; i++){
if (mysqlrow.key_value == 0)
flag = true;
else
flag = false;
}
To operate on all matching (key_value = 0) Results:
$query = <<<EOD
SELECT result_id
FROM Results
WHERE key_value = 0
EOD;
$pdo = new PDO(....);
$stmt = $pdo->prepare($query);
if ($stmt->execute()) {
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result_id = $result['result_id'];
//do something with this result?
}
}
But if you only wanted the number of Results with key_value = 0, use some SQL like:
SELECT COUNT(*) as num_with_zero FROM Results WHERE key_value = 0
I'm running this piece of code:
$sql = "SELECT IF(TIMEDIFF(NOW(),last_update) > '02:00:00',1,0) AS morethan FROM products LIMIT 1";
if($stmt = $this->connect->prepare($sql)) {
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
$stmt->close();
} else {
return false;
}
return $result;
I get 0, that means that the difference I'm checking for it wasn't found ?
Mysql IF works like this:
IF(condition, true, false)
That you revceive 0 in the result "morethan " it means that
TIMEDIFF(NOW(),last_update) > '02:00:00'
is false, in other words the timediff is smaller than 02:00:00
You can rewrite your query just removing the IF:
SELECT (TIMEDIFF(NOW(),last_update) > '02:00:00') morethan FROM products LIMIT 1
Your query will actually non-deterministically get a row (this means you can't predict which row) from the table products and check if it matches your condition. If it does, the query will return 1, otherwise 0. I think that is not your intention, right?
If you want to check if there is any row that fulfills that condition you can do this:
select 1 existsInTable from products
where TIMEDIFF(NOW(),last_update) > '02:00:00'
limit 1
This will return 1 whenever a match is found and an empty resultset when no match is found. You don't even need to check the values returned as you can just count the numbers of intems returned by the query with mysql_num_rows.
If your only goal is to check if a row exists in php (true or false), what is the best way to do it?
Option 1?
$result = mysql_query("SELECT * FROM users WHERE id = '1'");
$num_rows = mysql_num_rows($result);
if ($num_rows == 1)
// one user, like it should be.
else
// do something else
Option 2?
$query = mysql_query("select count(1) from users where id = 1")
if (mysql_result($query, 0) == 1)
// one user, like it should be.
else
// do something else
Option 3?
$query = mysql_query("something like SELECT EXISTS( SELECT */1/COUNT(*)/etc. ...)")
if (mysql_result($query, 0) == 1)
// one user, like it should be.
else
// do something else
Beter option 4?
you name it.
Subquestions
COUNT(*), COUNT(1) or COUNT(id)?
Option 3 is the fastest way to check if a row exists if you are using MySQL:
$query = mysql_query("SELECT EXISTS(SELECT 1 FROM users WHERE id = 1)")
if (mysql_result($query, 0) == 1)
// one user, like it should be.
else
// do something else
I think the question refers more the code itself then the time involved, so using his query:
$result = mysql_query("SELECT * FROM users WHERE id = '1'");
//if result not returned(false) from Mysql return False Else True
//This is just example and you can do anything you need in side the if()
if(!$result) {
//or return some error or redirect to another piece of code
return FALSE;
} else {
//or do some other php/mysql magic
//if there is a result you have the row to work with of needed
return TRUE;
}
mysql_query
...excerpt from PHP manual Return Values
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning
resultset, mysql_query() returns a resource on success, or FALSE on
error.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc,
mysql_query() returns TRUE on success or FALSE on error.
The EXISTS is faster then SELECT COUNT(*) because the subquery will stop searching when it finds one row. It won't have to find them all and count them. It will return either 0 or 1:
SELECT EXISTS
( SELECT * FROM ... )