简体   繁体   中英

PHP - Create array from Query

I need to fill this array with values from a query.

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

I need the article in the array for a class. How do I do this?

I don't know what exactly you want?

Maybe this will bring some value to you.

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']);
} 

Try this provided article is the class name;

<?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']);
}
?>

Please pardon my rusty typing... Still trying to get use to doing this on mobile app

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM