Happy new year! Suppose user1 is located at zip code 12345. I want to find other users within X miles from that zip code.
First, I created the form:
<div id="wrapper">
<form action="L1.php" method="post">
<select name="radius">
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
</select>
Miles within Zip Code:
<input name="zip" type="text" value="13126" />
<input type="submit" value="refine" />
</form>
</div>
Now I am listing all the zip codes within X miles from 12345: (L1.php):
<?php
include('includes/db_AF.php'); //includes the db credentials
$connection = #new mysqli(HOSTNAME, MYSQLUSER, MYSQLPASS, MYSQLDB);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//look up the zip code in the searchbox
$whereClauses = array();
if (! empty($_POST['zip'])) $whereClauses[] ="zip_code='".mysqli_real_escape_string($connection,$_POST['zip'])."'";
$where = '';
if (count($whereClauses) > 0) { $where = ' WHERE '.implode(' AND ',$whereClauses); }
$sql = "SELECT * FROM zip " .$where." ";
$result=mysqli_query($connection,$sql) or die("Error: ".mysqli_error()."<br />Query: ".$sql);
//find out the corresponding lat and long
while ($row = mysqli_fetch_assoc($result)) {
echo '<br />';
echo '<br />';
$lat=$row['latitude'];
echo '<br />';
$lon=$row['longitude'];
echo '<br />';
}
$radius=$_POST['radius'];
//here I am generating an array of all the zip codes within x miles from 12345.
$query="SELECT * FROM zip WHERE (3958*3.1415926*sqrt((latitude-'$lat')*(latitude-'$lat') + cos(latitude/57.29578)*cos('$lat'/57.29578)*(longitude-'$lon')*(longitude-'$lon'))/180) <= '$radius'";
$result_obj = '';
$result_obj = $connection->query($query);
while($resultx = $result_obj->fetch_array(MYSQLI_ASSOC)) {
$items[] = $resultx;
}
foreach ($items as $item) {
echo $item['zip_code'];
echo '<br />';
}
$queryz="SELECT zip FROM customer"; // I am generating an array of all customer zip codes.
$resultz_obj = '';
$resultz_obj = $connection->query($queryz);
while($resultzz = $resultz_obj->fetch_array(MYSQLI_ASSOC)) {
$itemsz[] = $resultz;
}
$resultv = array_intersect($items, $itemsz);
print_r($resultv);
So now I have an array of zip codes. I want to list users that live at those zip codes. I know I have to intersect two arrays but get "Notice: Array to string conversion" error. Any thoughts?
If You have zip code in $items then i think you don't need $itemsz for all customer zipcodes.
First you need to format $items array to like this :
$zips = (12345,12346,12347,12348)
Then just run a query like this in customer:
Select * from customer where customer.zipcode IN $zips
demo: https://eval.in/84652
SAMPLE code:
$items =array( '0' => array( 'zip_code' => 13121, 'latitude' => 43.483379, 'longitude' => -76.315044, 'city' => 'New Haven', 'state' => 'NY', 'county' => 'Oswego' ), '1' => array( 'zip_code' => 13126, 'latitude' => 43.465388 ,'longitude' => -76.342172 ,'city' => 'Oswego' ,'state' => 'NY', 'county' => 'Oswego' ) );
$strzipCodes="";
foreach($items as $item){
$strzipCodes .= $item['zip_code']." ,";
}
$strzipCodes = rtrim($strzipCodes,',');
$sql ="SELECT * FROM customer where zip IN(".$strzipCodes.")";
echo $sql;
// then execute query we will get all users inside those zipcodes
I think you get the idea.
Related
A variable $irn input by the users, I need to pass the variable $irn one by one to a SQL and display the result in GR textbox after clicking the button
Generate Result, I want to split the $irn to an array so I can pass it one by one to the SQL query.
I tried mb_split and preg_split
<?php
include "big2gb.php";
ini_set('default_charset', 'utf-8');
$result = $_GET["listIRN"];
$irn = $_POST["irn"];
$serverName = "192.168.4.75";
$connectionInfo = array( "Database"=>"SAFHKG", "UID"=>"sa1", "PWD"=>"Azsxdc11", "CharacterSet" => "UTF-8");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if($conn){
//echo "connect DB success!!!<br />";
}
else
{
//echo "successfully failed!!!<br />";
die(print_r(sqlsrv_errors(),true));
}
//find irn
$sql="Select Top 1
[Expression] = CONCAT(OFFICIALNUMBER, ' for ', TITLE, ' in Class ', LOCALCLASSES)
From CASES
INNER JOIN OFFICIALNUMBERS On CASES.CASEID = OFFICIALNUMBERS.CASEID
Where NUMBERTYPE IN ('R', 'A') and CASES.IRN = ('".$array[$i]."')
Order By
CASE
When NumberType = 'R' then -2
When Numbertype = 'A' then -1
End";
echo"
<table>
<form action='test22.php' method='post'>
<tr>
<td>IRN:</td>
<td>
<input type='text' id='txtIRN' value='' style='text-transform:uppercase' >
<input type='button' value='Add IRN' onClick='addIRN()' name=''/>
<input type='submit' value='Genarate Result' id='GR' name=''/>
</td>
</tr>
<tr><tr><tr>
<td><td>
<textarea id='listIRN' name='irn' rows='40' cols='30' >
</textarea><textarea id='GR' rows='40' cols='80' ></textarea>
</td></td>
</tr></tr></tr>
</form>
</table><br/>";
echo"
<script type='text/javascript'>
function addIRN(irn) {
var IRNText = document.getElementById(\"txtIRN\").value;
var IRNList = document.getElementById(\"listIRN\").value;
var irn = IRNList + '\\n' + IRNText;
document.getElementById(\"listIRN\").value = irn.trim().toUpperCase();
}
</script>";
//////////////////your entered//////////////////*
echo "<p>You entered:<p>";
$array = mb_split('\\n', $irn);
foreach($array as $line)
{
$array = explode('\s', $irn);
echo "$line\n";
}
//////////////////////////////////////////////
print_r ($array);
//echo $array[3];
//echo $array[0];
for ($i = 0; $i <= 20; $i++)
{
$result = sqlsrv_query($conn, $sql );
while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOc) )
{
echo " ". $row["Expression"] ." <br />";
}
}
$conn->close();
?>
strong text
User input will be like TM1150CN31 TM2846CN35 TM2855CN35 TM2865CN35 TM2874CN43 TM3367CN05
You can use explode function like below
$var = 'TM1150CN31 TM2846CN35 TM2855CN35 TM2865CN35 TM2874CN43 TM3367CN05';
$array = explode(' ', $var);
Out put will be like
Array
(
[0] => TM1150CN31
[1] => TM2846CN35
[2] => TM2855CN35
[3] => TM2865CN35
[4] => TM2874CN43
[5] => TM3367CN05
)
So I've been trying to create an 'add' function for a contest table that is also linked to a joining table as the contest has many sport events associated to it (and a sport events will also be included in many contests). I have managed to create it as below, however it is limited to only adding one row into the joining table based on the chosen game in a dropdown.
So now, how do I go about creating the form if I don't know how many sport events there might be? How will the website create another dropdown if one dropdown is used so that more sport events can be selected? Similarly, how does the controller know that there are x amount of dropdowns selected, and hence x amount of rows to be added to the joining table?
I'm sorry if I am using incorrect or ambiguous terms to describe my problem. I have only started learning and creating websites recently.
Thank you.
UPDATE: I may have a solution per the updated codes below. However I am now stuck on the inserting into the database page. For some reason when I click submit, the next page loads but with no error and no rows inserted. Please help :)
View
<h1>Add New Contest</h1>
<?php
echo form_open('contests/add/');
?>
<?php
echo "<br />" "<br />"
echo "Contest Name";
$data = array( 'name' => 'contest_name',
'value' => set_value('contest_name'),
);
echo form_input($data);
echo "<br />" "<br />"
echo "Game";
?>
<div class="field_wrapper">
<div>
<select name="field_name[]">
<option value="" disabled selected>Select Game</option>
<?php
foreach($events_lists->result() as $row) {
$sports_events_id = $row->sports_events_id;
$sports_events_start_date = $row->sports_events_start_date;
$sports_events_start_time = $row->sports_events_start_time;
$home_team_shorthand = $row->home_team_shorthand;
$away_team_shorthand = $row->away_team_shorthand;
?>
<option value="<?php echo $sports_events_id; ?>"><?php echo $home_team_shorthand; ?> v <?php echo $away_team_shorthand; ?> - <?php echo $sports_events_start_date; ?> <?php echo $sports_events_start_time; ?></option>
<?php } ?>
</select>
<img src="add-icon.png"/>
</div>
</div>
<?php
echo "<br />" "<br />"
$data = array( 'value' => 'Add Contest',
'name' => 'submit',
'class' => 'submit-btn',
);
echo form_submit($data);
echo form_close();
?>
Controller
function add()
{
$league_id = $this->uri->segment(3);
$this->load->module('leagues');
$data['leagues_list'] = $this->leagues->get_where($league_id);
foreach ($data['leagues_list']->result() as $row) {
$league_insert_id = $row->id;
$this->load->module('sports_events');
$data['events_lists'] = $this->sports_events->get_events_list($league_insert_id);
}
if ($this->form_validation->run() == FALSE) {
$data['view_file'] = 'add_contest';
$this->load->module('template');
$this->template->cmslayout($data);
} else {
$data1 = array(
'contest_name' => $this->input->post('contest_name')
);
if(isset($_REQUEST['submit'])) {
$data2 = $_REQUEST['field_name'];
}
if ($this->_transactions_new_contest($data1, $data2)) {
return $query;
$this->session->set_flashdata('team_phase_created', 'The team phase has been set');
redirect('/contests/');
}
}
}
Model
function _transactions_new_contest($data1, $data2){
$this->db->trans_start();
$this->db->insert('contests', $data1);
$contest_id = $this->db->query('SELECT contests.id FROM contests ORDER BY contests.id DESC limit 1');
foreach ($contest_id->result() as $row) {
$contest_result_id = $row->id;
foreach($data2 as $value){
$this->db->query('INSERT INTO contests_has_sports_events (contests_id, sports_events_id) VALUES (' . $contest_result_id . ', ' . $value . ')');
} }
$this->db->trans_complete();
}
This question already has answers here:
Best way to INSERT many values in mysqli?
(4 answers)
Closed 2 years ago.
I need to insert entries to mysql table from the form below.
1-form contains many rows.
2-entry will not be always consecutive in the rows (meaning row 1 can be empty and next row not)
3-all rows containing entries should be saved in the db table.
i want to INSERT INTO oz2ts_custompc_details (part_id, quantity, price)
Here is my entry form (custompc_form2.php)
<!DOCTYPE html>
<html>
<body>
<form action="../subs/custompcorder2.php/" method="post" id="form">
<p><input id="name" name="part_id[]"/>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<p><input id="name" name="part_id[]"/>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<p><input id="name" name="part_id[]"/>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<p><input id="name" name="part_id[]"/>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<input id="submit" type="submit" value="Submit Order" name="submission"/>
</form>
</body>
</html>
here is What I came up with but still not working.
here is the summary of how it is working: ||Rows 1 to 4 has data > all 4 are saved || row 1 is empty and rows 2 to 3 contains data > only rows 2 and 3 are saved not row 4|| Row 2 only has data all other are empty > Data not saved || Rows 2 and 3 has data > Row 2 only is saved
<?php
include '../db/connect.php';
foreach (array('part_id', 'quantity', 'price') as $pos) {
foreach ($_POST[$pos] as $id => $row) {
$_POST[$pos][$id] = mysqli_real_escape_string($con, $row);
}
}
$ids = $_POST['part_id'];
$quantities = $_POST['quantity'];
$prices = $_POST['price'];
$items = array();
$size = count($ids);
for($i = 0 ; $i < $size ; $i++){
// Check for part id
if (empty($ids[$i]) || empty($quantities[$i]) || empty($prices[$i])) {
continue;
}
$items[]=array(
"part_id" => $ids[$i],
"quantity" => $quantities[$i],
"price" => $prices[$i]
);
}
if (!empty($items)) {
$values = array();
foreach($items as $item){
$values[] = "('{$item['part_id']}', '{$item['quantity']}', '{$item['price']}')";
}
$values = implode(", ", $values);
$sql = "INSERT INTO oz2ts_custompc_details (part_id, quantity, price) VALUES {$values} ;
" ;
$result = mysqli_query($con, $sql );
if ($result) {
echo 'Successful inserts: ' . mysqli_affected_rows($con);
} else {
echo 'query failed: ' . mysqli_error($con);
}
}
?>
The first is a simplified entry form. The reel entry form looks like this:
<!DOCTYPE html>
<html>
<head></head>
<body>
<form action="../subs/custompcorder2.php/" method="post" id="form">
<div id="orderwrap">
<div id="orderheather">
<select id="platform" name="platform">
<option selected="selected" disabled="disabled">Select the
platform</option>
<option value="Intel">Intel</option>
<option value="AMD">AMD</option>
</select>
</div>
<div id="orderbody">
<p><select id="part_id" name="part_id[]">
<option selected="selected" disabled="disabled">Choose part1 </option>
<?php query() ?>
< /select>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<p><select id="part_id" name="part_id[]">
<option selected="selected" disabled="disabled">Choose part2 </option>
<?php query2() ?>
< /select>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<p><select id="part_id" name="part_id[]">
<option selected="selected" disabled="disabled">Choose part3 </option>
<?php query3() ?>
< /select>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<p><select id="part_id" name="part_id[]">
<option selected="selected" disabled="disabled">Choose part4 </option>
<?php query4() ?>
< /select>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<input id="submit" type="submit" value="Submit Order"name="submission"/>
</div>
</div>
</form>
</body>
</html>
Here is the php page containing function query(),query1(),..
<?php
include '../db/connect.php';
function query(){
global $con;
$myData=mysqli_query($con,"SELECT * FROM oz2ts_mijoshop_product");
while($record=mysqli_fetch_array($myData)){
echo'<option value="'.$record['product_id'].'">'.$record['model'].'</option>';
}
}
function query2(){
global $con;
$myData=mysqli_query($con,"SELECT * FROM oz2ts_mijoshop_product");
while($record=mysqli_fetch_array($myData)){
echo'<option value="'.$record['product_id'].'">'.$record['model'].'</option>';
}
}
function query3(){
global $con;
$myData=mysqli_query($con,"SELECT * FROM oz2ts_mijoshop_product");
while($record=mysqli_fetch_array($myData)){
echo'<option value="'.$record['product_id'].'">'.$record['model'].'</option>';
}
}
function query4(){
global $con;
$myData=mysqli_query($con,"SELECT * FROM oz2ts_mijoshop_product");
while($record=mysqli_fetch_array($myData)){
echo'<option value="'.$record['product_id'].'">'.$record['model'].'</option>';
}
}
function close(){
mysqli_close($con);
}
?>
Sanitize input correctly using array_map
Check for input before adding to array
Only run SQL if anything to be added
Use the following code:
<?php
include '../db/connect.php';
foreach (array('part_id', 'quantity', 'price') as $pos) {
foreach ($_POST[$pos] as $id => $row) {
$_POST[$pos][$id] = mysqli_real_escape_string($con, $row);
}
}
$ids = $_POST['part_id'];
$quantities = $_POST['quantity'];
$prices = $_POST['price'];
$items = array();
$size = count($ids);
for($i = 0 ; $i < $size ; $i++){
// Check for part id
if (empty($ids[$i]) || empty($quantities[$i]) || empty($prices[$i])) {
continue;
}
$items[] = array(
"part_id" => $ids[$i],
"quantity" => $quantities[$i],
"price" => $prices[$i]
);
}
if (!empty($items)) {
$values = array();
foreach($items as $item){
$values[] = "('{$item['part_id']}', '{$item['quantity']}', '{$item['price']}')";
}
$values = implode(", ", $values);
$sql = "INSERT INTO oz2ts_custompc_details (part_id, quantity, price) VALUES {$values} ;
" ;
$result = mysqli_query($con, $sql );
if ($result) {
echo 'Successful inserts: ' . mysqli_affected_rows($con);
} else {
echo 'query failed: ' . mysqli_error($con);
}
}
Here is a rough code, modify indeces by your own needs.
$ids = $_POST['part_id'] ;
$quantities = $_POST['quantity'] ;
$prices = $_POST['price'];
$items = array();
$size = count($names);
for($i = 0 ; $i < $size ; $i++){
$items[$i] = array(
"part_id" => $ids[$i],
"quantity" => $quantities[$i],
"price" => $prices[$i]
);
}
$values = array();
foreach($items as $item){
$values[] = "('{$item['part_id']}', '{$item['quantity']}', '{$item['price']}')";
}
$values = implode(", ", $values);
$sql = "
INSERT INTO oz2ts_custompc_details (part_id, quantity, price) VALUES {$values} ;
" ;
Here's an example of basic issue handling while inserting data. Included in error checks are
Confirm that we received all 3 fields - part_id, quantity and price
If there were 3 rows of part_id, there must be 3 rows of quantity and price
Add safety by preparing INSERT statement
Bind variables to the prepared statements
Pick up only those rows in which all 3 fields (part_id, quantity and price) were entered, and that they were valid numbers
Code that receives POST
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
// debug information. Let's find what the page is receiving
echo '<pre>', print_r($_POST, true), '</pre>';
$postedData = $_POST;
// confirm that we received all 3 fields - part_id, quantity, price
$fieldsReceived = true;
if ( !confirmFields('part_id')
|| !confirmFields('quantity')
|| !confirmFields('price')
) {
echo 'part_id, quantity or price has not been received. Exiting.';
exit;
}
// confirm that each of them have identical item-count
if ( count($postedData['part_id']) !== count($postedData['quantity'])
|| count($postedData['part_id']) !== count($postedData['price'])
) {
echo count($postedData['price_id']) .
' fields received for price_id, but different number of fields
were received for quantity or price. Please ensure that part_id,
quantity and price have the same number of fields. Exiting.';
exit;
}
// establish connection using mysqli_connect
$connection = mysqli_connect('localhost', 'user', 'pass', 'selected_db');
// prepare an insert statement
$sql = 'insert into oz2ts_custompc_details
(part_id, quantity, price) values
(?, ?, ?)';
$statement = mysqli_prepare($connection, $sql);
// bind integer, integer, double to the parameters in insert statement
// corresponding to the question marks
$part = 0;
$qty = 0;
$prc = 0.0000;
mysqli_stmt_bind_param($statement, 'iid', $part, $qty, $prc);
// loop through received data and only insert those that have valid values
// in part_id, quantity and price
$partsReceived = count($postedData['part_id']);
for ($i = 0; $i < $partsReceived; $i++) {
// if drop down boxes are used and default value for part is
// Choose part, let's see if user left the selection to default
// and ignore that line
if (strpos($postedData['part_id'][$i], 'Choose part') !== false) {
continue;
}
// do we have numeric data in current line?
// although not done here, one can check if part_id is integer (is_int)
// quantity is_int and price is_float before proceeding further
if ( !is_numeric($postedData['part_id'][$i])
|| !is_numeric($postedData['quantity'][$i])
|| !is_numeric($postedData['price'][$i])
) {
echo '<p>Entry # ' . ($i + 1) . '
will be ignored because of missing
or invalid part_id, quantity, or price</p>';
continue;
}
// update bind parameters
$part = $postedData['part_id'][$i];
$qty = $postedData['quantity'][$i];
$prc = $postedData['price'][$i];
// execute statement and move on to the next one
try {
mysqli_stmt_execute($statement);
echo '<p>Inserted part_id ' . $postedData['part_id'][$i] . '</p>';
} catch (Exception $e) {
echo '<p>Could not enter data with part_id '
. $postedData['part_id'][$i] . '<br>'
. 'Error ' . $e->getMessage() . '</p>';
}
}
// --------------------------
// FUNCTIONS
// --------------------------
/**
* Confirm that we received part_id, quantity and price from POST
*
* #param string $fieldName Name of the field to verify
*
* #return bool True if fieldname is set as an array; False otherwise
*/
function confirmFields($fieldName)
{
global $postedData;
return
(!isset($postedData[$fieldName]))
&& !is_array($postedData[$fieldName]) ? false : true;
}
?>
I am trying to fillup two select boxes using the result of a mysql select query. I run the query once and use the output variable to loop and set options of select tag accordingly. The problem is, first select box gets populated as expected but the second one does not. It remains empty whatsoever. Heres my code
<?php
$con = mysql_connect('localhost','root','') or die('Could Not Connect'.mysql_error());
mysql_select_db('irctc', $con)or die('Could Not Select'.mysql_error());;
$result = mysql_query("select * from stationcodes", $con)or die('Could not select'.mysql_error());
?>
<html>
<head>
</head>
<body>
<table>
<tr>
<td>Source</td>
<td>:-</td>
<td><select id='src'>
<option value=''>Select Source Station</option>
<?php while($row = mysql_fetch_array($result))
{ ?>
<option value='<?php echo $row['StationCode']; ?>'><?php echo $row['StationName']; ?></option>
<?php } ?>
</select>
</td>
</tr>
<tr>
<td>Destination</td>
<td>:-</td>
<td><select id='dst'>
<option value=''>Select Destination Station</option>
<?php while($row = mysql_fetch_array($result))
{ ?>
<option value='<?php echo $row['StationCode']; ?>'><?php echo $row['StationName']; ?></option>
<?php } ?>
</select>
</td>
</tr>
</table>
</body>
</html>
You need to "rewind" data pointer back to the beginning before starting to iterate over the results again. Use mysql_data_seek(0); to do that, before building your "Destination":
<td><select id='dst'>
<option value=''>Select Destination Station</option>
<?php mysql_data_seek(0); // reset data pointer to 1st row
while($row = mysql_fetch_array($result))
{ ?>
<option value='<?php echo $row['StationCode']; ?>'><?php echo $row['StationName']; ?></option>
<?php } ?>
</select>
</td>
Also do not use mysql_. Switch to mysqli_ or PDO. and it would help you to separate code from view and use any type of template engine (like Smarty)
You need to either rerun the query before the second select box is rendered or to cache its results in an array first. Once you use mysql_fetch_* it has been read and you need to rewind the cursor or just start again/
In addition, stay away from mysql_* and use PDO or mysqli instead.
When you get to the second select box, all records are already fetched, so nothing will happen there.
What you should do is fetch al records into a array before you start the html code.
Then in the html code use a foreach statement to loop over the array.
Store your database result in an array so that you can use it multiple times:
$records = array();
while ($row = mysql_fetch_array($result)) $records[] = $row;
And to avoid writing the same algorithm multiple times, define a function that you call instead, for example:
function select($attrs, $options, $selected=null) {
$ret = '<select';
if (is_array($attrs)) {
foreach ($attrs as $name => $val) {
$ret .= ' '.htmlspecialchars($name).'="'.htmlspecialchars($value);
}
}
$ret .= '>';
foreach ($options as $option) {
$ret .= '<option';
if (isset($option['value'])) {
$ret .= ' value="'.htmlspecialchars($option['value']).'"';
if ($selected === $option['value']) {
$ret .= ' selected="selected"';
}
}
$ret .= '>';
if (isset($option['label'])) {
$ret .= htmlspecialchars($option['label']);
}
$ret .= '</option>';
}
$ret .= '</select>';
return $ret;
}
Then all you need to do is call this function with different parameters:
$options = array();
while ($row = mysql_fetch_array($result)) {
$options[] = array(
'value' => $row['StationCode'],
'label' => $row['StationName']
}
}
$srcOptions = array_merge(array(array('label'=>'Select Source Station')), $options);
echo select(array('id'=>'src'), $srcOptions);
$dstOptions = array_merge(array(array('label'=>'Select Destination Station')), $options);
echo select(array('id'=>'dst'), $dstOptions);
When displaying a form on a page for a user to edit information, and the form consists of a drop down box, how do you loop through the selections in the dropdown box to select their predefined mySQL entry?
For example
Users country: Australia
How would I go about searching through a list of countries ie: http://snipplr.com/view/4792/country-drop-down-list-for-web-forms/ to make:
<option value="AU">Australia</option>
become
<option value="AU" selected="selected">Australia</option>
You could do something like:
<?php
$countries = array('AU' => 'Australia', 'AF' => 'Afghanistan', ...);
$selected = 'AU';
foreach ($countries as $code => $label) {
echo '<option value="' . $code . '"';
if ($selected == $code) {
echo ' selected="selected"';
}
echo '>' . $label . '</option>';
}
?>
Not the prettiest but you get the idea. As Shakti suggests, it's also easier to maintain if the values are in the DB and not in a massive array in the middle of the code.
Could be something like this:
<?php
//your query here
$sql = "SELECT * FROM countries ORDER BY code ASC";
$result_set = $database->query($sql);
while($country = $database->fetch_array($result_set)) {
if ($country["code"] == "AU"){
echo "<option value=\"{$country['code']}\" selected=\"selected\">{$country['name']}</option>";
}
else {
echo "<option value=\"{$country['code']}\">{$country['name']}</option>";
}
?>