I am getting an error when updating a database using PDO.
I am new to PDO so maybe the problem is a small one and I just don't understand.
Funny thing about the error, the command works fine and the database does actually get updated.
But it still returns an error back at me.
Code:
try {
$stmt = $pdo->prepare("UPDATE $page SET $section = :new_content WHERE $section = '$old_content'");
$stmt->execute(array(
'new_content' => $new_content
));
$result = $stmt->fetchAll();
echo "Database updated!";
}
catch(PDOException $e) {
echo 'ERROR UPDATING CONTENT: ' . $e->getMessage();
}
Error:
ERROR UPDATING CONTENT: SQLSTATE[HY000]: General error
I literally have no idea where the problem could be because its very vaque and I haven't been able to find anyone with the same problem.
You do not use fetchAll(),as in
$result = $stmt->fetchAll();
with update or insert queries. Removing this statement should rectify the problem.
Just to note, another possible reason for this error is if you make a second database call with the variable $stmt inside of an existing parent $stmt loop.
$stmt = $conn->query($sql);
while ($row = $stmt->fetch()) { //second use of $stmt here inside loop
Related
I've a query in PHP that work well on localhost, but online I get error:
exception 'PDOException' with message 'SQLSTATE[07002]: COUNT field incorrect: -3010 [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 5.
This is my query:
$sql = "UPDATE 01Anagrafica
SET [01Anagrafica].[01DataOraUltimaModificaPassword] = ?,
[01Anagrafica].[01NomeUtente] = ?,
[01Anagrafica].[01Password] = ?
WHERE [01Anagrafica].[01ID] = ?";
$vars = array("2018/04/05 12:00:00", "username", "passwordtest", "15");
try {
$s = $db->prepare($sql);
$s->execute($vars);
} catch (PDOException $e) {
echo $e;
}
Work well on localhost, I get error if I put online.
UPDATE: OK I've found the real problem but not the solution. Error is in [01Anagrafica].[01DataOraUltimaModificaPassword] = ? (It's a Date/Hours .MDB access field).
When I was using $s->bindValue(':date', $date); method, all is working. But now i've to use ? prepared statement. But it doesn't work.
UPDATE 2: Found problem. It's only a typing error :(
I'm getting some unusual behavior when using PHP/PDO and doing an INSERT. Here is some sample code:
foreach ($all_users as $this_user) {
try {
$stmt = $db->prepare('INSERT INTO fav_colors (name, color, whattime) VALUES (:name, :color, :whattime)');
$stmt->bindValue(':name', $this_user[name]);
$stmt->bindValue(':color', $this_user[color]);
$stmt->bindValue(':whattime', $this_user[time]);
$stmt->execute();
$count = $stmt->rowCount();
} catch(PDOException $e) { catchMySQLerror($e->getMessage()); }
if ($count == 1) {
echo "Successful write to table";
} elseif ($count == 0) {
echo "ERROR writing row to table";
}
}
Lets say I have 10 names/colors to insert and the times are DATETIME format (2016-01-01 12:00:00). I have a loop around this code and after the code I check $count to see if the insert worked OK.
Here is my problem. One of the 10 inserts, for whatever reason the $write_time was blank. mySQL generated an error (can't be null). My custom function catchMySQLerror writes the error to a table and e-mails me. It did, but $count was still 1 for this entry and according to it, everything was fine even though the record did not insert.
So is my problem with the try/catch I am using here to catch the exception? How can I add something where I can better handle the error within the code? I know I can add more lines after the catchMySQLerror line and work with the error that way. That is what I have done. But I would like to handle the error using an if/else and with the approach I just mentioned, I can only handle the error... not if it was success.
UPDATE: I edited the code to show how I have been using $count
If ->execute() throws an exception, $count = $stmt->rowCount(); isn't executed and therefore $count keeps the value of the previous iteration (if there was one).
If you rely on that value, you have to (re-)initilize it at the beginning of every iteration.
this is how it have to be done
foreach ($all_users as $this_user) {
try {
$stmt = $db->prepare('INSERT INTO fav_colors (name, color, whattime) VALUES (:name, :color, :whattime)');
$stmt->bindValue(':name', $this_user[name]);
$stmt->bindValue(':color', $this_user[color]);
$stmt->bindValue(':whattime', $this_user[time]);
$stmt->execute();
} catch(PDOException $e) {
catchMySQLerror($e);
echo "ERROR writing row to table";
}
}
I know this you get this question a lot, but I haven't been able to get this to work with all of the answers on previous questions about the same problem. I've tried testing the query, and it works fine. I've copied and pasted the exact same query on PHPMyAdmin and it worked fine and I get no errors when I execute the query.
Here's my code:
try {
$selectProfilesQuery = 'SELECT profile_id, user_id, profile_name, profile_picture_50, profile_tile_cover FROM profile WHERE user_id = :user_id';
$prepSelectProfiles = $conn->prepare($selectProfilesQuery);
$prepSelectProfiles->bindParam(':user_id', $uid, PDO::PARAM_INT);
$prepSelectProfiles->execute();
$profilesResult = $prepSelectProfiles->fetchAll();
}
catch(PDOException $e) {
$conn = null;
header('Location: ../errors/error_101.html');
}
while ($profiles = $profilesResult->fetch(PDO::FETCH_ASSOC)) {
$profileId = $profiles['profile_id'];
$profileTileBg = $profiles['profile_tile_cover'];
$profileImage = $profiles['profile_picture_50'];
$profileName = $profiles['profile_name'];
}
I've tried to find any other error that maybe had anything to do with my query, but whatever I do it keeps giving me two results (which is the desired effect, but should happen inside the application and not in my DB management system).
Who knows what the problem is here? Becuase I'm staring at this code for 30 minutes now and it makes me go nuts.
The error says the problem is on the line with:
while ($profiles = $profilesResult->fetch(PDO::FETCH_ASSOC)) {
Remove the $profilesResult = $prepSelectProfiles->fetchAll(); and use $prepSelectProfiles->fetch() in while loop.
Or
Do a foreach on the result:
foreach($profilesResult as $profiles) {
//...
}
The fetch() should be on PDO Object
So take out
$profilesResult = $prepSelectProfiles->fetchAll();
and change
while ($profiles = $profilesResult->fetch(PDO::FETCH_ASSOC)) {
with
while ($profiles = $prepSelectProfiles->fetch(PDO::FETCH_ASSOC)) {
$profilesResult is an array after u did $profilesResult = $prepSelectProfiles->fetchAll(); and u are calling fetch() using $profilesResult
which is is why its failing
Yes, it is different from other questions.
Here you need only understand what are you doing. In this line you are getting an array
$profilesResult = $prepSelectProfiles->fetchAll();
of simple arrays, none of which being an instance of PDO statement
To make this code little saner and less wordy
$sql = 'SELECT profile_id, user_id, profile_name, profile_picture_50, profile_tile_cover '
. 'FROM profile WHERE user_id = :user_id';
$stmt = $conn->prepare($sql);
$stmt->execute([$uid]);
$profiles = $stmt->fetchAll();
while (foreach $profiles as $row) {
extract($row);
}
I am using CakePHP 2.4.1 and I need to get direct access to PDO in order to pull a set of records from my MySQL DB, row by row.
This is the piece of code that I am using and that is generating the issue:
// Get PDO access
$this->_pdo = $this->Event->getDataSource();
try {
// Start transaction
$this->_pdo->begin();
// All the past events
$stm = $this->_pdo->prepare("SELECT `id` FROM `events` WHERE `stop_time` < '" . date('Y-m-d H:i:s') . "'");
// Loop through the events
if( $stm->execute() ) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// ....
}
}
// Commit transaction
$this->_pdo->commit();
} catch (Exception $e) {
// Rollback transaction
$this->_pdo->rollback();
CakeLog::write('error', $e );
}
However as soon as I launch the script I get back this error message
PHP Fatal error: Call to undefined method Mysql::prepare()
but I have seen that this framework is supporting PDO and in particular the prepare() function.
CakePHP PDO Documentation
Any ideas?
Thanks a lot
Actually the class you are using is http://api.cakephp.org/2.4/class-DataSource.html
No prepare() method there. Use this to get PDO
$myPDO = $this->SomeModel->getDataSource()->getConnection();
I am getting an error when updating a database using PDO.
I am new to PDO so maybe the problem is a small one and I just don't understand.
Funny thing about the error, the command works fine and the database does actually get updated.
But it still returns an error back at me.
Code:
try {
$stmt = $pdo->prepare("UPDATE $page SET $section = :new_content WHERE $section = '$old_content'");
$stmt->execute(array(
'new_content' => $new_content
));
$result = $stmt->fetchAll();
echo "Database updated!";
}
catch(PDOException $e) {
echo 'ERROR UPDATING CONTENT: ' . $e->getMessage();
}
Error:
ERROR UPDATING CONTENT: SQLSTATE[HY000]: General error
I literally have no idea where the problem could be because its very vaque and I haven't been able to find anyone with the same problem.
You do not use fetchAll(),as in
$result = $stmt->fetchAll();
with update or insert queries. Removing this statement should rectify the problem.
Just to note, another possible reason for this error is if you make a second database call with the variable $stmt inside of an existing parent $stmt loop.
$stmt = $conn->query($sql);
while ($row = $stmt->fetch()) { //second use of $stmt here inside loop