douzhaobo6488 2016-06-26 11: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 12: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

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

报告相同问题?

悬赏问题

  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan