SQL Rand()提供了结果集,但无法获取结果

时间:2017-09-08 16:07:57

标签: php mysql sql

我正在研究一个sql查询,它提供了来自表的随机行,我的目的是在每次获得随机排序结果集,并在android中使用volley,有时它会给出正确的结果,并且它工作正常并且有时候它不起作用它不会给json结果,但仍然会有这样的值" mysqli_result对象([current_field] => 0 [field_count] => 8 [个长度] => [num_rows] =&gt ; 10 [type] => 0)"就是rand()的问题?没有rand它工作正常,但我需要从表中随机行我需要一个特定数量的行随机选择是否还有其他方法来做到这一点?

<?php
  include_once("config.php");
 $r = mysqli_query($db,"Select * from qs ORDER BY RAND()
LIMIT 10");
print_r($r);
  $result = array();
 while($row = mysqli_fetch_array($r)){ 
array_push($result,array(
 "id"=>$row[0],
 "question"=>$row[1],
  "option1"=>$row[2],
 "option2"=>$row[3],
  "option3"=>$row[4],
 "option4"=>$row[5],
"answer"=>$row[6]

 )
 );
}
 echo json_encode(array("result"=>$result));
 ?>

1 个答案:

答案 0 :(得分:1)

问题在于我的角色编码是UTF-8,我将其改为UTF8 $ DB-&GT; set_charset( “UTF8”);

<?php

include_once("config.php");
$db->set_charset("utf8");
 $r = mysqli_query($db,"Select * from qs ORDER BY RAND() LIMIT 10");
  $result = array();
 while($row = mysqli_fetch_array($r)){   
array_push($result,array(
 "id"=>$row[0],
 "question"=>$row[1],
  "option1"=>$row[2],
 "option2"=>$row[3],
  "option3"=>$row[4],
 "option4"=>$row[5],
"answer"=>$row[6]

 )
 );
}
  echo json_encode(array("result"=>$result)); 
?>