PHP-从查询创建数组

时间:2018-08-19 18:31:07

标签: php arrays

我需要用查询中的值填充此数组。

$articles = array(
    new article("1", "Example item #1", "4.00"),
    new article("1", "Another thing", "3.50"),
    new article("1", "Something else", "1.00"),
    new article("1", "A final item", "4.45"),
); 

$sql="SELECT quantity, desc, curr FROM sales";

我需要数组中的文章作为类。 我该怎么做?

2 个答案:

答案 0 :(得分:0)

我不知道你到底想要什么?

也许这会为您带来一些价值。

foreach($your_query_result AS $key => $value){
    //if your query result is in object
    $articles = array($value->quantity, $value->desc, $value->curr);

    //if your query result is in array
    $articles = array($value['quantity'], $value['desc'], $value['curr']);
} 

答案 1 :(得分:0)

尝试提供的这篇文章是类名;

<?php
$dbcon = mysqli_connect("your_host","your_user","your_password","your_db");

// Check connection errors
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

//Run your query using the connection 
$sql="SELECT quantity, desc, curr FROM sales";
$result = mysqli_query($dbcon,$sql);

//Check for any error from the query
if(!$result) echo mysqli_error($dbcon);

//Read the results
$rows = mysql_fetch_assoc($result);

//Now create the array you want using value from each row
$articles = array();
while ($rows){
$articles[] =  new article($rows['quantity'], $rows['desc'], $rows['curr']);
}
?>

请原谅我生疏的打字方式...仍在尝试习惯在移动应用上做到这一点