简体   繁体   中英

get values from mysql column in php array

I've a database with several columns. One of the columns is 'name' and stores the name of the companies in the database. Another column ('id') assign a unique id number to each company. The table has a minimum of 1 and a maximum of 4 companies.

I'd like to show the name of the companies in different places in a html document and therefore need to refer to $company_name_1, $company_name_2 etc. However, these variables should always be in the html document, irrespective of whether the companies are in the database. If not in the database, the value shown should be empty.

How can I automatically define the names of the companies with an array and a loop? I want to expand the database at a later stage hence manually defining the four company names is not an option.

Thanks!

$result = mysql_query($con, "SELECT name FROM companydetails");
$storeArray = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] =  $row['name']; 
}

And then I would like to use:

echo $storeArray[0];

to show the first company and

echo $storeArray[1];

to show the second company. Etc.

Before echo first check if the element exists in array. This way there will be no error, something like this

 if(count($storeArray)>1)

 echo $storeArray[1];

 else echo "NA";


 if(count($storeArray)>2)

 echo $storeArray[2];
 else echo "NA";

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