简体   繁体   中英

php - update with PDO not working

I am trying to update a row in a table in mysql database using PDO and taking the data from a form using post method.

For example this code does not do the job (id taken from session)...

$u = $_POST;
if( isset($_POST['update']) ) {
    $output = 'table';
    $usr = "update table set one=?, two=?, three=? where id=?";

    $one=$_POST['one'];
    $two=$_POST['two'];
    $three=$_POST['three'];

    $query=$db->prepare($usr);
    if( !$query->execute(array($one, $two, $three)) ) {
        $db->error;
    } else {
        print "update successful";
    }
}

It also doesn't work with four parameters like this:

$u = $_POST;
if( isset($_POST['update']) ) {
    $output = 'table';
    $usr = "update table set one=?, two=?, three=? where id=?";

    $one=$_POST['one'];
    $two=$_POST['two'];
    $three=$_POST['three'];
    $id=$_POST['id'];

    $query=$db->prepare($usr);
    if( !$query->execute(array($one, $two, $three, $id)) ) {
        $db->error;
    } else {
        print "update successful";
    }
}

This does not work either (again, id taken from session)...

$u = $_POST;
if( isset($_POST['update']) ) {
    $output = 'table';
    $usr = "update users set one=:one, two=:two, three=:three where id=?";
    $res = $db->prepare($usr);
    if(!$res->execute(array(':one'=>$u['one'],
                            ':two'=>$u['two'],
                            ':three'=>$u['three']))) {
        $error['usr'] = sprintf("%s could not be updated", htmlentities($_POST['firstname']));
        $output = 'form'; }
    else {
        //$status = sprintf("%s created", htmlentities['firstname']);
    }
}

I also tried this http://www.mustbebuilt.co.uk/php/insert-update-and-delete-with-pdo/ and it also didn't work...

The arguments to the execute() method aren't the good ones :

For the first example, the number of expected arguments is 4, you only give 3, the id parameter is missing.

For the second, please read the documentation, you musn't set the ":" char in the associative array you give as argument. The id argument is still missing.

you miss $id you pass only 3 arguments

try this code :-

if( !$query->execute(array($one, $two, $three,$id)) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM