基于id = in url调用字段 - Php

时间:2011-03-25 01:28:36

标签: php

<?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);
?>

1 个答案:

答案 0 :(得分:0)

让我们使用PDO,最好的内置数据库适配器和filter extension来保护我们的输入。

// 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);

糟糕,请尝试此订单:

$pdo = new PDO('mysql:host=localhost;dbname=...', $username, $password);
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );