2013-05-06 57 views
1

我有一些PDO,我试图用来插入数据到MySQL表中。为什么没有插入到我的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()在页面顶部。

+0

您要添加三个参数到查询,但只有一个占位符。尝试用额外的问号替换$ title,$ url和$ _SESSION [\'tblUserID \'。现有的占位符添加了什么? – andrewsi 2013-05-06 17:12:06

+1

如果您使用准备好的语句,为什么还要将变量插入字符串中? – Barmar 2013-05-06 17:12:08

+1

您应该在PDO方法调用周围放置'try' /'catch'处理程序,以便在SQL中看到错误。 – Barmar 2013-05-06 17:13:06

回答

6

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

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

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

因为它是现在写的,你的查询是单位出语法错误,且易受SQL injection attacks

+0

谢谢!我忘了那个。 – mishmomo 2013-05-06 17:16:59

+1

看起来你忘了一个尾随的引用,它会导致语法突出显示出来。 – tadman 2013-05-06 17:26:11

+0

我认为它仍然是越野车,但我确实把它包装在try/catch中,并将变量从准备好的语句中提取出来。 – mishmomo 2013-05-06 17:43:42

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

+0

我尝试添加如此处所示的try/catch,但我没有收到任何异常。 – mishmomo 2013-05-06 17:41:30

+0

它是否将数据插入到表中?除非出现错误,否则不会显示任何异常。尝试将'echo $ title;'添加到您的代码中,并查看它是否输出了您期望的内容。如果它不能删除'私人功能。 。 .'并使它只是'function addResource()。 。 。 – 2013-05-06 18:11:40

+0

它现在有效。我不小心写了$ this-> resource - > $ url – mishmomo 2013-05-06 18:28:49

相关问题