从mysql数据库获取值并存储在php数组中

时间:2017-08-21 10:09:38

标签: php mysql

我正在使用php和Mysql开发一个项目,我需要从Mysql数据库中获取值并将它们存储到数组中。

代码:

$con=new mysqli("localhost","root","","databse");
$sql="select name from data";
$result= array();
$result=$con->query($sql);

如何在php数组中存储数据?

1 个答案:

答案 0 :(得分:1)

以下是如何操作的示例!

 //MySQLi information

    $db_host     = "localhost";
    $db_username = "username";
    $db_password = "password";

    //connect to mysqli database (Host/Username/Password)
    $connection = mysqli_connect($db_host, $db_username, $db_password) or die("Error " . mysqli_error());

    //select MySQLi dabatase table
    $db = mysqli_select_db($connection, "table") or die("Error " . mysqli_error());

   $sql = mysqli_query($connection, "SELECT * FROM data");

   while($row = mysqli_fetch_array($sql)) {
   $names[] = $row['name'];
}

修改: 使用

打印结果
print_r($names); 

foreach($names as $name) {
echo "$name";
}
祝你好运!