从php中的数据库中提取数组
问题描述:
im currently trying to extract a table from my database (articles) and the table article and put it in an array but im not sure weather or not it wokred because i dont know how to print an array. i was following this link.
<?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";
<?
even the echo hello wont work and im not sure if i was supposed to put a name and quantity in:
$artic = $row['name'];
$amount = $row['quantity'];
我正在尝试从我的数据库(文章)和表格文章中提取表格并将其放入数组中但是 我不确定天气是不是因为我不知道如何打印阵列。 我正在关注此链接。 p>
&lt;?php
$ servername =“localhost”;
$ username =“username”;
$ password = “password”;
//创建连接
$ conn = new mysqli($ servername,$ username,$ password);
//检查连接
if($ conn-&gt; connect_error){
die (“连接失败:”。$ conn-&gt; connect_error);
}
//连接到DB
$ db_selected = mysqli_select_db('article',$ conn);
if(!$ db_selected){
die(“不能使用文章:”。mysqli_error());
}
//将数据库表提取到PHP数组
$ query =“SELECT * FROM` articles`”;
$ result = mysqli_query( $ query);
$ number = mysql_numrows($ result);
$ article_array = array();
$ x = 0
while($ x&lt; $ number)
{
$ row = mysqli_fetch_array( $ result);
$ a rtic = $ row ['name'];
$ amount = $ row ['quantity'];
$ article_array [$ artic] = $ amount;
$ x ++;
}
echo count($ article_array) ;
// echo“你好”;
&lt;?
code> pre>
即使回声你好也不会工作,我不确定我是否应该放一个 名称和数量在: p>
$ artic = $ row ['name'];
$ amount = $ row ['quantity'];
code>
div>
答
You are mixing object oriented with procedural style. Your query and loop should look like this:
$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
Also your PHP closing tag is faulty - should be ?>
or omitted.