将单列数据库值放入数组,然后在另一个查询中调用它们

时间:2017-04-29 10:39:37

标签: php mysql arrays select

我在从'rownum'列中提取数据库信息并将其放入数组然后将该数组信息用于我的下一个查询时会出现问题,该查询随机选择数组的一行然后显示它。

<?php

  // Connect to database
  include 'DB.php';
  $con = mysqli_connect($host,$user,$pass);
  $dbs = mysqli_select_db($databaseName, $con);

  // Select Rownum to get numbers and only where there is no value in seen.
  $firstquery = "SELECT rownum FROM num_image WHERE seen=''";

  // If there are results store them here
  $result = mysqli_query($firstquery) or die ("no query");

  // Put the results taken from the table into array so it displays as: array(56, 44, 78, ...) etc...
  $result_array = array();
  while($row = mysqli_fetch_assoc($result))
  {
    $result_array[] = $row;
  }

  // Select the data I require
  $query = mysqli_query("SELECT number, association, image_file, skeleton, sound, colour, comments FROM num_image WHERE rownum='$row' LIMIT 1;");
  $test = mysqli_query("UPDATE num_image SET Seen='yes' WHERE rownum='$row';");

  // Fetch Results of Query, Ignore test.
  $arrayss = mysqli_fetch_row($query);    

  // Echo Results as a Json
  echo json_encode($arrayss);

?>

我不确定我做错了什么?是否必须回显数组,然后我的$ query行调用它?

1 个答案:

答案 0 :(得分:0)

更新了代码 - 解决了我的问题

感谢提示家伙,它帮助我绕过它并提出了一个有效的解决方案。

<?php

  // Connect to database
  include 'DB.php';
  $con = mysqli_connect($host,$user,$pass);
  $dbs = mysqli_select_db($databaseName, $con);

  // Select Rownum to get numbers and only where there is no value in seen.
  $firstquery = "SELECT rownum FROM num_image WHERE seen=''";

  // If there are results store them here
  $result = mysqli_query($firstquery) or die ("no query");

  // Put the results taken from the table into array so it displays as: array(56, 44, 78, ...) etc...
  $result_array = array();
  while($row = mysqli_fetch_assoc($result))
  {
    $result_array[] = $row;
  }
  for ($i = 0; $i < count($result_array); $i++) {
    $all_rownums[] = implode(',', $result_array[$i]);
  }

  //pick a random point in the array
  $random = mt_rand(0,count($all_rownums)-1);

  //store the random question
  $question = $all_rownums[$random];

  // Select the data I require
  $query = mysqli_query("SELECT number, association, image_file, skeleton, sound, colour, comments FROM num_image WHERE rownum='$question' LIMIT 1;");
  $test = mysqli_query("UPDATE num_image SET Seen='yes' WHERE rownum='$question';");

  // Fetch Results of Query, Ignore test.
  $arrayss = mysqli_fetch_row($query);    

  // Echo Results as a Json
  echo json_encode($arrayss);

?>

这部分帮助我解决了这个问题:

for ($i = 0; $i < count($result_array); $i++) {
        $all_rownums[] = implode(',', $result_array[$i]);
      }
  

欢乐舞蹈