【发布时间】:2015-12-03 16:24:52
【问题描述】:
我正在尝试使用 PDO 和绑定参数将数据从表单插入到 MYSQL 数据库。我首先尝试在没有 PDO 和 bindParam 的情况下进行插入,并且成功地从表单中获取数据并插入到数据库中,但是该基本方法对 SQL 注入是开放的。现在我正在使用以下(参见下面的代码)PDO 和 bindParam 方法,但数据没有被插入到我的数据库中。
问题:我做错了什么?是否存在一些不允许我将数据插入数据库的语法问题?
<?php
$username = 'username';
$password = 'pass';
$host = 'localhost';
$dbname = 'db';
try {
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("INSERT INTO table1 (issue, time, comments, lat, lng) VALUES (:issue, :time, :comments, :lat, :lng)");
$stmt->bindParam(':issue', $issue);
$stmt->bindParam(':time', $time);
$stmt->bindParam(':comments', $comments);
$stmt->bindParam(':lat', $lat);
$stmt->bindParam(':lng', $lng);
$stmt->execute();
header("Location: main.php");
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$dbh = null;
?>
编辑:(仍然不工作)
<?php
$username = 'username';
$password = 'pass';
$host = 'localhost';
$dbname = 'db';
try {
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (!isset($issue, $time, $comments, $lat, $lng)) {
die('data set error;');
}
$stmt = $dbh->prepare("INSERT INTO table1 (issue, time, comments, lat, lng) VALUES (:issue, :time, :comments, :lat, :lng)");
$params = array(':issue' => $issue,
':time' => $time,
':comments' => $comments,
':lat' => $lat,
':lng' => $lng);
if (!$stmt->execute($params)) {
print_r($stmt->errorInfo());
die();
}
header("Location: main.php");
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$dbh = null;
?>
【问题讨论】:
-
你在
$issue哪里插入数据? -
试试
echo $issue;看看字段里有没有值。