douxian9010 2014-09-02 03:32
浏览 44
已采纳

带有查询的PHP MYSQLI问题 - SQL语法中的错误

I'm trying to run this query with mysqli :

"SELECT * FROM campaigns WHERE user_id = ".$_SESSION['username']['user_id']." AND status = 'Paused'"

And I'm getting the following error :

There was an error running the query [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 '\'Paused\'' at line 1]

I've searched for a solution but found none.

Any suggestions?


More code

public function query($query) {
    $query = $this->db2->real_escape_string($query);

    if(!$result = $this->db2->query($query)) {
        die('There was an error running the query [' . $this->db2->error . ']');
    }

    $this->count = $result->num_rows;

    return mysqli_fetch_all($result, MYSQLI_ASSOC);

    $result->free();
}
  • 写回答

1条回答 默认 最新

  • dongzhong2674 2014-09-02 03:54
    关注

    I'd really avoid query wrapper methods as they make it difficult to provide parameter values, especially to mysqli. Start with something more prescriptive, for example

    public function getUserCampaigns($userId, $status) {
        $stmt = $this->db2->prepare('SELECT * FROM campaigns WHERE user_id = ? AND status = ?');
        $stmt->bind_param('is', $userId, $status);
        $stmt->execute();
    
        $result = $stmt->get_result();
        return $result->fetch_all(MYSQLI_ASSOC);
    }
    

    and call it with

    $campaigns = $obj->getUserCampaigns($_SESSION['username']['user_id'], 'Paused');
    

    I also highly recommend you run this before creating your mysqli connection instance

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    

    as this will make mysqli report errors as exceptions, thus avoiding the need to write a bunch of error checking code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 maixpy训练模型,模型训练好了以后,开发板通电会报错,不知道是什么问题
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题