Jump to content

multidimensional arrays & mysql


idig

Recommended Posts

hi
any help appreciated.

i have a mysql database table with 3 fields - province, province_id & country_id.the table contains 4 records. i want to get the data from the database and put into an array. i would then later want to read the data from the array.

this is what i used to create the array:

$provinces = array ("province" => array ("province_id" => $row['province_id'],"province" => $row['province'],"country_id" => $row['country_id']));

i then create a drop-down menu which is in the same while loop as that creating the array:

$value = $provinces["province"]["province"];
echo '<option value="',$value,'">',$value,'</option>\n';

the drop down menu displays fine - listing the 4 provinces but if i do a count of the array it only lists a count of 1.

what am i doing wrong and how can i make sure that all the records from the mysql database are included in the array even if i keep adding records to the mysql table. then how do i extract the data from the array - especially how do i do a search for a particular record within the array?

thanks in advance

clive
Link to comment
https://forums.phpfreaks.com/topic/6092-multidimensional-arrays-mysql/
Share on other sites

Welcome to the forums!

I think you're taking the long way to solve your problem. You don't need to use arrays so extensively. That is why you have a database and you should really learn the power of the database instead of using multi-dimensional array manipulation.

When you run your query, it should be setup like this:

[code]<?php
$query = "SELECT * FROM table";
$result = mysql_query($query) or die(mysql_error());

// the following tells you how many records were returned by the query
$numrows = mysql_num_rows($result);
echo "There are $numrows records in my database!<br/>";

// the following creates an array of a single record and consecutive calls
// using a while loop will fill the array with the next record
while($row = mysql_fetch_array($result))
{
    echo $row['column_name1'];
    echo $row['column_name2'];

    // or alternatively
    extract($row);
    echo $column_name1;
    echo $column_name2;
}
?>[/code]

You can also refine your query to look for specific items using WHERE clauses.

I hope this helps.
This will create a drop down menu using the database

[code]
<select name="fieldname">
<?
<?
$dropdown = "SELECT field1, filed2 FROM table ORDER BY field2 ASC";
$res = mysql_query($dropdown) or die (mysql_error());
while ($rows = mysql_fetch_array($res)) {
  print '<option value="'.$rows['field1'].'" selected>'.$rows['field2'].'</option>';
}
?>
</select>[/code]

ray

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.