mysql_ to pdo:我做对了吗?
问题描述:
(browseroutput.jpg)mysql_ to pdo:我做对了吗?
我刚换一个旧mysql_* from
一个老教程PDO,并想知道是否即时通讯做是正确的。 我没有得到mysql_*
和PDO,他们是驱动程序还是只是不同的变体来获取数据?
我的代码工作,因为它应该,但林有点怀疑它的工作,因为我是一个初学者。
<?php
// New PDO variant
try {
$user = "user";
$pass = "";
$pdo = new PDO('mysql:host=localhost;dbname=testdb', $user, $pass);
//build query
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
$query = "SELECT * FROM ajax_example WHERE sex = '$sex'";
if(is_numeric($age))
$query .= " AND age <= $age";
if(is_numeric($wpm))
$query .= " AND wpm <= $wpm";
$stmt = $pdo->prepare($query);
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";
$stmt->execute(array('name' => $name));
foreach ($stmt as $row) {
$display_string .= "<tr>";
$display_string .= "<td>$row[name]</td>";
$display_string .= "<td>$row[age]</td>";
$display_string .= "<td>$row[sex]</td>";
$display_string .= "<td>$row[wpm]</td>";
$display_string .= "</tr>";
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
答
You'we几乎是正确的,你只是错过了prepare()
<?php
// New PDO variant
try {
$user = "user";
$pass = "";
$pdo = new PDO('mysql:host=localhost;dbname=testdb', $user, $pass);
//build query
$age = intval($_GET['age']);
$sex = $_GET['sex'];
$wpm = intval($_GET['wpm']);
$query = "SELECT * FROM ajax_example WHERE sex = ? AND age <= ? AND wpm <= ?";
$stmt = $pdo->prepare($query);
$stmt->execute(array($sex,$age,$wpm));
$results = $stmt->fetchall();
if (count($results > 0)) {
echo "<table>";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Age</th>";
echo "<th>Sex</th>";
echo "<th>WPM</th>";
echo "</tr>";
foreach ($results as $row) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['sex'] . "</td>";
echo "<td>" . $row['wpm'] . "</td>";
echo "</tr>";
}
echo "</table>";
}else{
echo "no results available";
}
}
catch (PDOException $e) {
echo "Error!: " . $e->getMessage() . "<br/>";
}
?>
答
您应该使用preparedstatement
与?
传递的参数,如:
$sth = $dbh->prepare('SELECT * FROM ajax_example WHERE sex = ?');
$sth->execute(array('male'));
查询和参数将(显然)的变化取决于$age
和$wpm
值,但使用准备语句和绑定参数将有助于防止SQL Injection。
什么是'$ name'这里的要点? –
我不知道..必须是教程中的剩余物..我该如何改进它? – sinankarateke
阅读此https://*.com/a/767520/3568847 –