PDO准备的更新声明无法正常运行 [英] PDO prepared statement for update doesn't work properly

查看:74
本文介绍了PDO准备的更新声明无法正常运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的php代码:

public function update($table,$fields_and_values,$condition_field,$condition_field_value)
{
    $query="UPDATE $table SET ";
    foreach($fields_and_values as $field=>$value) $query.=($field."=:".$field." ,");
    $query.=" ";
    $query=str_replace(", "," WHERE ",$query);
    $query.=($condition_field."='".$condition_field_value."'");
    echo $query;
    $stmt=$this->conn->prepare($query);
    foreach($fields_and_values as $field=>$value) $stmt->bindParam(":".$field,$value);
    $stmt->execute();
}

这就是我在课堂上调用函数的方式:

and this is how i call the function in my class:

    $db=new db_connection('localhost','root','','maps');
$db->connect();
    $arr=array('username'=>'testfromnewclass3','password'=>'123456');
    $db->update('users',$arr,'username','term');
    $db->disconnect();

其他功能(例如断开连接)做什么都没有关系!它们可以正常工作.
我的问题是执行此命令时, username password 都变为123456! 这就是我从echo $query那里得到的:

It doesn't matter what the other functions like disconnect do! They work correctly.
My problem is that when this command executes, both username and password become 123456 ! And this is what i get from that echo $query:

UPDATE users SET username=:username ,password=:password WHERE username='term'

我的功能有问题吗?如果可以的话,我该如何解决?

Is something wrong with my function? and if so how can i fix it?

推荐答案

使用$stmt->bindValue($field, $value); 代替$stmt->bindParam(":".$field,$value);

选中此以了解PDOStatement::bindParam()之间的区别和PDOStatement::bindValue()

Check this to understand difference between PDOStatement::bindParam() and PDOStatement::bindValue()

这篇关于PDO准备的更新声明无法正常运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆