I have a multiple select checkbox but i couldnt find a way on how to insert into database which each checkbox will create new rows in database.
this is how my dropdown looks like
<select id="plant" name="plant[]" class="form-control" multiple="multiple">
<?php
$query_plant = "SELECT * FROM plant WHERE plant_enable=1 ORDER BY plant_name";
$rs_plant = DB_Query($query_plant);
while ($row_plant = DB_FetchRow($rs_plant)) {
$plant.='<option name='.$row_plant["plant_shortname"].' value='.$row_plant["plant_id"].'>' .$row_plant["plant_name"].' ['.$row_plant["plant_id"].']</option>';
}
mysql_free_result($rs_plant);
echo $plant;
?>
</select>
You can get the selected checkbox value by using the name of checkbox on form submit like:
$plants = $_REQUEST['plant'];
$plants is an array here, so use foreach() to iterate over it and for each value make a insert query or combine all values in a single query and fire that query on database.
if(isset($_POST['company'])) {
$checkbox1 = $_POST['plant'];
$chk="";
$stf_sql = "SELECT * FROM test_plant WHERE staff_id = '".$STAFF_ID."'";
$stf_res = DB_Query($stf_sql);
if(DB_RowsReturned($stf_res) > 0) {
$del_sql = "DELETE FROM test_plant WHERE staff_id = '".$STAFF_ID."'";
$del_res = DB_Query($del_sql);
}
foreach($checkbox1 as $chk1)
{
$in_ch="insert into test_plant(staff_id, plant_name, submit_dt) values ('$STAFF_ID','$chk1', Now())";
$in_res = DB_Query($in_ch);
$abc = mysql_query("SELECT * FROM test_plant");
while($abc_row = mysql_fetch_assoc($abc)) {
foreach($abc_row as $key => $value) {
echo $key;
}
}
}
} else {
echo "OK";
}
Related
I had cart data in session like product_id, product_name, product_price..... so there is multiple data in session with array it's not fixed..sometime single data and sometime morethan one..... but when customer check out.... I need to check each product with customers entered pincode …..and products have multiple or single pincode in table....so we can get them by session product_id ..... then want to check if those pin match with client/user pincode then store in new session and those products which are not match yet....also move in another new session..... or just want to display product like allowed or not allowed product for this pin
is there any way to make it simple ? i think it's work with foreach inside condtions and all..but still confused.....sorry for bad english !
i had just wrote little code but confused what to next ?
if (!empty($_SESSION["shopping_cart"])){
foreach ($_SESSION["shopping_cart"] as $keys => $value){
$pro_session_id = $_SESSION["shopping_cart"][$keys]['product_id'];
$select_price_data = mysql_query("select * from product_pincode where product_ID = '$pro_session_id'");
}
}
if (!empty($_SESSION["shopping_cart"])) {
foreach ($_SESSION["shopping_cart"] as $keys => $value) {
$pro_session_id = $_SESSION["shopping_cart"][$keys]['product_id'];
// echo $pro_session_id;
// echo "<br>";
// $select_pin_data = mysql_query("select * from product_pincode where product_ID = '$pro_session_id'");
$select_pin_query = "SELECT * FROM product_pincode WHERE product_ID = '$pro_session_id'";
$selected = mysql_query($select_pin_query, $con) or die(mysql_error($con));
$pin_val = array();
while ($get_pin_data = mysql_fetch_assoc($selected)) {
$pin_val[] = $get_pin_data;
}
foreach ($pin_val as $get_pin_data) {
if ($get_pin_data['pincode_number'] == $_SESSION["order_placement_details"][0]['user_pincode']) {
echo "Complete " . $get_pin_data['pincode_number'];
echo "<br>";
} else {
echo "unallowed" . $get_pin_data['pincode_number'];
echo "<br>";
}
}
}
I have dozens of inputs in an HTML table one can use to enter numerical values. When submit button is pressed all inputs values are added to their corresponding column in the SQL table via post method. Value of <input name="A1> will be sent to column A1 in SQL table, <input name="A2> to column A2, and so on.
I'm currently using something like this (but with dozens of parameters) to insert data in my table :
$sql = "INSERT INTO all_stats_table (A1, A2, A3) VALUES ($A1, $A2, $A3)";
Problem with this approach is that every input needs to be filled or it will result in an SQL error. I initially used php to set all empty inputs value to 0 before sending everything to database, but I don't think this method is the most efficient way to go.
I would rather like to dynamically check which inputs are actually filled and only send their values to the table instead of converting every empty input value to 0 and having to send everything to the database.
I've already set all default values to 0 in SQL, but I don't know how to only send filled input values via SQL. I tried using a php foreach loop but I'm definitely having trouble finding the right SQL syntax.
Is what I'm trying to do possible ? If not, what would be the best practice to make this process more efficient ?
Thank you for your help
EDIT : attempt to adapt akash raigade's great solution to non-numbered SQL columns :
HTML :
<input name='name'>
<input name='address'>
<input name='age'>
PHP :
$Field_list = array ('name','address','age');
$field_string = '';
$input_string = '';
foreach ($_POST as $userInfo=>$userInfo_value) {
if (isset($userInfo)) {
if ($field_string == '') {
$field_string = $field_string.$userInfo; //problem here ?
$input_string = $userInfo_value; //problem here ?
}
else {
$field_string = $field_string.','.$userInfo; //problem here ?
$input_string = $input_string.','.$userInfo_value; //problem here ?
}
}
}
$sql = "INSERT INTO protocole_test (".$field_string.") VALUES (".$input_string.")";
echo $sql ; //check query formed
[Upgraded version]
Basic idea is that we keep NAME attribute of INPUT same as table column-name where it is gonna be stored.Then with help of input tag name and value which are filled we prepare SQL statement which have only required (FILLED) columns and values.
For given example consider following MYSQL table :
sr.no.|name|age|gender
CODE [Tested]:
<input name="name" >
<input name="age" >
<input name="gender" >
<input type='submit'>
<?php
$field_string ='';
$input_string='';
foreach ($_POST as $userInfo=>$userInfo_value){
if($userInfo_value !=''){
echo $userInfo."->".$userInfo_value;
if ($field_string == '') {
$field_string = $field_string.$userInfo;
$input_string = $userInfo_value;
}
else {
$field_string = $field_string.','.$userInfo;
$input_string = $input_string.','.$userInfo_value;
}
}
}
$sql = "INSERT INTO protocole_test (".$field_string.") VALUES (".$input_string.")";
echo $sql ; //check query formed
?>
[original answer]Have a look at following code :
<input name='a1' id='input_for_name'>
<input name='a2' id='input_for_class'>
<input name='a3' id='input_for_seat.no'>
.
.
<input name='an' id='input_for_n'>
Now
<?php
//you must be having field list to be inserted i.e
//INSERT INTO all_stats_table >>>(A1, A2, A3)<<< VALUES ($A1, $A2, $A3)
//A1,A2,A3 is field list here
//so save them into an array.
$Field_list = array ('A1','A2','A3',.......'An');
//Now get which input_field is inputted by :
$i=0;
$field_string = '';
$input_string = '';
for($i<n){
if(isset($_POST['a'.$i])){
if ($field_string == ''){
$field_string = $field_string.$Field_list[$i];
$input_string = $_POST['a'.$i];
}
else {
$field_string = $field_string.','.$Field_list[$i];
$input_string = $input_string.','.$_POST['a'$i];
}}}
$sql = "INSERT INTO (".$field_string.") VALUES (".$input_string.")";
//to check query formed
echo $sql ;
?>
Explanation :
We check which input field is FILLED , if it is field we add its FIELD into FIELD LIST and ITS VALUE in INPUT LIST finally we GENERATE SQL STATEMENT.
Just check if they are not defined or empty, and if so, define them.
if ( (!isset($_POST['A1'])) || (empty($_POST['A1']) ){
$A1 = '0';
} else {
$A1 = $_POST['A1'];
}
I'm not able to test this and it may need some debugging, but you could create a function, then call the function for each input. Something like...
function chkinput($input){
if ( (!isset($_POST[$input])) || (empty($_POST[$input]) ){
$$input = '0';
} else {
$$input = $_POST[$input];
}
return $$input;
}
// You could potentially loop through the post array
// but here I just call the function once per input
chkinput('A1');
chkinput('A2');
...
chkinput('A12');
You loop through the $_POST array and check if it has a value. If it does concatenate it to an variable. Like this:
$fields = "";
$values = "";
foreach($_POST as $key=>$value){
if($value != ''){
if($value != end($_POST)){
$fields .= $key . ", ";
$values .= "'" . $value . "', ";
}else{
$fields .= $key;
$values .= "'" . $value . "'" ;
}
}
}
$sql = INSERT INTO protocole_test ($fields) VALUES ($values) ;
Your SQL would look like :
INSERT INTO protocole_test (A1, A2, A3) VALUES ('A1', 'A2', 'A3')
I have retrieved data from the table and all the retrieved data to be stored in another table in each row. I have tried the below code but it is inserting only "
$roll_no = $_POST['roll_no'];
$name = $_POST['name'];
$class = $_POST['class'];
$section = $_POST['section'];
$m_am = $_POST['m_am'];
$a_pm = $_POST['a_pm'];
$date = $_POST['date'];
echo $a_pm .'<br>'.$m_am.'<br>'.$roll_no;
/*$sql_2 = mysql_query("INSERT INTO stud_class_attendance (`sca_rollno`, `sca_name`, `sca_class`, `sca_section`,`sca_am`, `sca_pm`,
?>"
Use mysqli instead of mysql to prevent hacking
and also validate the user input use htmlentities() or htmlspecialchars()
<?php
$roll_no = htmlspecialchars($_POST['roll_no']);
$name = htmlspecialchars($_POST['name']);
$class = htmlspecialchars($_POST['class']);
$section = htmlspecialchars($_POST['section']);
$m_am = htmlspecialchars($_POST['m_am']);
$a_pm = htmlspecialchars($_POST['a_pm']);
$date = htmlspecialchars($_POST['date']);
echo $a_pm .'<br>'.$m_am.'<br>'.$roll_no;
$sql_2 = mysqli_query("INSERT INTO stud_class_attendance (`sca_rollno`, `sca_name`, `sca_class`, `sca_section`,`sca_am`, `sca_pm`, `date`)
values ('$roll_no','$name','$class','$section','$m_am','$a_pm','$date');
$sql_2->execute();
?>
You need a loop for that..
Execute your first query. get all the records from the first query. iterate them and insert one by one in database
See the example
$select = mysql_query("SELECT
name,rollno,class,section,a_am,a_pm,`date`
FROM `student`");
// check if event 1 row exists in database
if(mysql_num_rows($select) > 0 ){
// while loop to iterate every row one by one
$count =0;
while ($row = mysql_fetch_assoc($select)) {
$insert = mysql_query("INSERT INTO `stud_class_attendance`
(`sca_rollno`, `sca_name`, `sca_class`, `sca_section`,`sca_am`, `sca_pm`)
VALUES
('".$row['rollno']."','".$row['name']."','".$row['class']."',
'".$row['section']."','".$row['a_am']."','".$row['a_pm']."')");
// check if the query was executed
if(mysql_insert_id() > 0){
$count++;
}
}
}
echo $count." rows inserted";
$sql='
INSERT INTO `stud_class_attendance` (
`sca_rollno`, `sca_name`,`sca_class`, `sca_section`,`sca_am`, `sca_pm`
)
SELECT rollno,name,class,section,a_am,a_pm FROM `student`
';
$sql2=mysqli_query($sql);
$sql2->execute();
I have a table teamtrack_activity that holds id and activity_name.
I have table teamtrack_entry that holds all team daily entries. This table has a field "activity_id" that I want to store the teamtrack_activity id. I have this part working.
However I am having 2 issues:
Displaying activity_name instead of id. When I try to do this then activity_name gets passed and this of course doesn't work.
When I go back to edit the entry it does not show the value in the database. It just shows the select box anew.
if ($key == "activity_id")
{
$query="SELECT id, activity_name FROM teamtrack_activity Order By id";
$res = sql_query($query);
if ($res === FALSE)
{
trigger_error(sql_error(), E_USER_WARNING);
fatal_error(FALSE, get_vocab("fatal_db_error"));
}
$select_options["entry.$key"] = array();
for ($i = 0; ($row = sql_row_keyed($res, $i)); $i++)
{
$select_options["entry.$key"][$row['id']] = $row['id'];
}
}
Change:
$select_options["entry.$key"][$row['id']] = $row['id'];
into
$select_options["entry.$key"][$row['id']] = $row['activity_name'];
to get a dropdown with the activity ame, which submit the activity ID for your script.
Based on your comment;
It might be the parsing of your $select_options.
In a foreach loop you would want to
foreach($select_options["entry.$key"]) as $key => $label)
{
echo "<option value=".$key.">".$label."</option>";
}
Trying to bring back a time id and time itself into listbox stored in mysql. run the sql in myadmin runs fine, try it in the code ... not so fine. bring back indefined index error.
thanks.
<?php
function get_times(&$a_class, &$db){
$str_sql =<<<EOT
SELECT timeId, DATE_FORMAT(tSel, '%H:%i')
FROM tb_time24
ORDER BY timeId
EOT;
if ($query_result = mysql_query($str_sql, $db)) {
while ($a_result = mysql_fetch_assoc($query_result)) {
$a = array();
$a['timeId'] = $a_result['timeId'];
$a['tSel'] = $a_result['tSel'];
array_push($a_class, $a);
}
}
else {
$i_result = mysql_errno($db);
}
if(isset($i_result)){
return $i_result;
}
}
?>
calling it here.
Start Time:<select name="startTime" id="StartTime">
<?php
$a_class = array();
get_times($a_class, $db_handle);
foreach ($a_class as $a_class) {
print "<option value='".$a_class['timeId']."'>{$a_class['tSel']}</option>\n";
}
?>
</select>
Give a name to the formatted column:
$str_sql =<<<EOT
SELECT timeId, DATE_FORMAT(tSel, '%H:%i') tSel
FROM tb_time24
ORDER BY timeId
EOT;
Otherwise the keys in the array returned by mysql_fetch_assoc would be timeId and DATE_FORMAT(tSel, '%H:%i').