从php中的数据库中提取数组

时间:2015-07-01 17:49:39

标签: php mysql arrays mysqli

我目前正在尝试从我的数据库(文章)和表格文章中提取一个表并将其放入一个数组中,但我不确定天气是否因为我不知道如何打印数组而感到沮丧。我正在关注此链接。

http://phpscriptarray.com/php-arrays-tutorials-tour/how-to-extract-mysql-database-data-into-php-array-variable.php

<?php

$servername = "localhost";
$username = "username";
$password = "password";

// create connection
$conn = new mysqli($servername, $username, $password);
// check connection
if ($conn->connect_error){
    die("connection failed: " . $conn->connect_error);
} 
// connect to DB
$db_selected = mysqli_select_db('article', $conn);
if (!$db_selected){
    die("can't use article : " .mysqli_error());
} 
// extract databases table to PHP array
$query = "SELECT * FROM `articles`";
$result = mysqli_query($query);
$number = mysql_numrows($result);
$article_array = array();
$x = 0
while($x < $number)
{
    $row = mysqli_fetch_array($result);
    $artic = $row['name'];
    $amount = $row['quantity'];
    $article_array[$artic] = $amount;
    $x++;
}
echo count($article_array);
//echo "hello";

<?

即使回声你好也不会工作,我不确定我是否应该在名称和数量:

$artic = $row['name'];
$amount = $row['quantity'];

1 个答案:

答案 0 :(得分:1)

您正在将面向对象与程序样式混合在一起。您的查询和循环应如下所示:

$query = "SELECT * FROM `articles`";    
$result = $conn->query($query);
$article_array = array();
while($row = $result->fetch_array(MYSQLI_ASSOC)){
    $artic = $row['name'];
    $amount = $row['quantity'];
    $article_array[$artic] = $amount;
}

http://php.net/manual/en/mysqli.query.php

此外,您的PHP结束标记有问题 - 应为?>或省略。