mysql不更新数据库

gzszwxb4  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(352)

似乎无法更新数据库。没有返回任何错误,所有变量都被传递到函数中,我在google上搜索了几个小时甚至几天。奇怪的是,我有另一个函数,它使用的代码和这个函数中的代码一样,工作正常。。。

public function updateCustomer($uname, $umail, $ushipping, $uchargeID, $udate, $ID)
{
    try {
        $dbhost = 'host';
        $dbuser = 'app';
        $db_name = 'order';
        $dbpass = '';
        $conn1 = mysql_connect($dbhost, $dbuser, $dbpass);
        $sql1 = "UPDATE customers
                  SET name = $uname, email = $umail, shipping = $ushipping, shipped = 'NO', charge_ID = $uchargeID, date = $udate
                  WHERE ID = $ID";
        mysql_select_db('orders');

        mysql_query($sql1);
        return ;

    } catch (PDOException $e) {
        echo $e->getMessage();
    }
}
sr4lhrrt

sr4lhrrt1#

正如我在上面的评论中提到的, mysql_query() 不会引发任何异常。您应该检查它的返回值,如果为false,则返回 mysql_error() . 您遇到的问题很可能是因为数据库中没有转义任何变量。无效语法:

UPDATE customers SET name = example_username

你想要这个:

UPDATE customers SET name = 'example_username'

你最好告诉mysql你想在哪里使用变量,让mysql使用准备好的语句。例如:

public function updateCustomer($uname, $umail, $ushipping, $uchargeID, $udate, $ID)
{
    try {
        $dbhost = 'host';
        $dbuser = 'app';
        $db_name = 'order';
        $dbpass = '';
        $db = new PDO("mysql:host={$dbhost};dbname={$db_name}", $dbuser, $dbpass);
        $sql1 = "UPDATE customers
                  SET name = :uname, email = :umail, shipping = :ushipping, shipped = 'NO', charge_ID = :ucharge_id, date = :udate
                  WHERE ID = :id";

        $stmt = $db->prepare($sql1);

        $res = $stmt->execute([
          'uname' => $uname,
          'umail' => $umail,
          'ushipping' => $ushipping,
          'ucharge_id' => $uchargeID,
          'udate' => $udate,
          'id' => $ID
        ]);
        return;

    } catch (PDOException $e) {
        echo $e->getMessage();
    }
}

相关问题