作者:嘎嘎19850820 | 来源:互联网 | 2023-05-19 00:44
Iveseenacoupleofquestionsoverthelastfewdaysthathaveusedmysqlibutwheretheanswersa
I've seen a couple of questions over the last few days that have used mysqli
but where the answers appear to have not recognised the difference between $stmt->execute()
and $db->query()
.
我在过去几天看到了几个使用mysqli的问题,但答案似乎没有认识到$ stmt-> execute()和$ db-> query()之间的区别。
As I understand it, there are two differing models for accessing results in mysqli
.
据我了解,在mysqli中访问结果有两种不同的模型。
This one uses raw SQL and requires the programmer to escape the input to prevent SQL injection attacks, but allows the programmer to retrieve an associative array (or a plain array) containing column => value
mappings:
这个使用原始SQL并要求程序员转义输入以防止SQL注入攻击,但允许程序员检索包含column => value mappings的关联数组(或普通数组):
$result_set = $db->query("SAFE SQL QUERY HERE");
while ($row = $result_set->fetch_assoc()) {
# do something with $row['fieldname'];
}
Alternatively, you can do this, which allows nice binding of parameters and results, but cannot (AFAIK) give you any sort of simple array result:
或者,你可以这样做,它允许很好地绑定参数和结果,但不能(AFAIK)给你任何类型的简单数组结果:
$stmt = $db-prepare("SQL QUERY WITH ? PLACEHOLDERS");
$stmt->bind_param("s", $input_variable);
$stmt->execute();
$stmt->bind_results($output_col1, $output_col2);
while ($stmt->fetch()) {
# do something with $output_col1 and $output_col2
}
My question is - is there any way with mysqli
to get the simple array output shown in the first pattern, but whilst still using safely bound input parameters as per the second pattern?
我的问题是 - 有没有办法用mysqli来获得第一个模式中显示的简单数组输出,但是仍然使用安全绑定的输入参数按照第二个模式?
I can't find anyway to do this (other than using PDO
instead!).
我无论如何都找不到这个(除了使用PDO!)。
3 个解决方案
Alnitak,
AFAIK, you cannot bind an entire array to the fetched results automatically. Unfortunately. However, if you're looking for array behavior out of it (presumably so it's easier to pass the results around), you could try this:
AFAIK,您无法自动将整个数组绑定到获取的结果。不幸。但是,如果您正在寻找其中的数组行为(可能因此更容易传递结果),您可以尝试这样做:
prepare( 'SELECT id, email FROM email_list' );
{
$stmt->execute();
$stmt->bind_result( $arr['id'], $arr['email'] );
while( $stmt->fetch() )
DoSomething( $arr );
}
?>
This will give you the behavior you requested, above. It will not, however, dynamically bind array fields to associative indeces in the array -- that is, you must specify that id be bound to $arr['id'], etc.
这将为您提供上述请求的行为。但是,它不会将数组字段动态绑定到数组中的关联indeces - 也就是说,必须指定将id绑定到$ arr ['id']等。
If dynamic binding to the associative indeces is really required by your scenario, you could always write a simple class that would first parse the query for the selected fields, then setup the assoc array indeces, then perform the query.
如果您的方案确实需要动态绑定到关联indeces,则可以始终编写一个简单的类,该类首先解析所选字段的查询,然后设置assoc数组indeces,然后执行查询。