我在使用php PDO和mysql时遇到了一个奇怪的问题。
我在这里阅读了其他示例,但是当我通过PDO学习MySQL时,我不理解它,也无法解决它。
$name = $_POST[ "name" ];
$email = $_POST[ "email" ];
$telefone = $_POST[ "telefone" ];
$endereco = $_POST[ "endereco" ];
$numero = $_POST[ "numero" ];
$bairro = $_POST[ "bairro" ];
$cidade = $_POST[ "cidade" ];
$telefoneHash = make_hash( $telefone );
$PDO = db_connect();
//$PDO->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//With this code it gives the error: 'Syntax error or access violation: 1064'
//Without it it does not give an error but does not perform the update
$PDO = $PDO->prepare( 'UPDATE users SET :name, :email, :telefone, :endereco, :numero, :bairro, :cidade WHERE email = :email' );
$PDO->bindValue( ':name', $_REQUEST[ 'name' ] );
$PDO->bindValue( ':email', $_REQUEST[ 'email' ] );
$PDO->bindValue( ':telefone', $telefoneHash );
$PDO->bindValue( ':endereco', $_REQUEST[ 'endereco' ] );
$PDO->bindValue( ':numero', $_REQUEST[ 'numero' ] );
$PDO->bindValue( ':bairro', $_REQUEST[ 'bairro' ] );
$PDO->bindValue( ':cidade', $_REQUEST[ 'cidade' ] );
$PDO->execute();
echo $PDO->rowCount() . " records UPDATED successfully";
最佳答案
使用PDO进行UPDATE的语法为SET col=:col
使用列名,后跟等号和命名的占位符。
$PDO = $PDO->prepare( 'UPDATE users SET name = :name, email = :email,
telefone = :telefone, endereco = :endereco,
numero = :numero, bairro = :bairro, cidade = :cidade
WHERE email = :email' );
PDO错误处理将清楚地向您显示错误:
https://secure.php.net/manual/en/pdo.error-handling.php
还使用错误报告。
https://php.net/manual/en/function.error-reporting.php
假设列名与我在此处使用的名称相同。
但是,如上所述,为什么要使用
$_REQUEST
?只需使用您在POST数组中分配的变量,并假定您的表单使用的是post方法。$PDO->bindValue(':name', $name);
$PDO->bindValue(':email', $email);
$PDO->bindValue(':telefone', $telefoneHash);
$PDO->bindValue(':endereco', $telefone);
$PDO->bindValue(':numero', $numero);
$PDO->bindValue(':bairro', $bairro);
$PDO->bindValue(':cidade', $cidade);
$PDO->execute();
关于php - 使用带有变量的PDO进行MySQL更新,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48647802/