考虑使用准备好的语句,因为 mysql_ 已被弃用。如果您粗心或缺乏经验并且没有正确转义查询字符串,它也容易受到 SQL 注入的影响。
这是使用mysqli_的解决方案:
$link = mysqli_connect("localhost", "user", "password", "database") or die(mysqli_error($link));
$stmt = mysqli_stmt_init($link);
$query = 'SELECT NAME,AUTHOR,CITY FROM TESTIMONIALS ORDER BY RAND() LIMIT 3';
$arrTestimonials = array();
if (mysqli_stmt_prepare($stmt, $query)) {
mysqli_stmt_bind_result($stmt, $out_name, $out_author, $out_city);
mysqli_stmt_execute($stmt);
while (mysqli_stmt_fetch($stmt)) {
$arrTestimonials[]['name'] = $out_name;
$arrTestimonials[]['author'] = $out_author;
$arrTestimonials[]['city'] = $out_city;
}
} // error preparing statement
数组的结构如下:
Array
(
[0] => Array
(
[name] => Name 1
[author] => Author 1
[city] => City 1
)
[1] => Array
(
[name] => Name 2
[author] => Author 2
[city] => City 2
)
[2] => Array
(
[name] => Name 3
[author] => Author 3
[city] => City 3
)
)