What happens when running this code? - php

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.

Related

PDO how to tell that a record was deleted? [duplicate]

I am passing a DELETE query to mysql using PDO statements. I want to know, whether the query really deletes a row or not? I try to use return value of $stmt->execute()
function delete(){
$stmt = $this->db->prepare("DELETE FROM users WHERE id= :id");
$stmt->bindValue(':id',$_POST[id]);
var_dump($stmt->execute());
}
But This gives always true, even no row is deleted. This gives true even if I don't post any value Or even post same value again and again. May be because query is successful with 0 row deleted , so return value of $stmt->execute() does not help.
So Is There any other way in PDO to know whether any row is really deleted or not, more specifically I want to be sure that only one row was deleted.
So i want something like this
function delete(){
$stmt = $this->db->prepare("DELETE FROM users WHERE id= :id");
$stmt->bindValue(':id',$_POST[id]);
$stmt->execute();
if($rowdeleted == 1){ echo "success";}
else{echo "failure";}
}
Any ideas?
Explanation
In order to know how many rows have been affected for the last operation during the select and Delete you have to GET THE ROW COUNT after the execution of the code.
Conditions:
If the count is greater than 0 - It means the code has affected some operations.
If the count does no return greater than 0 - It means that there is no records to match in the WHERE Clause.
Examples
PDOStatement::rowCount - Returns the number of rows affected by the last SQL statement
PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.
Sample Code:
<?php
/* Delete all rows from the FRUIT table */
$del = $dbh->prepare('DELETE FROM fruit');
$del->execute();
/* Return number of rows that were deleted */
print("Return number of rows that were deleted:\n");
$count = $del->rowCount();
print("Deleted $count rows.\n");
?>
Sample Output:
Return number of rows that were deleted:
Deleted 9 rows.
Happy Coding :)
If you are using PDO then you need the rowCount method.
In case of mysqli you need the affected rows
You could try somethign like this:
if($stmt[0]->rowCount() > 0)
{
echo "success";
}
else{
echo "failure";
}
A simple trick is to check the number of row affected
$count = $stmt->rowCount();

Mysqli - Equal and Different Expression

I'm having some problems with my query that is always returning false, but it should return true if not exists.
The problem is since the expression doesn't exists, it returns false.
function isRegistered($mysqli, $username, $sitename, $status){
if($stmt = $mysqli->prepare("SELECT COUNT(*) FROM table1 WHERE username= ? AND sitename = ? AND status != ?")){
$stmt->bind_param("sss", $username, $sitename, $status);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows == 0){
return true;
}else{
return false;
}
}
}
I'm after that seeking if the function is true or false. If it's false, it throws an error, if it's true, it follows for the next step. The problem is that always coming false (even if that's not true).
Basically the user only can register once in a specific area. So the first time it should be allowed, and the second time it doesn't. Could someone check what's going wrong with my query?
The number of rows for an aggregation query is always 1. If nothing matches the WHERE clause, then one row will be returned with the value of "1".
You can fix this either by changing the SELECT COUNT(*) to something non-aggregated, such as SELECT 1 or SELECT username. Or, you can read the value of COUNT(*) back from the query and use that.
I'll let you choose how to proceed.

SQL count all doesn't execute in php

if($sql = $db->query("Count (*) FROM post_items")){
echo mysqli_num_rows($sql);
}
what's wrong with my code? is this the correct way to echo the total of row in a table?
Your query should be
select count(*) FROM post_items
but echoing
mysqli_num_rows($sql);
will always give 1 as the ans, because count function returns only one row.
Rather fetch the details and show the count
$row = $sql->fetch_row();
echo $row[0];
No it is not; you will always get a return value of 1.
Why? Because you are in essence double-counting. The query executes a COUNT aggregate on the table returning a single row with the counted number. mysqli_num_rows is then counting the number of rows in this result set - the single row - and returns 1.
Try, the following line instead, which should fetch the first (only) column returned of the first (only) row in the result set.
echo $sql->fetch_row()[0]
Note you're also missing a SELECT keyword in your SQL statement.
It should be
if($sql = $db->query("select count(*) FROM post_items")){
echo mysqli_num_rows($sql);
}

Testing a SQL Query for True or False

$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()

PHP PDO statement returns incorrect row count with SELECT?

Why does this portion of code return true even when it shouldn't be?
$stmt = $dbh->prepare("SELECT COUNT(`user_id`) FROM `users` WHERE `username`= :username LIMIT 1");
$stmt->bindParam(':username', $username);
$stmt->execute();
return ($stmt->rowCount() == 1) ? true : false;
If I enter a username in a field that has already been registered, it returns true which then outputs:
That username has already been taken!
But if I enter a username that hasn't been registered, it still returns true and outputs the line above. I'm unsure why this is and how it can be fixed.
I know that the PHP manual states that rowCount() has some issues with SELECT queries, but I can't find a workaround for this that returns the number of rows affected by a SELECT query.
Because COUNT() will always return 1 row, although its value may be 0.
You can do a SELECT TRUE instead:
SELECT TRUE FROM `users` WHERE `username`= :username LIMIT 1
Or you can check if the value is greater than 0:
return ($stmt->fetchColumn() > 0);
BTW - the "? true : false" part is redundant; having the boolean condition by itself does just that.
You are checking the number of result rows. As your query returns always exactly one result row, rowCount() returns 1. The one result row will contain the count, e.g. 0 or 1 in with your query.
You need to check that count value in the result-row or change your query to not return any rows in case the user does not exists.
Try simple without binding:
$res = $dbh->query('SELECT COUNT(`user_id`) AS total FROM `users` WHERE `username`= "'.$username.'" ')->fetch();
return ($res['total'] == 1) ? true : false;

Categories