I want to have a condition that will perform some action when the row doesn't exist at all.
$stmt = $conn->prepare('SELECT * FROM table WHERE ID=?');
$stmt->bindParam(1, $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
Tried if (count($row) == 0) and if($stmt->rowCount() < 0) but none of them works.
You can just check the return value directly.
$stmt = $conn->prepare('SELECT * FROM table WHERE ID=?');
$stmt->bindParam(1, $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if( ! $row)
{
echo 'nothing found';
}
/*
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); // Same here
if( ! $rows)
{
echo 'nothing found';
}
*/
If you are asking about checking without fetching then simply have MySQL return a 1 (or use the COUNT() command).
$sql = 'SELECT 1 from table WHERE id = ? LIMIT 1';
//$sql = 'SELECT COUNT(*) from table WHERE param = ?'; // for checking >1 records
$stmt = $conn->prepare($sql);
$stmt->bindParam(1, $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
if($stmt->fetchColumn()) echo 'found';
if($stmt->rowCount() == 0)
should work fine, since the number of rows can't be less than zero in any event at all.
From the manual:
For most databases, PDOStatement::rowCount() does not return the
number of rows affected by a SELECT statement. Instead, use
PDO::query() to issue a SELECT COUNT(*) statement with the same
predicates as your intended SELECT statement, then use
PDOStatement::fetchColumn() to retrieve the number of rows that will
be returned. Your application can then perform the correct action.
I would suggest reading up on that here.
Heres what I use in my object classes:
function exists_by_id () {
// check if object exists by id
$stm = DB::$pdo->prepare('select count(*) from `table` where `column`=:column');
$stm->bindParam(':column', $this->column);
$stm->execute();
$res = $stm->fetchColumn();
if ($res > 0) {
return true;
}
else {
return false;
}
}
Related
I want to have a condition that will perform some action when the row doesn't exist at all.
$stmt = $conn->prepare('SELECT * FROM table WHERE ID=?');
$stmt->bindParam(1, $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
Tried if (count($row) == 0) and if($stmt->rowCount() < 0) but none of them works.
You can just check the return value directly.
$stmt = $conn->prepare('SELECT * FROM table WHERE ID=?');
$stmt->bindParam(1, $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if( ! $row)
{
echo 'nothing found';
}
/*
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); // Same here
if( ! $rows)
{
echo 'nothing found';
}
*/
If you are asking about checking without fetching then simply have MySQL return a 1 (or use the COUNT() command).
$sql = 'SELECT 1 from table WHERE id = ? LIMIT 1';
//$sql = 'SELECT COUNT(*) from table WHERE param = ?'; // for checking >1 records
$stmt = $conn->prepare($sql);
$stmt->bindParam(1, $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
if($stmt->fetchColumn()) echo 'found';
if($stmt->rowCount() == 0)
should work fine, since the number of rows can't be less than zero in any event at all.
From the manual:
For most databases, PDOStatement::rowCount() does not return the
number of rows affected by a SELECT statement. Instead, use
PDO::query() to issue a SELECT COUNT(*) statement with the same
predicates as your intended SELECT statement, then use
PDOStatement::fetchColumn() to retrieve the number of rows that will
be returned. Your application can then perform the correct action.
I would suggest reading up on that here.
Heres what I use in my object classes:
function exists_by_id () {
// check if object exists by id
$stm = DB::$pdo->prepare('select count(*) from `table` where `column`=:column');
$stm->bindParam(':column', $this->column);
$stm->execute();
$res = $stm->fetchColumn();
if ($res > 0) {
return true;
}
else {
return false;
}
}
$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ?");
$stmt->bind_param("s", $query);
$stmt->execute();
$stmt->store_result();
if ($stmt->affected_rows > 0) {
echo "Exists";
}
Instead of echoing out Exists, I want it to echo out nameData. How can I go about doing that?
First of all, if you want only one row then append LIMIT 1 to your SELECT query, like this:
$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ? LIMIT 1");
So there are two approaches to display nameData:
Method(1):
First bind the variable $nameData to the prepared statement, and then fetch the result into this bound variable.
$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ? LIMIT 1");
$stmt->bind_param("s", $query);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows){
$stmt->bind_result($nameData);
$stmt->fetch();
echo $nameData;
}else{
echo "No result found";
}
Method(2):
First use get_result() method to get the result set from the prepared statement, and then use fetch_array to fetch the result row from the result set.
$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ? LIMIT 1");
$stmt->bind_param("s", $query);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows){
$row = $result->fetch_array()
echo $row['nameData'];
}else{
echo "No result found";
}
I think you can below code i hope your query is working fine it returns result properly then you can use below code.
$stmt->bind_result($nameData);
if ($stmt->fetch()) {
printf ("%s\n", $nameData);
}
Note that affected_rows won't do anything useful here.
However, nor you don't need num_rows as well (and therefore store_result too)
$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ?");
$stmt->bind_param("s", $query);
$stmt->execute();
$stmt->bind_result($nameData);
$stmt->fetch();
echo $nameData;
Considering all that hassle, even without useless functions, you may find PDO a way better approach:
$stmt = $pdo->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ?");
$stmt->execute($query);
echo->$stmt->fetchColumn();
I have a database in which I have user_id & associated_id.There can be multiple associated_id for a single user_id. Now I want to fetch all the associated_ids into a single array. I have tried this method but don't know how to get them in array.
$stmt = $this->conn->prepare("SELECT * FROM my_contacts WHERE user_id = ?");
$stmt->bind_param("s", $user_id);
if ($stmt->execute())
{
while ($stmt->fetch())
{
//what to write here
}
//echo var_dump($user);
$stmt->close();
}
Try this:
$stmt = $mysqli->prepare("SELECT associated_id FROM my_contacts WHERE user_id = ?")) {
$stmt->bind_param('s', $user_id); // Bind "$user_id" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($associated_id);
$stmt->fetch();
The results will be stored in the $associated_id array.
You can bind parameters like this and use fetchall method to get all the results in a array
$stmt = $this->conn->prepare("SELECT * FROM my_contacts WHERE user_id = :user_id");
$stmt->bind_param(":user_id", $user_id, PDO::PARAM_INT);
if ($stmt->execute())
{
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
//echo var_dump($user);
$stmt->close();
}
According to your code you used mysqli.
$stmt = $this->conn->prepare("SELECT * FROM my_contacts WHERE user_id = ?");
if($stmt->execute()){
$result = $stmt->get_result();
if($result->nom_rows > 0){
while($row = $result->fetch_assoc()){
var_dump($row)
}
}else{
echo "Sorry NO data found";
}
}else{
echo "Some thing is wrong";
}
here you can't used $stmt->bind_result(); instead of use $stmt->get_result()
$stmt->bind_result(); is only used when you define field in select query
with * you need to used $stmt->get_result()
refer this link for more information
Example of how to use bind_result vs get_result
I'm hitting my head to a wall... This is a fraction of my code:
$stmt = $db->prepare("SELECT vote,id FROM votes WHERE post_id = ? AND user_id = ? ");
$stmt->bind_param('ii', $post_id, $user_id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($result, $vote_id);
$stmt->fetch();
$num_rows = $stmt->num_rows;
$stmt->close();
if ($num_rows>=1)
{
if ($result!==$vote)
{
$stmt = $db->prepare("UPDATE votes SET vote = ? WHERE id=?");
$stmt->bind_param('ii', $vote, $vote_id);
$stmt->execute();
$stmt->close();
}
else if ($result==$vote)
{
$stmt = $db->prepare("UPDATE votes SET vote = 0 WHERE id=?");
$stmt->bind_param('i', $vote_id);
$stmt->execute();
$stmt->close();
}
}
No errors are shown, the script works just fine until it reaches ELSE IF part. It doesn't update although $vote value is the same as in a database.
!== is a strict comparison operator, and this statement is saying that $result must not be identical (in type as well as value) to $vote. You don't need to be that specific for this.
if ($result!==$vote)
What you should be doing is this:
if ($result != $vote) // only one equal sign, not two
{
...
} else { // they are equal implicitly, no need to redefine the ==
...
}
trying to convert all my old mysql_* operations into new and, from what i've heard, improved PDO, but this query wont seem to run successfully, I am trying to select all from the table PEOPLE where the username = $username (which has previously been declared $username = $_SESSION['username'];)
$query = "SELECT * FROM people WHERE username=?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $username);
$stmt->execute();
$num_rows = $stmt->fetchColumn();
if ($num_rows == 1) {
// ...
}
THE WORKING CODE IS:
$query = "SELECT * FROM people
WHERE username=?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $username);
$stmt->execute();
$num_rows = $stmt->fetchColumn();
$user = $stmt->fetchObject();
if ($user) {
//do something
}
$stmt->fetchColumn does not fetch the number of rows; in this case it will fetch the first column from the first row of the result set. Since that will not be equal to 1 generally your test will fail.
In this case there is also no real need to count the number of returned rows because you are expecting either one or zero (if the username does not exist). So you can simply do:
$stmt->execute();
$user = $stmt->fetchObject();
if (!$user) {
// not found
}
else {
echo "User $user->username found!";
}
The if(!$user) test works because if there is no row to fetch $user will be false (see the documentation for fetchObject).
$query = "SELECT * FROM people WHERE username = :username";
$stmt = $conn->prepare($query);
$stmt->bindParam(':username', $username);
$stmt->execute();
while ($row = $stmt->fetchObject()) {
// do stuff
}
Use PDOStatement::rowCount as the num_rows and PDOStatement::fetch(PDO::FETCH_ASSOC) as fetch_assoc equivalent.
You want
if ($stmt->num_rows == 1) {
instead.