considering the following for my question:
$success = false;
$err_msg = '';
$sql = 'UPDATE task SET title = ? WHERE task_id = ?';
$conn = connect('w'); // create database connection: r= read, w= write
$stmt = $conn->stmt_init(); // initialize a prepared statement
$stmt->prepare($sql);
$stmt->bind_param('si', $_POST['title'], $_POST['id']);
$stmt->execute();
If i want to check if an insert or a deletion was succesfull, i could easily check for the affected_rows, like this:
if ($stmt->affected_rows > 0) {
$success = true;
} else {
$err_msg = $stmt->error;
}
If $stmt->affected_rows equals -1, it means that $stmt->execute() executed correctly but did not insert the record or did not delete the record successfully.
But, what about an update ? What is the correct way to deal with an update?
The way i do it is by checking for the return value :
$isRecordUpdated = $stmt->execute();
if (!$isRecordUpdated) {
// execute failed, therefore NO record updated!
} else {
//execute success, record updated!
}
Is that the correct way you guys are doing it?
It seems to me that there are really two equivalent and correct ways of doing this: either by checking the return value of execute as you do, or by checking the affected_rows value. -1 means the query errored out; 0 means that it did not affect (delete or update) any rows because there were none matching the query.
Since it seems there is no "better" way, you should pick what would be most convenient for your code. If e.g. using one approach over the other means that you can then share code among all types of queries, you might want to pick that one.
Why not store the value from mysql-affected-rows into a property of that object when you call execute()?
http://php.net/manual/en/function.mysql-affected-rows.php
Related
I have a function which inserts multiple rows using the MySqli library with prepared statements. The inserts works great, the problem is the build in $stmt->affected_rows method always returns the number of affected rows as 1.
Now to move around the affected row issue I created a counter which counts each executed statement. This solution is accurate. But I enjoy using built in methods and functions, so why is the $stmt->affected_rows always returning one, even though I inserted multiple rows? Is my code defective in some way or form? Maybe there is a pure Sql solution.
Here is my code:
try {
$query = "INSERT INTO dryenrolltb(enroll_id,id_entity,bin_type,tara_weight,dtetime_created,enrollprint_status) VALUES(?,?,?,?,?,?)";
$stmt = $db->prepare($query);
$stmt->bind_param('iiidsi', $enroll,$ent,$bin,$tara,$dte_create,$enr_status);
$result['rows']['rowerrors'] = array();
$result['rows']['rowsaffected'] = [];
$cnt = 0;
foreach ($arr as $value) {
$enroll = $value['enroll'];
$ent = $value['entid'];
$bin = $value['bin_t'];
$tara = $value['tara'];
$dte_create = $value['dtecreat'];
$enr_status = $value['enr_status'];
if($stmt->execute()) {
$cnt++;
} else {
array_push($result['rows']['rowerrors'],$value['enroll']);
}
}
if ($stmt->affected_rows > 0) {
echo "Affectionately yours";
array_push($result['rows']['rowsaffected'], $stmt->affected_rows);
array_push($result['rows']['rowsaffected'], $cnt);
return $result;
} else {
return false;
}
} catch (Exception $e) {
echo "Danger exception caught";
return false;
}
Can someone please give me a clue on why the $stmt->affected_rows always returns one on multiple inserts?
No. It seems like MySQLi statement class has no way of storing a running total of affected rows. After I thought about it, it makes total sense. Let me explain.
Every time you execute the statement it will affect a given number of rows. In your case you have a simple INSERT statement, which will add records one by one. Therefore, each time you call execute() the affected_rows value is one.
The query could be something different. For example INSERT INTO ... SELECT or UPDATE could affect multiple rows.
You could also have INSERT INTO ... ON DUPLICATE KEY UPDATE. If the key exists in DB, then you are not inserting anything. If the values are the same, you are not even updating anything. The affected rows, could be 0 or more.
The reason why it would be unwise for the statement to keep a running total of the affected rows is that each execution affects certain rows, irrespective of the previous executions. They could be even the same records. Consider the following example:
$stmt = $mysqli->prepare('UPDATE users SET username=? WHERE id=?');
$stmt->bind_param('si', $name, $id);
$id = 102;
$name = 'Affected rows 1';
$stmt->execute();
echo $stmt->affected_rows; // 1
$name = 'Affected rows 2';
$stmt->execute();
echo $stmt->affected_rows; // 1
Both update statements updated the same row. If mysqli kept a running total it would report 2 affected rows, but in reality only 1 row was changed. If the number was summed, you would be losing information.
So, for your simple scenario, it is fine to keep the total on your own, for example by summing up the $stmt->affected_rows after each execution. Anything more than that, it would probably not make much sense.
I'm trying to test if a user has activated their account using rowcount. Currently it's returning a positive even when I deliberately edit the database data to fail.
I tested my SQL to see if that was the problem, it seemed to return the expected values. I'm assuming it is something to do with my PHP code
try
{
$db = new Database;
$query = "SELECT COUNT(*),accountStatus, email FROM users WHERE email = :email AND accountStatus ='Active'";
$stmt = $db->prepare($query);
$stmt->bindValue(':email', $email);
$stmt->execute();
$count = $stmt->rowCount();
}
catch(Exception $e)
{
$errors[] = ["name" => "email", "error" => "Something went wrong contact the administrator or try again later"];
}
if(count($count > 0))
{
return true;
}
else
{
return false;
}
From the docs:
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.
I have the following code in my CRUD class
//function to execute prepared statement query
//$sql = select , insert, update and or delete query => insert into table(col,col,col,...col) values(?,?,?,...?);
//$dataTypes = "ssidb", it could be any char in s=>string, i=>integer, d=>double and b=>blob data
//$param = $val1,$val2,$val3,....$valn, this is an option coma separated values to bind with query
public function dbQuery($sql,$dataTypes="",$param=""){
try{
$this->connect();
$stmt = $this->con->stmt_init();
$stmt = $this->con->prepare($sql);
$stmt->bind_param($dataTypes, $param);
if($stmt->execute() === true){
return true;
}
else{
return false;
}
}catch(Exception $e){
$this->errorMsg = $e->getMessage();
}
$this->closeConnection();
}
I am calling this method from my index page like this:
if(isset($_POST['btnSearch'])){
//search for some record with primary key
$sno = intval($_POST['sno']);
$sql = "SELECT sno,std_name,email,roll_number FROM table_1 WHERE sno = ?";
$dTypes = "i";
$params = $sno;
if($db->dbQuery($sql,$dTypes,$params)){
echo('Record exists');
}
else{
echo('Record did not found'.$db->errorMsg);
}
}//search for record
//inserting values to table_1 table
This always return true either there is any record exists or not?
Whats going wrong with this code?
There are many flaws in your code, and it will never work as intended, even after fixing this particular problem.
Before starting with a class, you need to practice heavily with raw API functions, and learn how to use them by heart. Otherwise your class will be just a straw house that will crumble from a softest touch.
Now to your problem.
To solve it, you need to understand one very important mathematical conception, that reads "empty result is not an error". 10 - 5 - 5 = 0 doesn't mean there is an error in your calculations! It merely means that the result is zero.
Exacly the same is here. When a database returns no rows, it doesn't mean there is an error. It just meams that there is zero (no) data to return.
The opposite is true as well: if there is no error, it doesn't mean that there are rows found.
To see whether any row were returned or not, you need to fetch this very row.
Therefore, instead of checking execute() result, just fetch your row into a variable and then check whether it contains anything.
Would someone please me with the code below, I am inexperienced in this area and my class in SQL was "A long time ago in a galaxy far, far away..." I know the connection string works because I have used it in other functions with this app. I have even used the code below for retrieving *rows from another table in another function, for the most part, except that I didn't use the WHERE clause.
First, I am able to store IP addresses in the table using a function and it is working well. Now I want to check to see if a given one exist in this table. Partial code is given below.
What seems to always return is 0 rows. I have put in test data into the table and hard-coded the $ipA, but I still get 0 rows return. Please help if possible and thanks for the effort spent.
function checkDB($ipA) {
require_once('connection.inc.php');
$resultAns = "";
//create db connection
$conn = dbConnect();
//init prepared stmt
$stmt = $conn->stmt_init();
//Set sql query for ipAddress search
//prepare the SQL query
$sql = 'SELECT * FROM ipAddress WHERE ipA = ?';
//submit the query and capture the result
if ($stmt->prepare($sql)) {
$stmt->bind_param('s', $ipA);
$stmt = $stmt->execute();
//if qry triggers error affeted_rows value becomes -1 &
//php treats -1 as true; so test for greater than 0
$numRows = $stmt->num_rows; //not to sure about the syntax here
}
// I want to know if the query brought back something or not, I don't what
// to know exactly what, only that it found a match or did not find a match.
// echos are for testing purposes to show me where I am landing.
if ($numRows == 0) {
echo '<script type="text/javascript">window.alert("numRows = 0")</script>';
$resultAns = 0;
} elseif ($numRows == 1) {
echo '<script type="text/javascript">window.alert("numRows = 1")</script>';
$resultAns = 1;
}
return $resultAns;
}
Try storing the result after you execute
$stmt->store_result();
Use $stmt->store_result(); before you call num_rows.
While the others caught one reason that $numRows would never receive a value other than 0, the other piece of code that was flawed and caused problems was...
$stmt = $stmt->execute(); which should have been just $stmt->execute();
I must have mixed it up with other code I wrote from somewhere else.
Thanks for the answers, they did help.
i have an update function that updates a specific row in the table. The sql query works in PHPmyadmin and I am always returned true on the function. However, the database is not updated. I looked over the code and nothing appears wrong. What could be the problem. primary_id is the primary id of the table and the only other column is fund_max.
function change_fund_max ($mysqli, $project_id, $fund_max) {
if ($stmt = $mysqli->prepare("UPDATE `project_fund_max` SET `fund_max` = ? WHERE
`project_id` = ?")){
$stmt->bind_param('ii', $project_id, $fund_max);
$return = $stmt->execute();
$stmt->close();
return $return;
} else {return false;}
}
Here is the use of the function.
$fund_max = 11.55;
$project_id = 1;
$row43 = change_fund_max ($mysqli, $project_id, $fund_max);
var_dump($row43);
Execute will only return false on a failure... like you messed up the SQL or something. What you really want to know is did the command actually update on the rows... check mysqli_stmt_affected_rows to see if more than zero rows where changed.
Also your project_id and fund_max parameters are the wrong way around in your bind ;)
Result:
function change_fund_max ($mysqli, $project_id, $fund_max) {
if ($stmt = $mysqli->prepare("UPDATE `project_fund_max` SET `fund_max`=? WHERE
`project_id` = ?")){
$stmt->bind_param('di', $fund_max, $project_id);
if (!$stmt->execute()) return false;
$count=$stmt->affected_rows;
$stmt->close();
return ($count>0);
} else {
return false;
}
}
Update: For sneaky "fund_max is a decimal" comment... if fund_max is a decimal you need to bind to a double otherwise you're loosing anything right of the decimal place during the bind_param command (my code updated)
A wild guess, but it seems the value passed in $project_id does not exist in the database.
That would make the UPDATE command run, not fail, but also not update any record.
another guess, project_id and/or fund_max may not be both integers. you may check in the manual
Also, the names of the columns shouldn't be surrounded by quotes(`), unless its present in the name itself, in the update query.
Edit:
function change_fund_max ($mysqli, $project_id, $fund_max) {
if ($stmt = $mysqli->prepare("UPDATE project_fund_max SET fund_max = ? WHERE
project_id = ?")){
$stmt->bind_param('di', $fund_max, $project_id);
$return = $stmt->execute();
$stmt->close();
return $return;
} else {return false;}
}