我正在尝试使用一些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()。
答案 0 :(得分:6)
因为您使用的PDO完全错误。占位符不使用PHP变量语法。查询字符串应为:
$stmt = $pdo->prepare('INSERT INTO .... VALUES (:id, :title, :url, :userid')
^^^^^^
$stmt->bindParam(':title', $title);
^^^^^^
请注意使用:whatever
格式的占位符。
正如现在所写的那样,您的查询是一个彻底的语法错误,容易受到SQL injection attacks的攻击
答案 1 :(得分: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;
}
}