简体   繁体   English

如何为mysql_query返回数组?

[英]how to return array for mysql_query?

  // make empty array
  $sqlArray=array();
  $jsonArray=array();


  // START NEED FAST WORKING ALTERNATİVES -----------------------------------------------------
  // first 20 vistors
  $query = "SELECT user_id FROM vistors LIMIT 20"; 
  $result = mysql_query ($query) or die ($query);

  // make vistors user query array
  while ($vstr_line = mysql_fetch_array($result)){
    array_push($sqlArray, $vstr_line['user_id']);
  }

  // implode vistors user array
  $sqlArray_impl = implode("', '", $sqlArray);
 // END NEED FAST WORKING ALTERNATİVES -----------------------------------------------------


  // Get vistors information
  $query = "SELECT id, username, picture FROM users WHERE id IN ('$sqlArray_impl')"; 
  $qry_result = mysql_query($query) or die($query);


  while ($usr_line = mysql_fetch_array($qry_result)){
    array_push($jsonArray, $usr_line['id'].' - '.$usr_line['username'].' - '.$usr_line['picture']);
  }


  print_r($sqlArray);

  echo '<br><br>';

  print_r($jsonArray);

see this my functions.. i need a replacement for fast working alternatives.. 看到这个我的功能..我需要一个快速工作的替代品。

function within the range specified above, to me, running faster than the alternative. 对我来说,功能在上述指定范围内运行比其他方法要快。 the query will return back array ? 查询将返回数组吗?

thx for all helpers ! 感谢所有帮手!

  1. Can you use a JOIN or SUB SELECT to reduce the query count from 2 to 1? 可以使用JOIN或SUB SELECT将查询数从2减少到1吗? Might not give much of a boost but worth a shot and a cleaner implementation. 可能没有太大的助益,但值得一试和更清洁的实现。

  2. Where is the bottleneck? 瓶颈在哪里? Most likely the db and not the php code. 最有可能的数据库,而不是PHP代码。

  3. Are the tables/columns properly indexed? 表/列是否正确索引? Run EXPLAIN on both queries. 对两个查询运行EXPLAIN。

Easiest would be to include first query as subquery eliminating one turn to the DB and a lot of code: 最简单的方法是将第一个查询作为子查询包括在内,从而避免了一次转向数据库和许多代码:

  // Get vistors information
  $query = "SELECT id, username, picture FROM users WHERE id IN (SELECT user_id FROM vistors LIMIT 20)"; 
  $qry_result = mysql_query($query) or die($query);

Unless there is more reason to have the first one seperate, but that is not visible in your code example. 除非有更多理由将第一个分开,否则在您的代码示例中不可见。

If you use PDO (recommended anyway...), you can return the result array all at once using fetchAll() . 如果使用PDO(无论如何建议...),则可以使用fetchAll()一次返回所有结果数组。

For your second query, you can use string concatenation in MySQL to directly return the result you want. 对于第二个查询,可以在MySQL中使用字符串连接直接返回所需的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM