dsghpgmay31938863
2018-06-04 22:08
浏览 64
已采纳

奇怪的未解决的PDO错误:语法错误或访问冲突:1064您的SQL语法中有错误;

I have got an error in a php script:

PHP Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 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 '' at line 1 in /var/www/html/a.php:143

Pay attention it says near ''(two single quotations). This script used to work correctly on my previous server but when I moved to the new server, it kept showing this error. My PHP version is 7.0 and Mysql version is 5.7.22.

How I connected to mysql:

try{
    $pdo = new PDO("mysql:host=localhost;dbname=db_name", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
} catch(PDOException $e){
    echo "Connection failed: " . $e->getMessage();
}

It prints: "Connected successfully". These are lines 142 and 143 which contain PDO queries:

$stmt = $pdo->prepare("SELECT has_paid FROM info WHERE chat_id=".$chat_id);
$stmt->execute();

I visited similar questions but they didn't help.

How can I solve this?

图片转代码服务由CSDN问答提供 功能建议

我在 php 脚本中出错: \ n

PHP致命错误:未捕获PDOException:SQLSTATE [42000]:语法错误 或访问冲突:1064 SQL语法中有错误; 检查与您的MySQL服务器版本对应的手册,以便在/var/www/html/a.php:143 中的第1行''附近使用正确的语法 n

注意它附近的''(两个单引号)。 这个脚本曾经在我以前的服务器上正常工作但是当我搬到新服务器时,它一直显示这个 错误。 我的PHP版本是7.0,Mysql版本是5.7.22。

我如何连接到mysql:

  try {
 $ pdo  = new PDO(“mysql:host = localhost; dbname = db_name”,$ username,$ password); 
 $ pdo-> setAttribute(PDO :: ATTR_ERRMODE,PDO :: ERRMODE_EXCEPTION); 
 echo“已成功连接”  ; 
} catch(PDOException $ e){
 echo“连接失败:”。  $ e-> getMessage(); 
} 
   
 
 

打印:“已成功连接”。 这些是包含PDO查询的第142和143行:< / p>

  $ stmt = $ pdo-&gt; prepare(“SELECT has_paid FROM info WHERE chat_id =”。$ chat_id); 
 $ stmt-&gt; execute(); 
    
 
 

我访问了类似的问题,但他们没有帮助。

我该如何解决这个问题?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douxing1969 2018-06-04 22:12
    已采纳

    I suspect your $chat_id is empty. So your SQL query ends up being:

    SELECT has_paid FROM info WHERE chat_id=
    

    MySQL syntax errors report the part of the SQL query that follows the place where MySQL got confused. In this case, it reports an error near '' because it got confused at the end of the query. This is not surprising, because = requires a right-hand-side argument.

    You should examine the code where you set $chat_id and make sure it has a non-empty value before attempting your query.

    By the way, it seems strange to me that you're using prepare() and execute() but you're not using query parameters. You should code it this way:

    $stmt = $pdo->prepare("SELECT has_paid FROM info WHERE chat_id=?");
    $stmt->execute([$chat_id]);
    

    (There is no need to use bindValue() as some people will say.)

    评论
    解决 无用
    打赏 举报
  • 查看更多回答(1条)

相关推荐 更多相似问题