简体   繁体   中英

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? 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.

  3. Are the tables/columns properly indexed? Run EXPLAIN on both queries.

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() .

For your second query, you can use string concatenation in MySQL to directly return the result you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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