dongyaxiao5884 2018-02-06 16:38
浏览 52
已采纳

使用PDO和变量进行MySQL更新

I'm having a strange problem with php PDO and mysql. I read other examples here, but while I am learning MySQL with the PDO, I did not understand it and I could not solve it yet.

$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";
  • 写回答

2条回答 默认 最新

  • du7999 2018-02-06 16:44
    关注

    The syntax for UPDATE with PDO is SET col=:col

    Using the column name, followed by the equal sign and the named placeholder.

    $PDO = $PDO->prepare( 'UPDATE users SET name = :name, email = :email, 
                           telefone = :telefone, endereco = :endereco, 
                           numero = :numero, bairro = :bairro, cidade = :cidade 
                           WHERE email = :email' ); 
    

    PDO error handling would have clearly shown you the errors:

    Use error reporting also.

    This assuming that the column names are of the same names that I used here.

    However and as stated, why use the $_REQUEST's? Just use the variables that you assigned in the POST arrays, and assuming that your form is using a post method.

    $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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。