$ data变量存储一个包含用户名和密码的数组,需要将其插入某个表中。
$data = array('username' => $username, 'password' => $password);
foreach($data as $key => $value){
$values = $values . "'" . $value . "'" . ",";
}
$sql = "INSERT INTO table(username, password) VALUES (?, ?)";
$query = $con->prepare($sql);
$query->execute($values);
如何更改此代码,以便将$ values变量的值打印到execute函数中?例如。 'NEWUSER', 'mysecretpass'
答案 0 :(得分:1)
你可以这样做:
$data = array('username' => $username, 'password' => $password);
$sql = "INSERT INTO table(username, password) VALUES (:username, :password)";
$query = $con->prepare($sql);
foreach($data as $key => $value){
$query->bindValue($key, $value);
#echo 'key = '.$key.' | value = '.$value;
}
$query->execute();
上面将每个值绑定到它的占位符,如果你想打印它们,你可以。
答案 1 :(得分:0)
试试这个!通过传递插入值数组来执行预准备语句。
$sql = "INSERT INTO table(username, password) VALUES (?, ?)";
$query = $con->prepare($sql);
$query->execute(array($username, $password));
答案 2 :(得分:0)
你可以bind这样的参数
$sql = "INSERT INTO table(username, password) VALUES (:user, :pass)";
$query = $con->prepare($sql);
$query->bindParam(':user', $data['username'] );
$query->bindParam(':pass', $data['password']);
$query->execute();