PHP mysqli query to check if a row exist [duplicate] - php

This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 8 years ago.
I have a mysql table, I want to check if a row exists where columnA=$a and $columnB=$b. I dont need to select anything from there. What should be efficient query for that? Currently Im doing like,
if ($stmt = mysqli->prepare("SELECT * FROM TABLE WHERE columnA=? && columnB= ? LIMIT 1")) {
$stmt->bind_param("ss", $a, $b);
$stmt->execute();
$stmt->store_result();
$count=$stmt->num_rows;
$stmt->close();
}
return ($count > 0 ? true : false);

Try with this:
if ($stmt = $mysqli->prepare("SELECT COUNT(*) FROM TABLE WHERE columnA=? && columnB=?")) {
$stmt->bind_param("ss", $a, $b);
$stmt->execute();
$stmt->bind_result($count);
$stmt->fetch();
$stmt->close();
}
return ($count > 0 ? true : false);
Now you should be able to get it done

That is efficient query if you want to improve that query you should select one column only to speed up the query.
if ($stmt = mysqli->prepare("SELECT id FROM TABLE WHERE columnA=? && columnB= ? LIMIT 1")) {

Select just one field from the row instead of all of them (*). Even though you're not using them, mysql still has to fetch them from storage and get them ready for transmission.
SELECT columnA FROM table WHERE ...
Otherwise there's not much else you can do to improve things, other than putting indexes on columnA and columnB to make the searching go faster.

Related

Same query but different results in phpMyAdmin and PHP [duplicate]

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

There's an error in my num_rows, but I can't see it [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 3 years ago.
OK, so I've gone round and round so many times now, I probably can't see the wood for the trees.
I want to return the number of rows that match the WHERE clause. This is my code
$stmt = $conn->prepare("SELECT id, title, category, last_completed, next_due, assigned_to FROM activities WHERE userId = ? AND status = ? AND DATEDIFF('$date', next_due) >= 1");
$stmt->bind_param("ss", $userId, $status);
$stmt->execute();
$result = $stmt->get_result();
$num_rows = mysql_num_rows($result);
echo $num_rows;
I have no doubt the error is obvious, but I can't see it. I can return the number of rows and establish it is more than 0, I just can't echo the num_rows!!!!
Your connection is oops method. so do with Oops format see the difference https://www.w3schools.com/php/php_mysql_select.asp
$conn->num_rows

PHP MySQL SELECT statement return null [duplicate]

This question already has answers here:
Understanding SUM(NULL) in MySQL
(2 answers)
Closed 4 years ago.
I want to select data from MySQL with a a where condition.
I'm sure the condition is false that's why it shouldn't return any data or any row but it returns null. I checked it with $stmt2->num_rows > 0 and this condition is true.
How can i prevent this from happening?
How my code suppose to work : this condition should be false for the first time and be true after I insert some data.
I think it's for SUM() that is used in select statement. How can I do that?
$q2="SELECT SUM(liked), SUM(disliked) FROM like_dislike WHERE post_id=?";
$stmt2 = $conn->prepare($q2);
$stmt2->bind_param('i', $post_id);
$stmt2->execute();
$stmt2->store_result();
$stmt2->bind_result($like_status, $dislike_status);
if ($stmt2->num_rows > 0 ) {
$stmt2->fetch();
}
else {
$like_status =0;
$dislike_status =0;
}
My select statement result in phpmyadmin:
According to the documentation :
SUM([DISTINCT] expr)
Returns the sum of expr. If the return set has no rows, SUM() returns NULL. The DISTINCT keyword can be used to sum only the distinct values of expr.
If there are no matching rows, SUM() returns NULL.
So you will always have NULL as result if you have no data.

Show last id of database in PDO [duplicate]

This question already has answers here:
PDO get the last ID inserted
(3 answers)
Closed 5 years ago.
I am trying to get the last id number of Database. But It's showing only 0.
I am learning PDO. Can anyone tell me how can I do it?
if($_SERVER['REQUEST_METHOD']=='POST'){
$sql = "SELECT * FROM tablename";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$row = $stmt ->fetch();
$showid = $pdo->lastInsertId();
echo $showid;
}
lastInsertId will return the ID of a row that was inserted by the same connection. You can't use it outside of that context.
The easiest way to fetch the last ID would be to run something like,
SELECT max(id) FROM tablename
If you're using this in order to work out which ID should be inserted next, consider using an auto-increment column for your ID instead.
lastInsertId() works only after a INSERT query - since you're only doing a select, it will always return string(1) = 0
So either you perform this code after an INSERT statement, or you can do the following:
$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();
Refering here to: PDO get the last ID inserted
Visit this thread, you'll find my samplecode provided by Corbin and much more informations on this topic.

MySQL error: 'invalid use of a group function' [duplicate]

This question already has answers here:
Call to a member function bind_param() on a non-object [duplicate]
(6 answers)
Closed 7 years ago.
I have a referral application where an ID can only have 2 direct referrals. I am trying to find IDs which appear less than 2 times in the ID_REF field with the code below.
$stmt = $conex->prepare("SELECT id FROM tb_modules WHERE count(id_ref) < ? ORDER BY id DESC LIMIT 1");
$stmt->bind_param("s", $n);
$n = 2;
$stmt->execute();
$stmt->store_result();
$numrows = $stmt->num_rows;
$stmt->bind_result($id);
//$stmt->fetch();
$stmt->close();
//echo $id.' '.'oi';
while ($stmt->fetch()) {
echo $id;
}
You aren't checking for any errors, that is completely bad development. You should start by ensuring that your prepare() is actually preparing the query correctly and not failing...
$stmt = $conex->prepare("SELECT id FROM tb_modules WHERE count(id_ref) < ? ORDER BY id DESC LIMIT 1");
// now check
if(!$stmt) {
die($conex->error); // or mysqli_error($conex);
} else {
$stmt->bind_param('s', $n);
}
Back to other matters. You seem to be trying to compare count(id_ref) which would be a number (int) against $n (which is an int too) but you're trying to pass it as a string.....?
You'll need to change that bind of yours to something like:
$stmt->bind_param('i', $n);
Also note, you can't set the $n variable after you call it.... that's going to throw an error.
Do the following:
var_dump($conex);
$stmt = $conex->prepare("SELECT id FROM tb_modules WHERE count(id_ref) < ? ORDER BY id DESC LIMIT 1");
var_dump($stmt)
This should shed some light on the matter.
I'm betting the $stmt variable is bool or null.
Your code isn't checking whether prepare returned successfully.
If the prepare encounters an error, it returns FALSE. instead of a statement object.
And a boolean FALSE value (the return from prepare) does not have a method/function bind_param.
$stmt = $conex->prepare("...");
if(!$stmt) {
echo "error in prepare ". mysqli_error($conex) ;
} else {
// prepare returned a statement object so we can do a bind_param
$stmt->bind_param(...);
To fix a syntax issue in the SQL statement that's causing an error in prepare, replace they keyword WHERE with keyword HAVING.
The predicates (conditions) in the WHERE clause are evaluated when rows are accessed. So the result of an aggregate function (e.g. COUNT() is not going to be available at the time those conditions in the WHERE are check. There's no way for that condition to be evaluated until after the rows are accessed, and the aggregate functions are evaluated. Predicates (conditions) in the HAVING clause get evaluated later, so it's valid to reference aggregates in a HAVING clause.
Just making that change to the SQL statement isn't likely going to get you the result you are looking for. Without a specification, we're just guessing what you are trying to return.

Categories