douzhaobo6488 2016-06-26 03:43
浏览 5
已采纳

从MySQL表中填充PHP中的数组

I am newbie to PHP and need to seek your help on how to populate the array which is $dataArray[] with the rows of MySQL so that I will be able to call the data Array in some other function or say I want to print the $dataArray as above. I would be thankful to you if you can provide me example code modifications in my below code

<?php
$dataArray=array();
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT reg_date,xyz,pqr FROM stuvw";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
    // output data of each row
    $test = mysqli_num_rows($result);
    echo $test;

    while($row = mysqli_fetch_assoc($result)) 
    {
        $populate = '"' . $row["reg_date"]. '"'."=>" . $row["xyz"]. ", " ;
        $dataArray[$populate] = $test;
    }
    echo $dataArray[$populate];        
}
mysqli_close($conn);
?>
  • 写回答

1条回答 默认 最新

  • dongxiee0744 2016-06-26 04:07
    关注

    You can use an Associative array. This stores the data in a key-value format.

    $dataArray[ $row['reg_date'] ] = $row['xyz'];

    What you are doing in you example is creating a string in the $populate variable and using it as a key in the $dataArray. The number of rows returned from the SQL query is then stored as the value for each item in the $dataArray. This number is in the $test variable.

    The key needs to be unique however so it makes sense to use the primary key from your MYSQL result as you key (if necessary).

    Have a read through W3Schools PHP course. http://www.w3schools.com/php/php_arrays.asp

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?