使用PHP脚本更新MySQL表

时间:2017-08-23 07:32:16

标签: php mysql

我正在开发一个Android应用程序,我希望将用户的地址插入到调用网站上的PHP脚本的数据库中。

在第一次尝试时,它必须将地址插入数据库,然后,它已更新相同的元组。

这是我的PHP脚本,但它在第36行(调用成员函数bind_param())时出错。

然而,插入工作完全正常。

get '/events/:id' do
  get 'https://api.teamsnap.com/v3/events/76674685'
end

3 个答案:

答案 0 :(得分:1)

根据您的评论,错误是因为呼叫prepare失败。 以下代码将允许获取更多信息:

        if($this->isAddressExist($id_user, $address))
        {   
            $stmt = $this->con->prepare("UPDATE address a, users u SET `address`=$address,`road`=$road,`city`=$city,`country`=$country WHERE a.id_user=u.id");
            if($stmt != False) {
              $stmt->bind_param("ssss", $address, $road, $city, $country);
              if ($stmt->execute()){
                  return 2;
              } else {
                  return 3;
              }
            } else {
              // this line will give an insight into an error message
              echo $this->con->error;
            }
        }

收到MySQL的错误消息后:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'road=Sarak,city=Khost,country=Afghanistan WHERE a.id_user= 10' at line 1

我们找到了确切的错误位置,并且使用了$address变量,而它应该是?!这样的陈述无法准备。

使用以下更新语句应修复它:

$stmt = $this->con->prepare("UPDATE address a, users u SET `address`=?,`road`=?,`city`=?,`country`=? WHERE a.id_user=u.id");

答案 1 :(得分:1)

public function Address($id_user, $address, $road, $city, $country) {
        if($this->isAddressExist($id_user))
    {   
        $stmt = $this->con->prepare("UPDATE address SET `address`=?,`road`=?,`city`=?,`country`=? WHERE id_user= ?");
        if($stmt != False) {
          $stmt->bind_param("ssss", $address, $road, $city, $country,$id_user);
          if ($stmt->execute()){
              return 2;
          } else {
              return 3;
          }
        } else {
          // hopefully this line will give an insight into an error message
          echo $this->con->error;
        }
    } else{
            $stmt = $this->con->prepare("INSERT INTO `address` (`id_address`, `id_user`,`address`, `road`, `city`, `country`) VALUES (NULL, ?, ? , ? ,? ,? );"); 
            $stmt->bind_param ("sssss", $id_user, $address, $road, $city, $country);

            if ($stmt->execute()){
                return 0;
            } else {
                return 1;
            }
        }

    }

这应该有效。在参数绑定方面你必须使用? (问号)而不是参数名称,并在bind_param函数中按正确的顺序按名称绑定参数。

答案 2 :(得分:0)

$stmt = $this->con->prepare("UPDATE address SET `address`=$address,`road`=$road,`city`=$city,`country`=$country WHERE a.id_user=u.id");

尝试更新一个表