Track error in PDO update query [duplicate] - php

This question already has answers here:
Reference — frequently asked questions about PDO
(3 answers)
Closed 8 years ago.
I have an update query
$query = $db->prepare("UPDATE user SET UserID='6',UserName='xyz' WHERE UserID= '6' ");
$query->execute();
it runs fine, but when I change field UserName to UserNamee
$query = $db->prepare("UPDATE user SET UserID='6',UserNamee='xyz' WHERE UserID= '6' ");
$query->execute();
It should show error, but it doesn't show any error
I just want to handle these kind of errors in my project.

you can track the error in PDO using errorCode() function this function returns 0000 when no error else return a 4 digit number (error code), for your example you can try :
$query = $db->prepare("UPDATE user SET UserID='6',UserNamee='xyz' WHERE UserID= '6' ");
$query->execute();
if($query->errorCode()=='0000')
{ echo 'no error'; }
else
{ echo 'error'; }

PDO has various error modes that you can pass to the constructor as the driver_options argument. You can find them at http://php.net/manual/en/pdo.setattribute.php . Most people use array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION).

You should use try-catch:
try {
$query = $db->prepare("UPDATE user SET UserID='6',UserName='xyz' WHERE UserID= '6' ");
$query->execute();
} catch (PDOException $e) {
echo $e->getMessage();
}
And remember to do this after connection at the database:
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$db->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
$query = $db->prepare("UPDATE user SET UserID='6',UserNamee='xyz' WHERE UserID= '6' ");
if (!$query) {
print_r($db->errorInfo());
}
else
$query->execute();

Related

"bind_param" returning 0 rows [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 2 years ago.
I have a query with a parameter to bind stored in the session.
I tested the query on the database and it should return 1 row but it does not!
I tried everything. Its not an issue with the $id because I use it for another query and it is fully working:
$resultReturn = $con->prepare( 'SELECT `returns`.`return_id`, `returns`.`return_status` FROM
`agents` LEFT JOIN `returns` ON `returns`.`agent_id` = `agents`.`id` AND `agents`.`id` = ?');
$resultReturn->bind_param('i', $id);
$resultReturn->execute();
$resultReturn->fetch();
$resultReturn->store_result();
$resultReturn->bind_result($returnID, $returnStatus);
if($resultReturn)
{
echo $resultReturn->num_rows; //zero
while($row = $resultReturn->fetch_row())
{
echo $resultReturn->num_rows; //incrementing by one each time
}
echo $resultReturn->num_rows; // Finally the total count
}
$con -> close();
the first if returns always FALSE; If I set manually the id it works!
Here is my other query at the beginning of the same page (and its perfectly working):
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if (mysqli_connect_errno()) {
exit('Failed to connect to MySQL: ' . mysqli_connect_error());
}
// We don't have the password or email info stored in sessions so instead we can get the results from the database.
$stmt = $con->prepare('SELECT password, email, role FROM agents WHERE id = ?');
// In this case we can use the account ID to get the account info.
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->bind_result($password, $email, $role);
$stmt->fetch();
$stmt->close();
It is because I'm using the same connection for multiple queries?
Move fetch() after bind_result().
The correct order should be:
$resultReturn = $con->prepare(/* */);
$resultReturn->bind_param('i', $id);
$resultReturn->execute();
$resultReturn->store_result();
$resultReturn->bind_result($returnID, $returnStatus);
$resultReturn->fetch();

PHP prepared statement not working [duplicate]

This question already has answers here:
How do I escape reserved words used as column names? MySQL/Create Table
(4 answers)
Closed 2 years ago.
I am making a prepared statement in PHP and my code is fine until I add in 'id' and 'key' to my parameters. They are definitely in the table that I am requesting too. What is wrong? Thanks in advance!
ERROR: Call to a member function bind_param() on boolean
if($_POST['userx']){
echo '<div id="div2"><div id="font2">Dashboard</div>';
$queryA = "SELECT name,profo,password,id,key FROM collegestudents WHERE email = ?";
$stmt = $connection->prepare($queryA);
$stmt->bind_param('s',$_POST['userx']);
$stmt->bind_result($name1,$profo,$password1,$key,$id);
$stmt->execute();
$stmt->fetch();
$stmt->close();
Key is a reserved keyword in mysql.
It's a good habit to enclose field names and table names in backticks in queries but also to check for errors.
$queryA = "SELECT `name`,`profo`,`password`,`id`,`key` FROM `collegestudents` WHERE `email` = ?";
$stmt = $connection->prepare($queryA);
if ($stmt) {
$stmt->bind_param('s',$_POST['userx']);
...
}
else {
echo "MySQL ERROR: " . $connection->error;
}
$stmt = $connection->prepare($queryA);
returns boolean(false)
make sure your query is correct
you can do a simple check like this
$stmt = $connection->prepare($queryA);
if (!$stmt) {
echo "failed to run";
} else {
$stmt->bind_param('s',$_POST['userx']);
$stmt->bind_result($name1,$profo,$password1,$key,$id);
$stmt->execute();
$stmt->fetch();
}
Edit:
if you are using PDO you were doing it wrong it should be like this
$stmt = $conn->prepare("SELECT name,profo,password,id,key FROM
collegestudents WHERE email = :email");
$stmt->bindParam(':email', $email);
Change your database connection file with
<?php $con = new PDO('mysql:host=127.0.0.1;dbname=yourdatabasename;','username',''); ?>
Then change below line
$queryA = "SELECT name,profo,password,id,key FROM collegestudents WHERE email = ?";
$stmt = $connection->prepare($queryA);
$stmt->bind_param('s',$_POST['userx']);
$stmt->bind_result($name1,$profo,$password1,$key,$id);
$stmt->execute();
with
$queryA = "SELECT name,profo,password,id,key FROM collegestudents WHERE email = :v";
$stmt = $connection->prepare($queryA);
$stmt->execute( array('v' => $_POST['userx']) );

pdo not binding param properly [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I've been stuck on this for about 3 days now and asked multiple people about this and no one seems to have an answer to me why this is not working. I cannot figure out why they aren't binding because the bindings work on the select statement but not the update. I know for a fact that $sessCheck['userid'] and $sessCheck['hwid'] are being set because I already printed them out to check if they were null or something.
The request inbound from slim
{"userid": "1000","hwid":"TESTING"}
The function
function updateHWID(){
$request = Slim::getInstance()->request();
//$bsreq = utf8_encode();
$sessCheck = json_decode($request->getBody(), true, 9 );
$db = getConnection();
$sql = "SELECT userid,hwID FROM accounts WHERE userid = :userid";
$stuff = $db->prepare($sql);
$stuff->bindParam("userid", $sessCheck['userid']);
$stuff->execute();
$db = null;
$rows = $stuff->fetch(PDO::FETCH_ASSOC);
if ($rows['hwID'] != $sessCheck['hwid']) {
$sql2 = "UPDATE accounts SET hwID=':hwid' WHERE userID = ':userid';";
try {
$db2 = getConnection();
$stmt = $db2->prepare($sql2);
//these two param's are not binding
$stmt->bindParam("userid", $sessCheck['userid']);
$stmt->bindParam("hwid", $sessCheck['hwid']);
$stmt->execute();
//$rt = $stmt->fetch(PDO::FETCH_ASSOC);
//$stmt->debugDumpParams();
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
}
This is the result incoming on the sql log
1372 Query UPDATE accounts SET hwID=':hwid' WHERE userID = ':userid'
I've also tried this as well as using the which also didn't work
$stmt->bindParam(":userid", $sessCheck['userid']);
$stmt->bindParam(":hwid", $sessCheck['hwid']);
Then I tried this too and it didn't work
$stmt = $db2->prepare("UPDATE accounts SET hwID='?' WHERE userID = '?';");
$stmt->bindParam(1, $sessCheck['hwid'], PDO::PARAM_STR);
$stmt->bindParam(2, $sessCheck['userid'], PDO::PARAM_INT);
Take the binded parameter names out of their single quotes.
so:
$sql2 = "UPDATE accounts SET hwID=:hwid WHERE userID = :userid;";

Check status of previous MySQL query and execute next query

I want to execute multiple MySQL queries. Where the next query depends on the status of the previous one. I need to check the status of the query and in some cases also rowCount(). If the first query returns what I want the next query will be executed and so on. If one of them fail the whole process will be stopped.
I usually nest my queries inside of a try/catch block. Is there a better way to do this? Here is my code. I do not want you to fix my code just see it and give me any suggestions. I'm using PDO with MySQL 5.6.26.
Thanks
$updated = false;
//#1
$query = "select username, forgot_code, time, valid from forgot_requests where forgot_code = :forgot_code";
try {
$run_query = $db->prepare($query);
$run_query->execute(array(':forgot_code' => $_POST['forgot_code']));
$data = $run_query->fetch(PDO::FETCH_OBJ);
//13min = 780s
if($run_query->rowCount() == 1 && (time() - $data->time < 7800000) && $data->valid) {
//#2
$query = "update users set password = :password where username = :username";
try {
$run_query = $db->prepare($query);
$run_query->execute(array(
':password' => password_hash($_POST['password'], PASSWORD_DEFAULT),
':username' => $data->username
));
//#3
$query = "update forgot_requests set valid = 0 where forgot_code = :forgot_code";
try {
$run_query = $db->prepare($query);
$run_query->execute(array(':forgot_code' => $_POST['forgot_code']));
//update
$updated = true;
} catch(PDOException $e) {}
} catch(PDOException $e) {}
}
} catch(PDOException $e) {}
I assume you want to enforce a valid database state with your pre cautions.
MySQL and PDO offer you the concept of transactions to ensure that a series of sql statements will only be executed all together.
Example
<?php
$db->beginTransaction();
// Query 2
$query = "update users set password = :password where username = :username";
$run_query = $db->prepare($query);
$run_query->execute(array(
':password' => password_hash($_POST['password'], PASSWORD_DEFAULT),
':username' => $data->username
));
// Query 3
$query = "update forgot_requests set valid = 0 where forgot_code = :forgot_code";
$run_query = $db->prepare($query);
$run_query->execute(array(':forgot_code' => $_POST['forgot_code']));
// All queries will be executed or no query will be executed
$db->commit();
?>
If you encounter any problems you can roll back a transaction:
<?php
$db->rollBack();
?>
Further information can be found in MySql manual: (http://dev.mysql.com/doc/refman/5.7/en/commit.html) and in php documentation (http://php.net/manual/de/pdo.begintransaction.php)

PHP check to see if MySQL table exists [duplicate]

This question already has answers here:
How can I check if a MySQL table exists with PHP?
(12 answers)
Closed 7 years ago.
I'm trying to see if a table already exists and then act accordingly. I was unable to solve my problem from viewing previous posts.I'm aware of a secondary problem where the sql throws an error but I don't know why it throws. When I replace $thisTable with the actual string, it works. But my primary problem is not being able to detect if the table exists.
$thisTable = "testX";
$thisTable = preg_replace("/[^A-Z,a-z,0-9]/", '', $thisTable);
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SHOW TABLES LIKE ".$thisTable;
//I get an SQL error here?
$stmt = $conn->prepare($sql);
$stmt->execute();
$isThere = $stmt->num_rows;
if ($isThere > 0){
echo "Already exists."
} else {
echo "Doesn't exist."
}
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage() . "<br/>WITH QUERY: " . $sql;
}
You need quotes around the table name in the query.
$sql = "SHOW TABLES LIKE '$thisTable'";

Categories