Mon*_*ica 1 php mysql pdo insert
我有一些我想用来将数据插入MySQL表的PDO.
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;
}
Run Code Online (Sandbox Code Playgroud)
事实上,每当我检查表时,都没有插入任何内容.怎么会?
编辑:我在页面顶部有session_start().
因为你使用PDO完全错了.占位符不使用PHP变量语法.查询字符串应为:
$stmt = $pdo->prepare('INSERT INTO .... VALUES (:id, :title, :url, :userid')
^^^^^^
$stmt->bindParam(':title', $title);
^^^^^^
Run Code Online (Sandbox Code Playgroud)
请注意使用:whatever占位符的格式.
正如现在编写的那样,您的查询是一个平坦的语法错误,容易受到SQL注入攻击