【问题标题】:php - update with PDO not workingphp - 使用 PDO 更新不起作用
【发布时间】:2015-10-30 10:15:43
【问题描述】:

我正在尝试使用 PDO 更新 mysql 数据库中表中的一行,并使用 post 方法从表单中获取数据。

例如,此代码无法完成工作(从会话中获取的 ID)...

$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";
    }
}

它也不适用于像这样的四个参数:

$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";
    }
}

这也不起作用(同样,id 取自会话)...

$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']);
    }
}

我也试过这个http://www.mustbebuilt.co.uk/php/insert-update-and-delete-with-pdo/,它也没有用......

【问题讨论】:

  • 确保数据与数据库中已有的数据不同。如果它相同,它将返回 0 行更改
  • 如果我在更新它意味着我正在做一些改变,不是吗?......只是在想......
  • 其中一个答案发生了什么?...

标签: php mysql pdo


【解决方案1】:

execute() 方法的参数不是好的参数:

对于第一个例子,期望的参数个数是4个,你只给3个,id参数就没有了。

第二个,请阅读文档,你不能在作为参数的关联数组中设置“:”字符。 id 参数仍然缺失。

【讨论】:

  • 对不起,但在第二种情况下,“:”字符是必需的,否则 PDO 无法正确绑定值。此解决方案的优点是绑定参数的顺序无关紧要。
  • 第一个例子 - 添加第四个参数(id)不会改变任何东西
  • 尝试打印错误!这一行什么都不做:$db->e​​rror;
  • 至少,$id 变量是否存在于您的脚本中?
  • @Kern & ThinkTank :冒号或无冒号,无论哪种方式都可以。在内部,它以 开头的冒号存储,但如果您将其省略,它只会为您添加。
【解决方案2】:

你错过了$id 你只传递了 3 个参数

试试这个代码:-

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

【讨论】:

  • 更新表集 one='$one', two='$two', three='$three' where id='$id'
  • 打印此查询并在 phpmyadmin @mt_had 上运行
猜你喜欢
  • 2016-01-07
  • 1970-01-01
  • 2013-10-04
  • 2017-09-27
  • 2015-11-21
  • 1970-01-01
  • 2014-07-09
  • 1970-01-01
  • 2013-01-03
相关资源
最近更新 更多