I want to run 2 different INSERT queries on the dropdown select option
If user selects option 1 the Insert Query for Table 1 runs.
When the user selects option 2 the other Insert query for Table 2 runs.
<?php
if(isset($_POST['submit_form']) && isset($_POST['listings'])) {
switch ($listings) {
case 'GradeA':
$stmt = "INSERT INTO Packing_listA (Country, Total_bales) VALUES ('$Country' , '$Total_bales')";
break;
case 'GradeB':
$sql = "INSERT INTO Packing_listB (Country, Total_bales) VALUES ('$Country' , '$Total_bales')";
break;
}
if ($mysqli->query($stmt) || $mysqli->query($sql) === TRUE) {
$last_id = $mysqli->insert_id;
$_SESSION['ct_id'] = $last_id;
echo "<p>New record created successfully. Last inserted ID is: '". $last_id."'</p>";
echo "<script>setTimeout('delayer()', 1000)</script>";
}
} ?>
And the HTML is
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" class="form" role="form">
<select style="font-size:1.5em; height:45px;" class="form-control" name="listings" >
<option>Choose Color</option>
<option value="GradeA" <?php if($listings == "GradeA") print('selected="selected"'); ?>>GradeA</option>
<option value="GradeB" <?php if($listings == "GradeB") print('selected="selected"'); ?>>GradeB</option>
</select>
<div class="form-group">
<center>
<button style="height:45px; font-weight:bold;" name="submit_form" class="form-control btn btn-lg btn-info">
Next
</button>
</center>
</div>
</form>
But I am open to any other method Like Radio Buttons or If, Else condition or anything that works.
When the option 1 is selected only associated Query will run and vice versa.
First, I'll go for something like this :
if (isset($_POST['submit_form']) && isset($_POST['listings'])) {
$sql = "INSERT INTO "
."Packing_list".($_POST['listings'] == 'GradeA'? 'A' : 'B')
."(Country, Total_bales)"
."VALUES ('$Country' , '$Total_bales')";
if ($mysqli->query($sql)) {
$_SESSION['ct_id'] = $mysqli->insert_id;
echo "<p>New record created successfully. Last inserted ID is: '".$_SESSION['ct_id'].
"'</p>";
echo "<script>setTimeout('delayer()', 1000)</script>";
}
}
Second , I think you can make a better code (strange think in this one...)
Related
I'm quite new to this, so sorry if this is a very easy question. When i try to insert into mysql using a multiple option html form it only inserts the last option selected from the drop down list, but inserts that option multiple times.
HTML
<form action ="test_page.php" method="post">
<select name= fruit[] size="8" multiple>
<option value ="Apples" >Apples</option>
<option value ="Oranges" >Oranges</option>
<option value ="Bananas" >Bananas</option>
<option value ="Grapes" > Grapes </option>
<option value ="Strawberries"> Strawberries</option>
</select>
<br><br>
<input type="submit" name="submit" value="Submit" />
</form>`
And here's the PHP
<?php
foreach ($_POST["fruit"] as $favourite)
{
$sql = "INSERT INTO Fruit_table (Apples, Oranges, Bananas, Grapes) VALUES ('$favourite','$favourite','$favourite', '$favourite');";
}
if ($conn->multi_query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Add quotes around the name.
From this:
<select name=fruit[] size="8" multiple>
to this:
<select name="fruit[]" size="8" multiple>
I found your problem!
So, you are actually setting $sql multiple times with the foreach while only executing the last one.
So like this;
foreach ($_POST["fruit"] as $favourite)
{
$sql = "INSERT INTO Fruit_table (Apples, Oranges, Bananas, Grapes)
VALUES ('$favourite','$favourite','$favourite', '$favourite');";
}
This is the full working code!
<?php
foreach ($_POST["fruit"] as $favourite)
{
$sql = "INSERT INTO Fruit_table (Apples, Oranges, Bananas, Grapes)
VALUES ('$favourite','$favourite','$favourite', '$favourite');";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
So, I only changed until where the foreach() will be. This should work now!
i am trying to bulid an online attendace in php, i am fetching student list from student table, and want to put all chkboxs if checkd as present and if unchecked as absent,
i am unable to do that.
<div class="attendance">
<form accept="att.php" method="POST">
<?php
$sel_sql = "SELECT * FROM student";
$run_sql = mysqli_query($conn,$sel_sql);
while($rows = mysqli_fetch_assoc($run_sql)){
$id = $rows['id'];
echo '<input type="checkbox" name="status" value="'.$id.'" checked>'.ucfirst($rows['f_name']).'';
}
?>
<input type="submit" name="submit_attendance" value="Post Attendance">
<?php echo $msg; ?>
</form>
</div>
it shows prefect students list, but i dont know how to set insert query for all of these chkboxes
try this query to insert from another table
SELECT * INTO TABLE2 FROM student
use where condition on student table as where student.column value to select checked values
Applied same above things with checkbox input field
echo '<input type="checkbox" name="status" value="'.$id.'" 'if($row['present_field_of_database']) ? 'checked' : ''
'>'.ucfirst($rows['f_name']).'';
it's fine then updated code with your problems i hope it's work for you
<div class="attendance">
<form accept="att.php" method="POST">
<?php
$sel_sql = "SELECT * FROM student";
$run_sql = mysqli_query($conn,$sel_sql);
while($rows = mysqli_fetch_assoc($run_sql)){
$id = $rows['id'];
// if your $id value is right from $rows['id'] then
// change your student table name to the another table where available status of the student
$wh_sql = "SELECT * FROM student WHERE id=".$id;
$run_wh_sql = mysqli_query($conn, $wh_sql);
$Wh_rows = mysqli_fetch_assoc($run_wh_sql);
// add student present or absent value to the rows data
$rows['status'] = $Wh_rows['status'];
}
// set value as A or P respectively absent or present add jquery plugins for onclick event while client click on checkbox change value respectively
echo '<input type="checkbox" name="status" value="'.$rows['status'].'" 'if($rows['status'] == "A") ?'checked': '' '>'.ucfirst($rows['f_name']).' onclick= "$(this).val(this.checked ? P : A)"';
?>
<input type="submit" name="submit_attendance" value="Post Attendance">
<?php echo $msg; ?>
</form>
</div>
if (isset($_POST['send'])) {
$s_id = $_POST['status'];
$id = $_POST['student'];
if ($s_id) {
foreach ($s_id as $s) {
foreach ($id as $i) {
if (mysqli_query($conn, "INSERT INTO attendence(s_id,status) VALUES('".
mysqli_real_escape_string($conn, $s)."','".
mysqli_real_escape_string($conn, $i)."')")) {
$msg = "success";
}else{
$msg = "failed";
}
}
}
}
}
i have 3 students. when i press send it sends 9 entries. i am unable to understand how to insert all students data
This is attendance table
This is attandance table
i want to put entries like this if check box chekd it wil post p and if not it wil post a. i just need how to insert all sutdent at once quert
I have a form by which i use to send mails to users.
<form method="post" action="/functions/mails/mailstomysql.php">
<?php
$sql="SELECT UserId, FatherName, FirstName FROM profiles";
echo "<div class='FieldTitle' style='display:none;'>To</div>";
echo "
<div class='ui segment'>
<div class='ui fluid multiple search selection dropdown'>
<input type='hidden' multiple name='ReceiverId[]' required>
<i class='dropdown icon'></i>
<input class='search' tabindex='0'>
<div class='default text'>To</div>
<div class='menu' tabindex='-1'>
"; // list box select command
foreach ($conn->query($sql) as $row){//Array or records stored in $row
echo "
<option class='item' data-value='".$row['UserId']."' value='".$row['UserId']."'>$row[FirstName] s/o $row[FatherName]</option>";
}
echo "
</div>
</div>
</div>
?>
<input type="text" name="MailSubject">
<textarea type="text" name="MailContent"></textarea>
<input id="btnAddRecord" name="submit" type="submit" value="Send">
</form>
This is the SQL Statement that retrieve the data for above form:
$sql="SELECT UserId, FirstName FROM profiles";
And this is the mailtomysql.php file which insert the data into MySQL database.
$ReceiverId=$_POST['ReceiverId'];
$MailSubject=$_POST['MailSubject'];
$MailContent=$_POST['MailContent'];
$sql = "INSERT INTO mails (
`ReceiverId`, `MailSubject`, `MailContent`, `MailRead`, `MailDate`
)
VALUES (
'$ReceiverId', '$MailSubject', '$MailContent', '1', CURRENT_TIMESTAMP()
)";
if ($conn->query($sql) === TRUE) {
echo "Mail sent!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
The above code works awesome and perfect.
My Question
The above mailtomysql.php file insert the selected users from Multiple Selection Box and post the selected user ids to ReceiverId column which i do not want that, instead i want to have row for every selected user.
like:
Now
ReceverId
114, 265, 112
What i want
ReceverId
114
256
112
Why
If a user want to delete the mail then it will delete the mail and other users which are in that mail will not see the mail too because it is deleted by a user.
So once more my question is how to make mailtomysql.php file to make row for every selected users rather than having selected users ids in one row.
Edited:
I used the Semantic-Ui to select the options from the dropdown list, but it is not working.
On form side:
<form method="post" action="/functions/mails/mailstomysql.php">
<select multiple name='ReceiverId[]'>
<?php foreach ($conn->query($sql) as $row){
echo "<option class='item' data-value='".$row['UserId']."' value='".$row['UserId']."'>". $row['FirstName'] . "</option>";
} ?>
</select>
<input type="text" name="MailSubject">
<textarea type="text" name="MailContent"></textarea>
<input id="btnAddRecord" name="submit" type="submit" value="Send">
Make sure the value is set in the option and the name of the select is ReceiverId[].
On the receiving end, this will result into only one query...
$ReceiverIds = $_POST['ReceiverId'];
$values = "";
foreach($ReceiverIds as $receiver){
//don't forget some validation here...
//this is potentially unsafe too since the values are not properly escaped. Perform proper escaping here...
$values .= "('$receiver', '$MailSubject', '$MailContent', '1', CURRENT_TIMESTAMP()
),\n";
}
$values = rtrim($values, ",\n");
$sql = "INSERT INTO mails (
`ReceiverId`, `MailSubject`, `MailContent`, `MailRead`, `MailDate`
)
VALUES
$values";
$success = $conn->query($sql)
foreach($ReceiverId as $item){
$sql = "INSERT INTO mails (
`ReceiverId`, `MailSubject`, `MailContent`, `MailRead`, `MailDate`
)
VALUES (
'$item', '$MailSubject', '$MailContent', '1', CURRENT_TIMESTAMP()
)";
$success = $conn->query($sql)
}`
hoping someone can help me out. I am trying to insert into a mysql db a value that a user selects from a dynamic dropdown
i can get the dynamic drop down to list the values properly. the table that the dynamic dropdown data comes from has 2 colums (fruit_id, FruitType) ... there are a total of 4 fruits currently listed in this table (and in my dropdown)
what I would like to do is display this drop down in a form and once a user selects a fruit, i would like to insert the (fruit_id) value of the selected fruit into another mysql table
here is what i have so far, for some reason no matter what I select in the dropdown the (fruit_id) that gets inserted is 4 (ps, I only have 4 fruits in my table/dropdown)
this is the code that I have so far, any suggestions are appreciated. thanks :)
<?php
require_once('../../../connect.php');
// dropdown
$fruit_type = '';
$sql = "SELECT fruit_id, FruitType from mydb.mytbl";
$stmt = $dbh->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row) {
$fruit_type.= '<option value="' . $row["fruit_id"] . '">' . $row["FruitType"] . '</option>';
}
if(isset($_POST['submit'])){
$errors = array();
require('validate.php');
if(!count($errors)){
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);
$sql = "INSERT INTO fruittable
(fruit_id)
VALUES ('".$row['fruit_id']."');
";
$stmt = $dbh->prepare($sql);
$result = $stmt->execute();
}
}
if(isset($result)){
if($result){
}else{
echo '<b>Unable to Insert</b>';
print '<pre>'.print_r($stmt->errorInfo(), true);
}
}
?>
<h1>Log Fruit</h1>
<form method="post" action="add.php">
fruit type <br/>
<select name="fruit_select">
<option value=""</option>
<?php echo $fruit_type;?> <br/>
</select>
<p></p>
<br/>
<input type="submit" name="submit" value="Add" />
</form>
I fixed your PDO. you have to bind the parameters in PDO.
Here is how you would have the code display each option:
<?php
require_once('../../../connect.php');
if ($_POST['submit']) {
$fruitid=$_POST['fruit_select'];
$insertsql = "INSERT INTO fruittable (fruit_id) VALUES (:fruitid)";
$stmt = $dbh->prepare($insertsql);
$stmt->bindParam(':fruitid', $fruitid);
$stmt->execute();
}
$fruit_type = '';
$sql = "SELECT fruit_id, FruitType FROM table";
$stmt = $dbh->prepare($sql);
$stmt->execute();
?>
<h1>Log Fruit</h1>
<form method="post" action="add.php">
fruit type <br/>
<select name="fruit_select">
<option value=""</option>
<?php
while ($row = $stmt->fetch()) {
echo "<option value='".$row['fruit_id']."'>".$row['FruitType']."</option>";
}
?>
</select>
<br/>
<input type="submit" name="submit" value="Add" />
</form>
Using this code in a page called add.php should do what you are wanting. It will list the fruits and whenever you select a fruit and click Add/Submit button it'll add it to the database.
in my db i have 20+ columns. i added 19 columns throught input form and stored in db succesfully. i fetch few rows from db in my main page. in my main page 1 more column is there. that is status column, it is a combo box type. if i click status column it should show 4 values. i want to select one of the values and then when i click save button it must go to stored in db with that same ID. how to do that? i tried but its not updated in mysql db...
mainpage combo box coding:
echo "\t<td><form action=statusdb.php method=post>
<select name=update><option value=empty></option><option value=Confirm>Confirm</option><option value=Processing>Processing</option><option value=Pending>Pending</option><option value=Cancelled>Cancelled</option></select>
<input name=\"update[".$a_row['slno']."]\"; type=submit id=id value=Save></form>
</td>\n";
status db coding:
if (isset($_GET['id']))
{
$id = mysql_real_escape_string($_GET['id']);
$sql = mysql_query("UPDATE guestdetails SET status = '" . $_POST['update'] ."'");
if(!$sql)
{
die("Error" .mysql_error());
}
}
help me how to do that?
In your IF should be $_POST, not $_GET
Also, need to add WHERE clause, like this:
if (isset($_POST['id']))
{
$id = mysql_real_escape_string($_POST['id']);
$update= mysql_real_escape_string($_POST['update']);
$sql = mysql_query("UPDATE guestdetails SET status = '$update' WHERE id='$id'");
if(!$sql)
{
die("Error" .mysql_error());
}
}
Also, you used name update twice, once in <select> once in <input>, take that one from <input> out, make it hidden field with name id and value of your slno row:
echo "\t<td>
<form action=statusdb.php method=post>
<select name=update>
<option value=empty></option>
<option value=Confirm>Confirm</option>
<option value=Processing>Processing</option>
<option value=Pending>Pending</option>
<option value=Cancelled>Cancelled</option>
</select>
<input name='id' type='hidden' value='".$a_row['slno']."';>
<input type='submit'>Save</button>
</form>
</td>\n";
Try like below:
<form action="statusdb.php" method="post">
<?php
while($a_row = mysql_fetch_array($sql)) {
$sl_no = $a_row['slno'];
echo '<select name="update['.$sl_no.']"><option value=empty></option><option value=Confirm>Confirm</option><option value=Processing>Processing</option><option value=Pending>Pending</option><option value=Cancelled>Cancelled</option></select> ';
echo '<input type="hidden" name="sl_no[]" value="'.$sl_no.'" />';
}
?>
<input name="update_rows" type="submit" value="Save">
</form>
<?php
if(isset($_POST['update_rows'])) {
$nums = $_POST['sl_no'];
$update = $_POST['update'];
foreach($nums as $sl) {
$sl_no = $sl;
$val = $update[$sl_no];
$sql_update = mysql_query("UPDATE guestdetails SET status = '$val' WHERE sl_no='$sl_no'");
}
}
?>
you are not submitting any id to status db.