假定一个合法的用户输入了字符串"lemming",那么这个例程将(假定是数据库中适当的数据)输出消息"A lemming has very low intelligence."。假定存在一个尝试性注入-例如"lemming' or 1=1;",那么这个例程将打印(无害)消息"Sorry, no records found."。
此外,mysqli扩展还提供了一个面向对象版本的相同的例程。下面,我们想说明这种版本的使用方法。
<?php
$animalName = $_POST['animalName'];
$mysqli = new mysqli( 'localhost', 'username', 'password', 'database');
if ( !$mysqli ) exit( 'connection failed: ' . mysqli_connect_error() );
$stmt = $mysqli->prepare( "SELECT intelligence
FROM animals WHERE name = ?" );
if ( $stmt ) {
$stmt->bind_param( "s", $animalName );
$stmt->execute();
$stmt->bind_result( $intelligence );
if ( $stmt->fetch() ) {
print "A $animalName has $intelligence intelligence.\n";
} else {
print 'Sorry, no records found.';
}
$stmt->close();
}
$mysqli->close();
?>