How to Populate an Array for MYSQL
What I need to do to populate an array,this is because i need to pull some records information from my MySQL database.
I have number of fields but instead of that want to fetch data for some field name only. And these are as follows:
Cust_id ¦ Cust_name ¦ Cust_loc
$name_ar = array(
'Cust_name1' => 'nickname1',
'Cust_name2' => 'nickname2',
'Cust_name3' => 'nickname3',
/* and on and on */
);
Please suggest how do i trigger or modify an Array to get the expected output.
Re: How to Populate an Array for MYSQL
// get the data from the DB to an array, initializing:
$myarray = array();
// iterate through DB records
while ($row = mysql_fetch_object ($result))
{
// now the array element with the "object_name" from the current database record gets the value "object_code" from the current database record
$myarray[$row['object_name']] = $row['object_code'];
}
// finally we can use the array:
$editor->set_inserts($myarray);
Re: How to Populate an Array for MYSQL
I found this code on the internet so i brought it for you to go ahead.hope this will solve your problem.
Code:
while($row = mysql_fetch_row($result)) {
$myarray[$row[0]] = $row[1];
}
while(list($key,$value) = each($myarray)) {
echo "$key : $value";
}
Re: How to Populate an Array for MYSQL
The mysql_fetch_array function returns an associative array, but it also returns FALSE if there are no more rows to return! Using a PHP While Loop we can use this information to our advantage.
If we place the statement "$row = mysql_fetch_array()" as our while loop's conditional statement we will accomplish two things:
- We will get a new row of MySQL information that we can print out each time the while loop checks its conditional statement.
- When there are no more rows the function will return FALSE causing the while loop to stop!
Now that we know what we need to do and how to go about doing it, the code pretty much writes itself, so let's move on to the next lesson. Just kidding! Here is the code that will print out all the rows of our MySQL Resource.
PHP and MySQL Code:
PHP Code:
<?php
// Make a MySQL Connection
$query = "SELECT * FROM example";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['name']. " - ". $row['age'];
echo "<br />";
}
?>
Output:
Quote:
Timmy Mellowman - 23
Sandy Smith - 21
Bobby Wallace - 15