下面是使用mysqli的(對象的語法 - 很容易轉化爲函數的語法,如果你願意的話)的例子:
$db = new mysqli("host","user","pw","database");
$stmt = $db->prepare("SELECT * FROM mytable where userid=? AND category=? ORDER BY id DESC");
$stmt->bind_param('ii', intval($_GET['userid']), intval($_GET['category']));
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($column1, $column2, $column3);
while($stmt->fetch())
{
echo "col1=$column1, col2=$column2, col3=$column3 \n";
}
$stmt->close();
另外,如果你想要一個簡單的方法來抓取關聯數組(與SELECT使用*),而不必明確指定變量綁定到,這裏有一個方便的功能:
function stmt_bind_assoc (&$stmt, &$out) {
$data = mysqli_stmt_result_metadata($stmt);
$fields = array();
$out = array();
$fields[0] = $stmt;
$count = 1;
while($field = mysqli_fetch_field($data)) {
$fields[$count] = &$out[$field->name];
$count++;
}
call_user_func_array(mysqli_stmt_bind_result, $fields);
}
要使用它,只需調用它,而不是調用bind_result:
$stmt->store_result();
$resultrow = array();
stmt_bind_assoc($stmt, $resultrow);
while($stmt->fetch())
{
print_r($resultrow);
}
可能重複[在PHP中停止SQL注入的最佳方法](http://stackoverflow.com/questions/60174/best-way-to-stop-sql-injection-in-php) – outis 2012-03-26 02:05:41