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 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了