mysql_affected_rows returns 0 - php

I have a problem with mysql_affected_rows() function in PHP. I use MySQL update, in phpMyAdmin I can see, that 'confirmed' changes from 0 to 1, but mysql_affected_rows still returns 0! I cannot find a solution. My code is:
$query = "UPDATE visits
SET confirmed = 1
WHERE id = ? AND confirmed = 0 AND expire > now() - INTERVAL 10 MINUTE;";
$stmt = $this->conn->stmt_init();
if($stmt->prepare($query)) {
$stmt->bind_param('i',$id); //$id is a function parameter
$res = $stmt->execute();
$stmt->close();
echo mysql_affected_rows();
}

It seems you're using PDO, not the mysql_* functions.
Therefore, you should uso PDOs rowCount function:
$query = "UPDATE visits
SET confirmed = 1
WHERE id = ? AND confirmed = 0 AND expire > now() - INTERVAL 10 MINUTE;";
$stmt = $this->conn->stmt_init();
if($stmt->prepare($query)) {
$stmt->bind_param('i',$id); //$id is a function parameter
$res = $stmt->execute();
echo $stmt->rowCount();
$stmt->close();
}

Use affected_rows to get the number of affected rows when using an UPDATE statement :
$stmt = $this->conn->stmt_init();
if($stmt->prepare($query)) {
$stmt->bind_param('i',$id); //$id is a function parameter
$res = $stmt->execute();
echo $stmt->affected_rows;
$stmt->close();
}
It also needs to be before the close() statement

Since everyone seems to think you using PDO, whereas it looks more like MySQLi to me, here is the MySQLi way:
$query = "
UPDATE visits
SET confirmed = 1
WHERE id = ?
AND confirmed = 0
AND expire > now() - INTERVAL 10 MINUTE
";
$stmt = $this->conn->stmt_init();
if ($stmt->prepare($query)) {
$stmt->bind_param('i', $id); //$id is a function parameter
$res = $stmt->execute();
echo $stmt->affected_rows; // Here's the good stuff
$stmt->close();
}

Use this http://www.php.net/manual/en/pdostatement.rowcount.php
The PDOStatement::rowCount return the number of rows affected by the query

You need to pass the connection as a parameter to the function.
echo mysql_affected_rows($this->conn);
http://php.net/manual/en/function.mysql-affected-rows.php

Related

How to return true or false if row exist on mysql via PDO [duplicate]

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;
}
}

Named parameter in update where clause (pdo object)

I try to translate this query to my PDO object from this thread:
UPDATE table_name
SET col1 = <<new value>>,
col2 = <<new values>>,
last_modified_timestamp = <<new timestamp>>
WHERE primary_key = <<key column>>
AND last_modified_timestamp = <<last modified timestamp you originally queried>>
So i have a "modified" field in the mysql table and fetch the data (SELECT modified AS last_modified) to pre-fill in a hidden field in my form and post the value to the object:
$position->readOne();
$position->last_modified = $_POST['last_modified'];
<input name='last_modified' value='{$position->last_modified}'>
My object update query looks like:
UPDATE positions
SET
... some values ...
WHERE id=:id
AND modified=:last_modified
$stmt->bindParam(":last_modified", $this->last_modified);
If I check the posted variables, everything looks fine but the update query ignores my second where clause completely and override the modified field after post the form.
Sure a beginner issue but I can´t find it.
Thanks
EDIT:
Select query
public function readOne(){
$query = "SELECT
p.position,
p.modified,
p.modified AS last_modified
FROM positions p
WHERE id = ?
LIMIT 0,1";
$stmt = $this->conn->prepare( $query );
$stmt->bindParam(1, $this->id);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$this->position = $row['position'];
$this->modified = $row['modified'];
$this->last_modified = $row['last_modified'];
}
Update query
public function updatePosition(){
$this->getTimestamp();
$query = "UPDATE positions
SET
position=:position,
modified=:modified,
WHERE id=:id
AND modified=:last_modified";
$stmt = $this->conn->prepare($query);
$this->position=htmlspecialchars(strip_tags($this->position));
$stmt->bindParam(":id", $this->id);
$stmt->bindParam(":position", $this->position);
$stmt->bindParam(":modified", $this->timestamp);
$stmt->bindParam(":last_modified", $this->last_modified);
if($stmt->execute()){
print_r($this->last_modified);
return true;
}
print_r($stmt->errorInfo());
return false;
}
public function getTimestamp(){
date_default_timezone_set('Europe/Berlin');
$this->timestamp = date('Y-m-d H:i:s');
}
I figured it out. The update query and everything else worked fine but the problem was the notification handling, so the function updatePosition() told me everything was updated but it worked as it should and it did not update anything if the value was not the same.
This fixed it:
if($stmt->execute()){
$affected_rows = $stmt->rowCount();
if ($affected_rows == 1) {
return true;
}
This helped me to understand how it works ... PDOStatement::execute() returns true but the data is not updated

just everything together for a number

I should have made ​​such that it is +1 up ​​database instance every time you write a status on its away
problem: right now when writing +1 then the whole time 1
solved: this is how I want when I have 1 point in advance so it must just above the old numbers thus making it for 2 and 3, etc.
if ($stmt = $this->mysqli->prepare('UPDATE bruger SET point=? WHERE id=?')) {
$stmt->bind_param('si', $point, $id);
$point = +1;
$id = $_SESSION["id"];
$stmt->execute();
$stmt->close();
}
You should either do a select query first, then add 1 using PHP and then do an update query, or change the update query so that it automatically adds 1 without using PHP, which is better.
Changing the query would result in the following code:
if ($stmt = $this->mysqli->prepare('UPDATE bruger SET point=point + 1 WHERE id=?')) {
$stmt->bind_param('si', $id);
$id = $_SESSION["id"];
$stmt->execute();
$stmt->close();
}

fetch() not returning first row

I am trying to update code that has been written using prepared statements. This is my first time using them and I am having difficulty retrieving all the results. When I use a direct SQL statement, it works so I don't think that's the problem.
The code will not return any results until there are at least two that match the query, then it will return all but the first row. I tried using fetchAll, but that gives different error about a call to an undefined method.
Thanks in advance for any help that you can provide. If it's not to much to ask, please provide example or reference I can refer to and complete my understanding.
function html_competitive_make_gallery ($init) {
global $USER;
$user_id = $USER->id;
$page_name = 'competitive';
$base_name = $init['base_name'];
global $link;
$sql_pre = "SELECT form_id, community_id FROM frm_root WHERE user_id = ?
AND page_name = ? ORDER BY last_modified_date DESC LIMIT 1";
$stmt = $link->prepare($sql_pre);
$stmt->bind_param('is', $user_id, $page_name);
$stmt->execute();
$stmt->bind_result($form_id,$community_id);
$stmt->fetch();
$stmt->close();
$sql = "SELECT data FROM tester WHERE type= '".$base_name."'
AND form_id= '".$form_id ."' AND community_id= '". $community_id ."' LIMIT 5";
$stmt = $link->prepare($sql);
$stmt->execute();
$stmt->bind_result($data);
$stmt->fetch();
$html[]='<div class="gallery" style ="width:100%;height:30%;overflow:hidden;">';
while ($stmt->fetch()){
echo $data;
}
$stmt->close();
$html[]='</div>';
return implode ( $html);
}
You're running fetch() before entering your loop, hence dropping the first row of your results:
$stmt->execute();
$stmt->bind_result($data);
$stmt->fetch(); // <<< THIS LINE SHOULD NOT BE HERE
$html[]='<div class="gallery" style ="width:100%;height:30%;overflow:hidden;">';
while ($stmt->fetch()){
echo $data;
}
$stmt->close();
Try this:
while ($data = $stmt->fetch()){
echo $data;
}
$stmt->close();
Your main problem is called "mysqli".
You will face such problems as long as you're using mysqli with prepared statements.
Just quit it and use PDO:
function html_competitive_make_gallery ($init) {
global $USER;
global $link;
$sql_pre = "SELECT form_id, community_id FROM frm_root WHERE user_id = ?
AND page_name = ? ORDER BY last_modified_date DESC LIMIT 1";
$stmt = $link->prepare($sql_pre);
$stmt->execute(array($USER->id, 'competitive'));
return $stmt->fetch();
}

How to check if a row exist in the database using PDO?

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;
}
}

Categories