How do I store all results from an SQL query in a multidimensional array?

后端 未结 5 1300
心在旅途
心在旅途 2021-02-08 17:46

hello every one i want to convert my array into other array type , plz help me out . I m using this

$row = mysql_fetch_array($result, MYSQL_ASSOC); 
相关标签:
5条回答
  • 2021-02-08 17:57
    $data = array(); // create a variable to hold the information
    while (($row = mysql_fetch_array($result, MYSQL_ASSOC)) !== false){
      $data[] = $row; // add the row in to the results (data) array
    }
    
    print_r($data); // print result
    

    Update Feb '17 Now that it's 2017, it's advised you use PDOs over mysql_*. A lot safer and can return this natively with fetchAll (as shown in `TrexXx's answer).

    0 讨论(0)
  • 2021-02-08 18:00

    You can't get a multi-dimensional array from the resultset of your SQL query in just one command. You need to repeat the function mysql_fetch_array once per SQL result row.

    Also you can use mysql_fetch_assoc to get the results as an associative array.

    To achieve your goal:

    $num = mysql_num_rows($result);
    for ($i = 0; $i < $num; $i++)
    {
        $myArray[] = mysql_fetch_assoc($result);
    }
    
    0 讨论(0)
  • 2021-02-08 18:01

    The only way to avoid doing a loop would to use PDO (PHP Data Objects) which is a better way to access database in PHP and you could do this :

    $pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
        
    $q = $pdo->query('select * from yourtable');
    $r = $q->fetchAll();
        
    var_dump($r);
    
    0 讨论(0)
  • 2021-02-08 18:15
    $row = array();
    $row[] = mysql_fetch_array($result, MYSQL_ASSOC);
    

    Normally you'd assign the results like this in a loop

    $rows = array();
    while ($result = mysql_fetch_array($result, MYSQL_ASSOC)) {       
        $rows[] = $result;
    }
    
    0 讨论(0)
  • 2021-02-08 18:18

    If you need to store all rows returned by the query in an array, try this:

    $result = array(); 
    
    while ( $row = mysql_fetch_array($result, MYSQL_ASSOC) ){
        $result[] = $row
    }
    
    0 讨论(0)
提交回复
热议问题