<?php
// Filter our input.
$pID = filter_input(INPUT_GET, 'pID', FILTER_SANITIZE_NUMBER_INT);
if(!$pID) {
echo "No pID specified.";
exit;
}
// Throw exceptions on errors. You will need to catch these.
PDO::setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$username = "##";
$password = "##";
// You'll want to fill in the database name, and define the un/pw
$pdo = new PDO('mysql:host=localhost;dbname=dbname', $username, $password);
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
// Prepare a statement to be executed.
// <http://us2.php.net/manual/en/pdo.prepare.php>
$sth = $pdo->prepare('
SELECT fname, lname
FROM Professor
WHERE pID = ?
');
// Execute the prepared statement. The values in the array are
// automatically escaped and quoted, and placed where the question
// marks are in the prepared statement. *Used correctly*, this method
// makes you immune from SQL Injection.
// <http://us2.php.net/manual/en/pdostatement.execute.php>
$sth->execute(array(
$pID
));
// Did we get any results?
if($sth->rowCount() > 0) {
// Yes! Fetch one row as an associative array.
// <http://us2.php.net/manual/en/pdostatement.fetch.php>
$row = $sth->fetch(PDO::FETCH_ASSOC);
echo "I found {$row['fname']} {$row['lname']}.";
} else {
// Nope, let the user know we found nothing.
echo "No results.";
}
unset($sth);
?>

基于id = in url调用字段 - Php
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- duanhuan1147 2011-03-25 01:44关注
Let's use PDO, the best built-in database adapter and the filter extension to protect our input.
// Filter our input. $pID = filter_input(INPUT_GET, 'pID', FILTER_SANITIZE_NUMBER_INT); if(!$pID) { echo "No pID specified."; exit; } // You'll want to fill in the database name, and define the un/pw $pdo = new PDO('mysql:host=localhost;dbname=...', $username, $password); // Throw exceptions on errors. You will need to catch these. $pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); // Prepare a statement to be executed. // <http://us2.php.net/manual/en/pdo.prepare.php> $sth = $pdo->prepare(' SELECT fname, lname FROM Professor WHERE pID = ? '); // Execute the prepared statement. The values in the array are // automatically escaped and quoted, and placed where the question // marks are in the prepared statement. *Used correctly*, this method // makes you immune from SQL Injection. // <http://us2.php.net/manual/en/pdostatement.execute.php> $sth->execute(array( $pID )); // Did we get any results? if($sth->rowCount() > 0) { // Yes! Fetch one row as an associative array. // <http://us2.php.net/manual/en/pdostatement.fetch.php> $row = $sth->fetch(PDO::FETCH_ASSOC); echo "I found {$row['fname']} {$row['lname']}."; } else { // Nope, let the user know we found nothing. echo "No results."; } unset($sth);
Whoops, try this order instead:
$pdo = new PDO('mysql:host=localhost;dbname=...', $username, $password); $pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报