Creating an Array with PHP and MySQL
Question by user1114330
I have looked at several posts on stackoveflow for creating an array and haven’t found what I was looking for yet…so many different answers I would like to attempt and get one clear that is closest to what I am trying to accomplish.
Say I want to create an array using this query:
“select * from products”
How is this accomplished most efficiently?
Thank you.
PS – note that I am starting from scratch.
UPDATE
My config file:
`[root@CentOS testphp]# vi config.php
<?php
// Connection's Parameters
$db_host="localhost";
$db_name="tablename";
$username="username";
$password="password";
$db_con=mysql_connect($db_host,$username,$password);
$connection_string=mysql_select_db($db_name);
// Connection
mysql_connect($db_host,$username,$password);
mysql_select_db($db_name);
?>`
The php code I am trying to create the array with…I am getting a Syntax Error:
Parse error: syntax error, unexpected T_VARIABLE in /var/www/html/testphp/test.php on line 2
I get the same error:
`[root@CentOS testphp]# vi test.php
<?php include('config.php')
$query = "select * from upload_products";
$dataArray = array();
$result = mysqli_query($query, $link);
while($row = mysqli_fetch_assoc($query)) {
$dataArray[] = $row;
}
var_dump($dataArray); //Now you have your array.
?>`
Any ideas…It feels like I am missing something here. And, yes I have read the documentation…used their code line by line, reviewed the code and still get the same error as I do with all the code examples I have found on the web.
Answer by Starx
There is not definite way to convert a database result object into an associative array directory. You will have to create this array your result.
$query = "...";
$dataArray = array();
$result = mysqli_query($query, $link);
while($row = mysqli_fetch_assoc($query)) {
$dataArray[] = $row;
}
var_dump($dataArray); //Now you have your array.