MySQL不更新数据库

时间:2018-07-28 19:46:36

标签: php mysql

似乎无法更新数据库。没有错误返回,所有变量都被传递到函数中,我已经搜索了几个小时甚至几天。奇怪的是,我有另一个函数使用的是与该函数正常工作的代码相同的代码...

    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();
    }
}

1 个答案:

答案 0 :(得分:3)

正如我在上面的评论中提到的,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();
    }
}