Php 我做得对吗?
我刚刚把一个旧的Php 我做得对吗?,php,mysql,pdo,driver,Php,Mysql,Pdo,Driver,我刚刚把一个旧的mysql_*从一个旧的教程切换到PDO,想知道我做的是否正确。 我没有得到mysql和PDO,它们是驱动程序还是只是获取数据的不同变体 我的代码可以正常工作,但我有点怀疑它是否有效,因为我是一个初学者 <?php // New PDO variant try { $user = "user"; $pass = ""; $pdo = new PDO('mysql:host=localhost;dbname=testdb',
mysql_*从一个旧的教程切换到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();
}
?>
您应该使用preparedstatement
并使用?
传递参数,例如:
$sth = $dbh->prepare('SELECT * FROM ajax_example WHERE sex = ?');
$sth->execute(array('male'));
查询和参数将(显然)根据$age
和$wpm
的值而变化,但使用prepared语句和绑定参数将有助于防止出现这种情况。您几乎是对的,您刚刚错过了prepare()
这里的$name
是什么?我不知道。。必须是教程的剩余内容。。我该如何改进它呢?读这篇文章,这里有很多问题。。其中一个是您的SQL查询可以被SQL注入。检查绑定你的参数。
<?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/>";
}
?>