1

我有一些 PDO 试图用来将数据插入到 MySQL 表中。

private function addResource() {
    include('./dbconnect.php');
    $pdo = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_password);
    $stmt = $pdo->prepare('INSERT INTO Resources VALUES (?, $title, $url, $_SESSION[\'tblUserID\'');
    $stmt->bindParam(1, $title);
    $stmt->bindParam(2, $url);
    $stmt->bindParam(3, $_SESSION['tblUserID']);
    $stmt->execute();
    if ($stmt->rowCount() != 1)
        throw new Exception('Could not add resource');
    $status = true;
}

问题是,每当我检查表格时,都没有插入任何内容。怎么来的?

编辑:我在页面顶部有 session_start() 。

4

2 回答 2

6

因为您使用 PDO 完全错误。占位符不使用 PHP 变量语法。查询字符串应为:

$stmt = $pdo->prepare('INSERT INTO .... VALUES (:id, :title, :url, :userid')
                                                     ^^^^^^
$stmt->bindParam(':title', $title);
                  ^^^^^^

请注意:whatever占位符格式的使用。

正如现在所写的那样,您的查询是一个明显的语法错误,并且容易受到SQL 注入攻击

于 2013-05-06T17:12:51.767 回答
0

尝试这个:

private function addResource() {
      include('./dbconnect.php');
      try{
          $pdo = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_password);
          $stmt = $pdo->prepare('INSERT INTO Resources VALUES (:title, :url, :userid)';
          $stmt->bindParam(':title', $title);
          $stmt->bindParam(':url', $url);
          $stmt->bindParam(':userid', $_SESSION['tblUserID']);
          $stmt->execute();
          if ($stmt->rowCount() != 1)
            throw new Exception('Could not add resource');
          $status = true;
          }
       }catch (Exception $e){
          echo $e->getMessage();
          exit;
       }
    }

参考: http: //php.net/manual/en/pdo.prepared-statements.php

于 2013-05-06T17:24:21.543 回答