June 18, 2012

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.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!