Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MySQL UPDATE statement not working

I have a MySQL database with a table (opendpu) that has multiple columns including columns titled "ECRNUM" and "PE_REQUIRED".

I'm simply trying to test this update statement by specifying some values. I get this error:

Array ( [0] => 42000 [1] => 1064 [2] => You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DOE WHERE ECRNUM = 81308' at line 1 )

I cannot, for the life of me, figure out what is wrong here. Can anyone help?

<?php
  require ('config.php');
 $ecrno = '81308';
 $pe_required = 'JOHN DOE';

while (true) {
try {
    $db = new PDO($dsn, $uname, $pword);
    $db->exec( "SET CHARACTER SET utf8" );
    $db->setAttribute( PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC ); 
    $db->setAttribute( PDO::ATTR_PERSISTENT, true );
    break;
}
    catch (Exception $e) {
        $db = null;
        $counter++;
        if ($counter == $limit)
            throw $e;
    }
}

$stmt = $db->prepare("UPDATE opendpu SET PE_REQUIRED = $pe_required WHERE ECRNUM = $ecrno");
$stmt->execute() or die(print_r($stmt->errorInfo(), true));

  ?>

.

like image 828
bagofmilk Avatar asked Jun 26 '26 01:06

bagofmilk


2 Answers

+1 for using prepared statements... but (and its a big BUT):

You should never use prepared statements without bind_param as this leaves you wide open to SQL injection and negates the benefits of prepared statements.

$stmt = $db->prepare("UPDATE opendpu SET PE_REQUIRED=? WHERE ECRNUM=?");
$stmt->bind_param('si', $pe_required, $ecrno);
$stmt->execute() or die(print_r($stmt->errorInfo(), true));
like image 102
hammus Avatar answered Jun 28 '26 19:06

hammus


Change your syntax like this [Enclosed quotes around the variable]

$stmt = $db->prepare("UPDATE `opendpu` SET PE_REQUIRED = '$pe_required' WHERE ECRNUM = '$ecrno'");
like image 34
Shankar Narayana Damodaran Avatar answered Jun 28 '26 19:06

Shankar Narayana Damodaran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!