echo array from mysql into <option> value - php

Please help me, I'm inserting the array (11,7,10) into a table.
Now i want to echo this data:
click here to show table
like this structure iwant to make it
<select>
<option value="11">11- HbA1C</option>
<option value="7">10- O"Solivan Test</option>
<option value="10">7- Randam Blood Glucose</option>
</select>
/////////////////////////////////////
table==>
id name date re_doctor sex age no_ana name_pr
11 aaaa 17/04/2017 Female 11,10,7 11- HbA1C,10- O"Solivan Test,7- Randam Blood Gluco.
////////////////////////////////////////////////
my code :-
<?
$qqq=$_GET['n'];
$sql = "SELECT * FROM `profile` where id ='$qqq'"; // select only the username field from the table "users_table"
$result = mysql_query($sql); // process the query
$username_array = array(); // start an array
while($row = mysql_fetch_array($result)){ // cycle through each record returned
$array1[] = $row[6]; // get the username field and add to the array above with surrounding quotes
// get the username field and add to the array above with surrounding quotes
$array3[] = $row[7]; // get the username field and add to the array above with surrounding quotes
}
?>
<select> <option>
<?
foreach($array1 as $it=>$ss){
foreach($array3 as $rr=>$vv){
if ($it==$rr) {
echo str_replace(',', '<option value="'.$ss.'">', $vv .'</option>');
}
}
}
?>
</select>

Lets say your data comes in as 11,7,10 from a multiple option or a checkbox as an array
Do a loop from the incoming form data from the array $no_ana at the user form
foreach($no_ana as $key => $value){
mysql_query("INSERT INTO table_name (id, name, date,
re_doctor, sex, age, no_ana, etc)
VALUES ($val1, $val2, $val3, $val4,
$val5, $val6, $value, $etc");
}
insert this code snippet to your script and test it out.
Here is how you do a multiple attribute
<select multiple name="name_pr[]">
<option value="11">11- HbA1C</option>
<option value="7">10- O"Solivan Test</option>
<option value="10">7 - Ramdam Blood Glocose</option>
</select>

Related

How to insert into multiple columns of a table from a dropdown field

I have the following HTML code:
<form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
Faculty ID:<input type="text" name="fid" id="fid" value="">
<span class="error">*</span><br><br>
Sunday: <select name="sun[]" id="sunday" multiple="multiple">
<option value="11">8:15-9:15</option>
<option value="12">9:15-10:15</option>
<option value="13">10:15-11:15</option>
<option value="14">11:15-12:15</option>
<option value="15">12:15-1:15</option>
<option value="16">1:15-2:15</option>
<option value="17">2:15-3:15</option>
<option value="18">3:15-4:15</option>
<option value="19">4:15-5:15</option>
</select>
<span class="error">*</span><br><br>
<button type="submit" value="Submit">Submit</button>
</form>
How can I insert multiple values selected from the drop down list (sunday) into different columns?
For example, if 8:15-9:15 is selected then the value must be entered into the s1 column into the table, if 9:15-10:15 then it has to be entered into the s2column of my MySQL table and so on.
Getting selected variable from dropdown list
$sunday = array('-select time--', '8:15-9:15', '9:15-10:15' and so on);
$selected_key = $_POST['sun'];
$selected_val = $sun[$_POST['sun']];
inserting data into into different table
$query = "INSERT INTO `" . $selected_val . "`
VALUES ('".$x"','".$y."','".$z."')";
you can store the drop-down options into keys of an array, which values is the column names. Then you can check which options were selected and add the corresponding columns to another array. Then you insert the data:
$columns = array(
"8:15-9:15" => s1,
"9:15-10:15" => s2,
"10:15-11:15" => s3,
"11:15-12:15" => s4,
"12:15-1:15" => s5,
"1:15-2:15" => s6,
"2:15-3:15" => s7,
"3:15-4:15" => s8,
"4:15-5:15" => s9
); //create a map between the options and column names
//retrieve the selected options to an array
$selectedOptions = $_POST['sun'];
$selectedColumns = array();
if(count($selectedOptions)) {
//add the column name for each selected option to an array
foreach ($selectedOptions as $option) {
$selectedColumns[] = $columns[$option];
}
// create a string with the columns names
$columnsToInsert = implode(", ", $selectedColumns);
// create a string with the selected options
$valuesToInsert = implode("', '", $selectedOptions);
// create the query string
$query = "INSERT INTO your_table('$columnsToInsert') VALUES ('" . $valuesToInsert ."')";
// then you execute the query
}

Display data from database using explode in php

I have table named "test". I would like to retrieve data from one column. Each row have multiple data separate with coma. How can i display all the data of column in drop-down?
ID | Qualification
1 | BE,Phd,ME
2 | MCA,MBA
3 | MBA
How can i display all the data of Qualification column in dropdown? Output should be like following
BE
Phd
ME
MCA
MBA
MBA
Loop throught your rows and create an array of each row by exploding the rule. Then merge the arrays together. Something like this:
//Example data TODO: replace with your table data
$rows[0]['Qualification'] = 'a,b,c';
$rows[1]['Qualification'] = 'a,b,c';
$qualificationArray = array();
foreach($rows as $rowData)
{
$rowDataArray = explode(',',$rowData['Qualification']);
$qualificationArray = array_merge($qualificationArray,$rowDataArray);
}
Then use the qualificationArray to create an dropdown
echo '<select name="qualification">';
foreach($qualificationArray as $qualification)
{
echo '<option value="'.$qualification.'">'.$qualification.'</option>';
}
echo '</select>';
So the output of this is a dropdown of every value:
<select name="qualification">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
First off, read all the data from the database:
$quals = array(); // This is the array where we are going to store all the data.
if ($result = $db->query("SELECT * FROM `test`"))
{
while ($row = $result->fetch_assoc())
{
$quals[$row['ID']] = $row['Qualification'];
}
}
The rows are now stored in $quals in the form $quals[ID] = CommaSeperatedQualifications.
Next, create the drop-down by
Iterating through each element in $quals.
Separating the comma-separated list, Qualification into an array of elments, say $list.
Further iterating through $list and printing the <option>s of the drop-down.
For example:
// now create a drop-down
echo '<select name="list_of_quals">';
foreach ($quals as $id => $value)
{
$list = explode(',', $value);
foreach ($list as $item)
{
echo '<option value="' . $id . '">' . $item . '</option>';
}
}
echo '</select>';

insert data to mysql database from multiple select list (html form)

I make a form, where there is ID of a shop:
<input type="text" name="shopId">
and there is a multiple choice select:
<select name="cars" multiple required>
after i get selected options, i have to pass them to a table in the database; table consists of 2 columns: shopId and car. The thing is it passes only one option and it is impossible to have a few rows added to the table like in one shop two or three models. I suppose i have to pass the data like an array or something. Can you help me, please.
$shopId = $_GET["shopId"];
$cars = $_GET["cars"];
this is a query:
$query = "INSERT INTO shops (shopId, car) VALUES ($shopId, $cars)";
I'd say given the constraints, the only option you have is to combine all the selected options into a single comma separated string (using PHP's built-in function called implode http://php.net/implode), then insert the shopID and the comma-separated-list of cars into a new row. I'd do it like this:
<?php
if ($_POST) {
$cars_string = implode(', ', $_POST['cars']);
$sql = '
INSERT INTO
`my_table` (
`shopID`,
`cars`
)
VALUES (
'. $_POST['shopID'] .',
"'. $cars_string .'"
)
';
mysql_query($sql) OR die(mysql_error());
}
?>
<form method="post" action="">
Shop ID: <input type="text" name="shopID"/> -
<select name="cars[]" multiple="multiple">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="honda">Honda</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
</select>
<input type="submit" name="Submit"/>
</form>
This is the best solution given the constraints you've provided. However, I do not see the logic in only being able to add a single row per form submit. That is not a good database design, especially in the long-term.
Please notice how the <select> element has the name of name="cars[]" and pay close attention to the open/close square brackets after the word cars[]. This will allow multiple options to be passed through the form, instead of only one. This is a critical difference and it should not be overlooked, as #bart2puck mentions in his solution. Also, the most browser-friendly way to allow users to select multiple options is to use the attribute multiple="multiple" in your <select> element.
you are getting only 1 insert because you are setting the value of $_GET['cars'] to the last selected item in your multiple. to acheive what you are looking for set the select name of cars to cars[]. When you goto process this you will now have an array in $_GET data.
then loop through that to do your inserts.
$shopId = $_GET['shopId'];
foreach ($_GET['cars'] as $value)
{
$ins = "INSERT INSERT INTO shops (shopId, car) VALUES ($shopId, $value)";
}
if you can only have 1 insert, which seems odd, then do something like:
$cars = "";
foreach ($_GET['cars'] as $value)
{
$cars .= $value . ",";
}
$cars = substr($cars,0,-1); //to remove the last comma
then
$ins = "INSERT INSERT INTO shops (shopId, car) VALUES ($shopId, $cars)";
you are going to end up with a field like 'honda,mazda,toyota' and this doesn't seem very efficient.

Insert multiple form selections into one single table column (set)

I have a simple form with the following:
<form action="#" method="post" name="form1" >
<input name="criteria1" size="64">
<input name="criteria2" size="64">
<select name="criteria3[]"multiple="multiple" >
<option value="5 ">5</option>
<option value="7">7</option>
<option value="10">10</option>
</select>
</form>
Now, if the user selects more then one option from criteria3, how do I insert that in a single database table field as well as insert the other two criteria in their own column?
I have tried many different ways and just get no where. My last attempt was as follows:
$values = array();
$type = explode(",", $_POST['criteria3']);
foreach ($type as $value) {
$values[] = sprintf('(%d)', $value);
}
$values = implode(',', $values);
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
$insertSQL = sprintf("INSERT INTO table (name, date, number)
VALUES (%s, %s, '$values')",
GetSQLValueString($_POST['criteria1'], "text"),
GetSQLValueString($_POST['criteria2'], "text"));
Not really sure what is going wrong – have tried several iterations and am getting no where.
Here are the most recent errors:
Warning: explode() expects parameter 2 to be string, array given in /filename.php on line 84
Warning: Invalid argument supplied for foreach() in /filename.php on line 86
Try the following(If you want separate records corresponding to separate values for criteria3 for a single entity):
$criteria1 = $_POST['criteria1'];
$criteria2 = $_POST['criteria2'];
$arr=$_POST['criteria3'];
foreach($arr as $criteria3)
{
$sql="insert into table_name (criteria1, criteria2, criteria3) values('".$criteria1."', '".$criteria2."', '".$criteria3."')";
mysql_query($sql);
}
And if you want a single record for a single entity with multiple criteria3-values use the following code:
$criteria1 = $_POST['criteria1'];
$criteria2 = $_POST['criteria2'];
if(isset($_POST['criteria3'])) //true when at least on of the options is selected.
{
$criteria3=implode(',', $_POST['criteria3']);
}
else //i.e. when no option is selected.
{
$criteria3='';
}
$sql="insert into table_name (criteria1, criteria2, criteria3) values('".$criteria1."', '".$criteria2."', '".$criteria3."')";
mysql_query($sql);
Since I am the only one that will be inserting data - I found a crude work around until I can get the code that Rajesh provided to work - I think this is the right path if I can get it to work.Thanks to all for your input. If I could, I would give you all the up vote!
remove the explode function from $_POST['criteria3'], Because it is already array it not need of explode so you try directly
$type = $_POST['criteria3'];
foreach($type as $k => $v) {
// here do the INSERT query with value $v
}
or if you prefer this link
1).Getting data from a multiple select dropdown with PHP to insert into MySQL
hope this helpful for you :)
<form action="" method="post" name="form1" >
<input name="criteria1" size="64">
<input name="criteria2" size="64">
<select name="criteria3[]" multiple >
<option value="5 ">5</option>
<option value="7">7</option>
<option value="10">10</option>
</select>
<?php
if(isset($_POST['submit']))
{
$criteria1 = $_POST['criteria1'];
$criteria2 = $_POST['criteria2'];
if(isset($_POST['criteria3']))
{
$query = "insert into table_name (criteria1, criteria2, criteria3) values";
foreach($_POST['criteria3'] as $list)
{
$query .= "('$criteria1','$criteria2','$list')";
}
echo $query;
}
}
?>
Explode only works with a string.
What you get from your form for criteria3 is an array, so you should act accordingly:
$criteria1 = $_POST['criteria1'];
$criteria2 = $_POST['criteria2'];
$criteria3 = implode(",", $_POST['criteria3']);
Here we generate a string based on the content of the table returned by your form.
We seperate each element by a comma.
Then we create the SQL query.
$sql = sprintf("INSERT INTO table (name, date, number) VALUES (%s, %s, %s);", $criteria1, $criteria2, $criteria3);
Hope this helps.

Select all option values php mysql

I'm trying to select all values from my MySQL database. Options a, b, and c work fine but I'm not sure of the syntax to select all three.
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
<option value="1,2,3">All</option>
I think you want to use the select to fetch a item or all items if I understand your question correctly and by seeing your 'all' option's value.
If so then change your select option's value for all to <option value="all">all items</option>.
Then change your PHP file (where you posting to with the form) to this:
// is the all option send?
if($_POST['your_select'] === 'all') {
//query to get all the items (SELECT * FROM table)
} else {
// query with the post value as the id (SELECT * FROM table WHERE id = $_POST['your_select'])
}
i think you want multiple="multiple" it will allow you to select multiple
<select name="modules[]" multiple="multiple">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
<option value="1,2,3">All</option>
</select>
now you will get array of selected option which you can get by either GET or POST
to select all on selecting last you can use jquery like
$('option').click(function(){
if($(this).val() =='1,2,3'){
$("option").attr("selected", "selected");
}
})
Try this
<form action="my_page.php" method="post">
<select name="my_select">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
<option value="1,2,3">All</option>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
# in my_page.php page
# put submitted value of the select tag in an array
# (submitted value in this case equals "1", "2", "3" or "1,2,3")
$values = explode(",", $_POST["my_select"]);
# get number of values in the array
$num_of_values = count($values);
# escape all values before using them in your sql statement
foreach ($values as $key => $val) {
$values["$key"] = mysql_real_escape_string($val);
}
# if we have more than 1 value in the array
if (count($values) > 1) {
$sql = "SELECT * FROM table_name WHERE "; # note the space after "WHERE" keyword
for ($i = 0; $i < $num_of_values; $i++) {
# this "if" statement is for removing the "OR" keyword from the sql statement
# when we reach the last value of the array
if ($i != $num_of_values - 1) {
$sql .= "column_name = '{$values[$i]}' OR "; # note the space after "OR"
} else { #if we reached the last value of the array then remove the "OR" keyword
$sql .= "column_name = '{$values[$i]}'";
}
}
# execute your query
$result = mysql_query($sql);
} else { # if we have only one value in the array
$result = mysql_query("SELECT * FROM table_name WHERE column_name = '{$values[0]}'");
}
?>

Categories