-1

我在这里做错了什么?我想也许 exec 中的变量有问题,但我有一个在另一个地方工作的模拟命令。注释部分返回 int(1) 作为受影响的行,此代码返回以下错误。非常感谢您的建议,我只是在学习。

"object(PDO)#2 (0) { } Array ( [0] => 42000 [1] => 1064 [2] => 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 'try, Wed, 06 Mar 2013 13:25:09 +0200)' at line 1 ) "

代码 :

<?php
class gbMsg {
    private $_db;
    private $dbc;

    function __construct(){
        $this->dbc = parse_ini_file($_SERVER["DOCUMENT_ROOT"]."/lock/conect.ini");
        try{
            $this->_db = new PDO($this->dbc["conn"], $this->dbc["user"], $this->dbc["pass"]);
        }catch(PDOException $e){
            echo $e->getMessage();
        }
    }

    function addPost($name, $msg){
        echo var_dump($this->_db);
        $d = date("r");
        $stmt = $this->_db->exec("INSERT INTO gPosts (name, message, date) VALUES ($name,$msg, now())")
        or die(print_r($this->_db->errorInfo(), true));
        echo var_dump($stmt);
    }
}

#   function addPost(){
#       echo var_dump($this->_db);
#       $stmt = $this->_db->exec("INSERT INTO gPosts (name, message, date) VALUES ('Kirill','sec', now())");
#       echo var_dump($stmt);
#   }
#}
4

2 回答 2

2

但是,用户参数化查询更好地解决您的问题:

 $stmt = $this->_db->exec("INSERT INTO gPosts (name, message, date)
 VALUES (\"$name\",\"$msg\", now())")

你忘了引号...

您可以在此处阅读有关参数化查询和准备好的语句的更多信息:http: //php.net/manual/en/pdo.prepared-statements.php

于 2013-03-06T11:35:36.223 回答
-1

我想像下面这样的东西也应该起作用。恕我直言,它看起来比转义双引号要干净得多

$stmt = $this->_db->exec("INSERT INTO gPosts (name, message, date)
 VALUES ('$name','$msg', now())")
于 2014-07-28T14:04:27.890 回答