dpr77335 2015-07-01 17:49
浏览 149
已采纳

从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.

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";

<?

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'];
  • 写回答

1条回答 默认 最新

  • doujiao1538 2015-07-01 17:58
    关注

    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.

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

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作