【问题标题】:SQL Rand() gives resultset but cant fetch resultsSQL Rand() 给出结果集但无法获取结果
【发布时间】:2017-09-09 01:08:56
【问题描述】:

我正在研究一个 sql 查询,它给出表中的随机行我的目标是每次都获得随机排序的结果集,它与 android 中的 volley 一起使用,有时它会给出正确的结果,它工作正常,有时它不起作用它不会给出json结果,但仍然会有像这样的值“mysqli_result Object ([current_field] => 0 [field_count] => 8 [lengths] => [num_rows] => 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));
 ?>

【问题讨论】:

  • 我认为它没有将值添加到结果数组中,下面的工作正常 $r1 = mysqli_query($db,"Select * from qs ORDER BY RAND() LIMIT 10"); $projects = 数组(); while ($row=mysqli_fetch_row($r1)) { printf ("%s (%s)\n",$row[0],$row[1]); }
  • 得到实际问题是 echo json_encode(array("result"=>$result));
  • $result 数组已经有元素

标签: php mysql sql


【解决方案1】:

问题在于我的字符编码是 UTF-8,我将其更改为 UTF8 $db->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)); 
?>

【讨论】:

    猜你喜欢
    • 2019-10-31
    • 2013-06-13
    • 2013-01-18
    • 2015-01-25
    • 2019-08-10
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多