mysqli :: prepare():无法获取MySQL

时间:2012-10-13 11:17:22

标签: php mysqli

我开始在PHP中使用mysqli_*函数而不是旧的mysql_*函数,我对此代码有点问题:

public function addUser($table, $code = false, $rows = false) {
   if (!$code) {
      header("Location: " . $this->authenticate());
   } else {
      $this->getToken($code);
   }
   $user = $this->getEndpoint('users/current', false, true);
   $user = $user->response->user;
   if (!$rows)
        $rows = array(
            "remote_id" => $user->id,
            "firstName" => $user->first_name,
            "lastName" => $user->last_name,
            "photo" => $user->photo->medium,
            "gender" => $user->gender == 'male' ? 1 : 2,
            "email" => $user->contact->email,
        );
   $rows['access_token'] = $this->accessToken;
   $stmt = $this->mysql->prepare("SELECT id FROM users WHERE access_token = '{$this->accessToken}'"); //line 136
   $stmt->execute(); //line 137
}

代码返回这两个错误:

  

警告:mysqli :: prepare():无法在第136行的C:\ Users \ Grega \ Server \ application \ inc \ classes \ APIConnect.php中获取MySQL

     

致命错误:在第137行的C:\ Users \ Grega \ Server \ application \ inc \ classes \ APIConnect.php中的非对象上调用成员函数execute()

“无法获取MySQL”的原因是什么?数据库连接是正确的,它在其他类中工作,并且查询返回有效结果,如果我回显它并在phpMyAdmin中执行它。另外,我的变量名为mysql NOT mysqli

1 个答案:

答案 0 :(得分:1)

您应该阅读有关MYSQL与MYSQLi之间差异的更多信息。

您的代码是:

$stmt = $this->mysql->prepare("SELECT id FROM users WHERE access_token = '{$this->accessToken}'");

你应该这样做:

$stmt = $this->mysql->prepare("SELECT id FROM users WHERE access_token = ?");
$stmt->bind_param("s" , $this->accessToken ); //Used 's' as I guess that the accessToken is a string

binding部分是prepare事物的关键部分。 (您的查询是安全的)

之后,您可以使用$stmt->execute();get_result()