Populate PHP Array from While Loop

后端 未结 5 764
清歌不尽
清歌不尽 2020-12-12 19:41

If I am fetching data from a MySQL database and using a while loop to iterate through the data how would I add each one to array?

$result = mysql_query(\"SEL         


        
相关标签:
5条回答
  • 2020-12-12 20:07

    This has been one of the fastest ways for me to create (multi-dimensional) arrays. I'm not sure if you want all of your results smooshed into one array or not.

    // Read records
    $query = "SELECT * FROM `Departments`"; 
    $query = mysql_query($query);
    
    // Put them in array
    for($i = 0; $array[$i] = mysql_fetch_assoc($query); $i++) ;
    
    // Delete last empty one
    array_pop($array);
    

    You can use print_r($array) to see the results.

    0 讨论(0)
  • 2020-12-12 20:07

    If you have multiple columns in your Departments table and you want to save in different array.

    $result = mysql_query("SELECT * FROM `Departments`");
    $dept_id = array();
    $dept_name=array();
    while($row = mysql_fetch_assoc($result))
    {
    //fetches and store all results in id column on your departments table
    $dept_id= $row['id'];
    //fetches and store all results in name column on your departments table    
    $dept_name=$row['name'];
    }
    
    0 讨论(0)
  • 2020-12-12 20:16

    This will do the trick:

    $rows = array();
    $result = mysql_query("SELECT * FROM `Departments`");
    while($row = mysql_fetch_assoc($result))
    {
      $rows[] = $row;
    }
    
    0 讨论(0)
  • 2020-12-12 20:17

    my fav is the following;

    $result=odbc_exec($conn,$sql);
    if ($result) {
        while($found_results[] = odbc_fetch_array($result)) { } 
        array_pop($found_results); //pop off the empty line from while loading
    }
    

    you dont need to pop the last line, but it does leave a blank if you omit it. works the same for mysql obviously.

    0 讨论(0)
  • 2020-12-12 20:22

    Build an array up as you iterate with the while loop.

    $result = mysql_query("SELECT * FROM `Departments`");
    $results = array();
    while($row = mysql_fetch_assoc($result))
    {
       $results[] = $row;
    }
    

    Alternatively, if you used PDO, you could do this automatically.

    0 讨论(0)
提交回复
热议问题