我不熟悉在 mysql 和 php 中使用准备好的语句。我需要一些帮助来创建准备好的语句来检索列。
我需要从不同的列中获取信息。目前对于测试文件,我使用完全不安全 SQL 语句:
$qry = "SELECT * FROM mytable where userid='{$_GET['userid']}' AND category='{$_GET['category']}'ORDER BY id DESC"
$result = mysql_query($qry) or die(mysql_error());
有人可以帮我创建一个 secure 使用来自准备好的 url 参数(如上)的输入的 mysql 语句吗?
奖励:准备好的语句也可以提高速度。如果我在一个页面上只使用三到四次准备好的语句,它会提高整体速度吗?
最佳答案
这是一个使用 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 *),而不是必须准确指定要绑定(bind)的变量,这里有一个方便的函数:
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 - 如何在 php 中创建安全的 mysql 准备语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1290975/