I have a problem when I want to insert multiple fields into one table.
Here's my form:
<h1>Add user</h1>
<form method="post" action="index.php">
<table>
<thead>
<th>Name</th>
<th>Age</th>
</thead>
<tr>
<td><input name="name[]" type="text" /></td>
<td><input name="age[]" type="text" /></td>
</tr>
<tr>
<td><input name="name[]" type="text" /></td>
<td><input name="age[]" type="text" /></td>
</tr>
<tr>
<td><input name="name[]" type="text" /></td>
<td><input name="age[]" type="text" /></td>
</tr>
</table>
<input type="submit" name="submit" value="Submit" />
</form>
And here's the submit code:
if (isset($_POST['submit'])) {
foreach ($_POST as $val) {
$name = $val['name'];
$age = $val['age'];
mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')");
}
}
The query inserts into the database, but not the values that I've entered.
Can someone please help me?
You are doing a foreach on $_POST rather than on the name/age arrays. You should be doing foreach on name or age array like this:
if (
!empty($_POST['name']) && !empty($_POST['age']) &&
is_array($_POST['name']) && is_array($_POST['age']) &&
count($_POST['name']) === count($_POST['age'])
) {
$name_array = $_POST['name'];
$age_array = $_POST['age'];
for ($i = 0; $i < count($name_array); $i++) {
$name = mysql_real_escape_string($name_array[$i]);
$age = mysql_real_escape_string($age_array[$i]);
mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')");
}
}
I would also note that you are currently susceptible to SQL injection so I added the step of escaping your strings for name/age.
I would also highly suggest simply making a single bulk insert into the DB instead of an insert of each record individually (I will leave that up to you to implement). This approach is almost always preferable from a performance standpoint.
Finally, you REALLY should not be using mysql_* functions as they are deprecated. Consider changing to mysqli or PDO.
if (isset($_POST['submit'])) {
$i = 0;
foreach ($_POST as $val) {
$name = $_POST['name'][$i];
$age = $_POST['age'][$i];
mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')");
$i++;
}
}
This will solve your problem !
foreach($_POST['firstname'] as $key=>$value) {
$firstname = $_POST['firstname'][$key];
$lastname = $_POST['tipo'][$key];
echo "Parte: $lastname";
echo "<br>";
echo "Tipo: $firstname";
echo "<br>";
}
A little bit easier code which works for me well.
if (isset($_POST['submit'])) {
$i = 0;
for ((array) $_POST as $val) {
$sql = "INSERT INTO users (name, age) VALUES (
'{$_POST["name"][$i]}','{$_POST["age"][$i]}'
);
mysql_query($sql);
echo (!mysql_affetced_rows()) ? "Query Wrong" : "Query Okay";
$i++;
}
}
below is the fxample how to inset multi row at one time
$query_string = "INSERT INTO YOURTBL_NAME(column_1,column_2)VALUES";
$data ="";
for($i=0;$i<count($YOUR FILE ARRAY);$i++)
{
$data .='("'.$paramater_1[$i].'","'.$paramater_2.'"),';
}
$qry = substr($query_string.$data, 0, -1);
$result = mysql_query($qry);
$education_institute_array = $_POST['education_institute'];
$education_qualification_array = $_POST['education_qualification'];
$education_start_date_array = $_POST['education_start_date'];
$education_end_date_array = $_POST['education_end_date'];
$education_note_array = $_POST['education_note'];
for ($i = 0; $i < count($education_institute_array); $i++) {
$education_institute = mysql_real_escape_string($education_institute_array[$i]);
$education_qualification = mysql_real_escape_string($education_qualification_array[$i]);
$education_start_date = mysql_real_escape_string($education_start_date_array[$i]);
$education_end_date = mysql_real_escape_string($education_end_date_array[$i]);
$education_note = mysql_real_escape_string($education_note_array[$i]);
$sql_education_insert = "INSERT INTO `education` (`user_id`, `education_institute`, `education_qualification`, `education_start_date`, `education_end_date`, `education_note`) VALUES ('$user_id', '$education_institute', '$education_qualification', '$education_start_date', '$education_end_date', '$education_note')";
$sql_result_education = mysql_query($sql_education_insert);
}
Related
I want to insert into my mysql database only those rows that have a checked checkbox at the end.
Since i have several tables and table data cells that have the same name, then my data is stored in arrays (product_name[] etc.):
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<?php
while($res = mysqli_fetch_array($result)) {
echo "<table id='tbl'>
<thead><th name='category[]'>".$res['category_name']."</th></thead>
<tbody>
<tr>
<td><input name='product_name[]' id='name' type='text'></td>
<td><input name='quantity[]' type='text' value='1'></td>
<td><input type='checkbox' name='check[]'></td>
</tr>
</tbody>";
}
?>
</table>
<div class="bottom-btn">
<button id="submit" type="submit">Lisa märgitud külmkappi</button>
</div>
</form>
Do i have to store the checkboxes in array as well (check[])?
My php code for the insert:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$product_name = $_POST['product_name'];
$quantity = $_POST['quantity'];
// $check = $_POST['check'];
foreach($product_name as $i=>$product_name)
{if(!empty($product_name)){
$sql = "INSERT INTO products (id, product_name, category, quantity, expiration_date, barcode) VALUES ('','$product_name', '', '$quantity[$i]', '', '')";
if($stmt = mysqli_prepare($conn, $sql)){
mysqli_stmt_bind_param($stmt, "ss",$param_product_name, $param_quantity);
$param_product_name = $product_name;
$param_quantity=$quantity;
if(mysqli_stmt_execute($stmt)){
header("location: myFridge.php");
} else{
echo "Something went wrong. Please try again later.";
}
mysqli_stmt_close($stmt);
}
}
}
mysqli_close($conn);
}
So far i have tried this: if(!empty($_POST['check'])) and this if(isset($_POST['check']) , but those did not work.
How to check if checkbox is checked before inserting data to database?
EDIT. WORKING.
I added this code to my page to make an array of checkbox on and off values:
function getAllCheckboxValues($check){
$found = array();
foreach ($check as $key => $val){
if($val == 'on'){
$found[] = $key;
}
}
foreach($found as $kev_f => $val_f){
unset($check[$val_f-1]);
}
$final_arr = array();
return $final_arr = array_values($check);
}
$checkbox_arr = getAllCheckboxValues($_POST['check']);
And also added a hidden input before every checkbox:
<input type='hidden' name='check[]' value='off'>
Then matched the checbox array with my products array and voila!
You could simply var_dump($_POST) to see whats in your post request. That always helps when facing issues like that.
Checkboxes come with the value on if they are checked and off if they are not, so it will never be empty and always be set, which is why your checks did not work. You should check if($_POST['check'] === 'on') instead.
Good day.
<input type="text" name="title">
<input type="text" name="name[]">
<input type="text" name="name[]">
<?php
if(isset($_POST['submit']){
$title = $_POST['title'];
$name = $_POST['name'];
$add = "INSERT INTO books (title, name) VALUES ('$title','$name')";
}
?>
How can this code work? It should be inserted with same title and different names at the same time. Thank you.
Sample Form
I want the record to be updated as follows:
---------------------------------
|--bookID--|--Title--|--Author--|
|----1-----|---one---|----me----|
|----2-----|---two---|---you----|
---------------------------------
$_POST['name'] is an array with key 0,1 ...
So in your example you ve got:
//This is just an example
foreach($_POST['name'] as $name) {
}
Hope this helps.
Atul Vekariya example is correct but you need to also execute the query in the loop. That's why this example did not work for you.
if(is_array($_POST['name']) && !empty($_POST['name'])) {
foreach($_POST['name'] as $name) {
$add = "INSERT INTO books (title, name) VALUES ('$title','$name')";
//execute query here. mysqli_query($add) or PDO::query
}
}
Please check below code
if(is_array($_POST['name']) && !empty($_POST['name'])) {
foreach($_POST['name'] as $name) {
$add = "INSERT INTO books (title, name) VALUES ('$title','$name')";
//execute query here. mysqli_query($add) or PDO::query
}
}
After searching different solutions. Here is the one that works. Thank you for all the help.
<?php
include_once 'config/connect.php';
if($_SERVER["REQUEST_METHOD"] == "POST"){
$title = $_POST['title'];
$name = $_POST['name'];
$length = count($name);
$addBook = "INSERT INTO books (title,name) VALUES ";
for($i=0; $i<$length; $i++){
$addBook .= "('$title','$name[$i]'),";
}
$addBook = rtrim($addBook, ',');
if($conn->query($addBook) === TRUE) {
echo "Success";
} else {
echo "Error: ".$addBook."<br>".$conn->error;
}
}
?>
<form action="addBook.php" method="POST">
Title: <input type="text" name="title">
<br/>
Authors: <input type="text" name="name[]"> <input type="text" name="name[]">
<br/>
<input type="submit" name="submit">
</form>
Good day! I am having a problem in storing values in my database. The flow of the program is the user will input in how many subject he will get. For example, he/she can put 6 subjects. So it will release 6 input types with values equal to text. My problem is I don't get 6 rows in my database as the user take 6 inputs.
HTML/PHP
<form method="POST">
<table>
<tr>
<td>SUBJECT CODE/SUBJECT DESCRIPTION/SEMESTER</td>
</tr>
<?php $counter=1 ;
while($counter <= $subj){?>
<tr>
<td>
<select name="sub">
<?php $select=mysql_query("SELECT * FROM subject
WHERE course_code = '$course' AND semester = '$sem'");
while($rows=m ysql_fetch_assoc($select)){
$code=$rows['subj_code'];
$desc=$rows['subj_desc'];
$units=$rows['units'];
$yr=$rows[ 'year_level'];
?>
<**option value="<?php echo $codes[$code]; ?>">
<?php echo $code. " - ".$desc; ?>
</option>**
<?php } ?>
</select>
</td>
<td>
</td>
</tr>
<?php $counter++; } } ?>
<tr>
<td>
<input type="submit" name="add" value="add subjects">
</td>
</tr>
</table>
</form>
PHP/SQL
<?php
if (isset($_POST['add'])) {
$data = array();
$subject = $_POST['sub'];
$sem = $_SESSION['sem'];
for ($i = 0; $i < count($subject); $i++) {
$subject = mysql_real_escape_string($subject[$i]);
$sem = mysql_real_escape_string($sem[$i]);
$yr = mysql_real_escape_string($yr[$i]);
$fac = mysql_real_escape_string($fac[$i]);
$col = mysql_real_escape_string($col[$i]);
$set = mysql_query("SET foreign_key_checks = 0");
if (!$set) {
die("Foreign key SET failed");
} else {
$insertmid = mysql_query("INSERT INTO grade_midterm
(midterm_grade, semester, year_level, subj_code, stud_id, fac_id, col_code)
VALUES ('NA','$sem','$yr','$subject', '$user','$fac','$col')");
if (!$insertmid) {
die("Failed to insert midterm" . mysql_error());
} else {
$insertfinal = mysql_query("INSERT INTO grade_final
(final_grade, semester, year_level, subj_code, stud_id, fac_id, col_code)
VALUES ('NA','$sem','$yr','$subject','$user','$fac','$col')");
if (!$insertfinal) {
die("Failed to indert final");
} else {
$set2 = mysql_query("SET foreign_key_checks = 1");
echo "<script>alert('Success Adding Subject');</script>";
}
}
}
}
}
?>
You have a select box with name sub in your loop
<select name="sub">
this means every next selectbox will overwrite the previous one
use
<select name="sub[]">
to create a array in your $_POST variable
I have a table named positions. This table has the list of the different positions that the admin has added in the listOfPositions.php like President, Vice-President, etc. After adding different positions, he can now add the different people under that position. And that's where my problem is. How will I have an auto increment input name for the names of the people depending on how many positions it has in the table positions ?
I tried using javascript, but it increments only in the html and not reflecting to the php when I try to save. My current code where the adding of the names of different persons depending on the position is the ff:
<script type="text/javascript" src="http://code.jquery.com/jquery-git.js"></script>
<form action="post_officers.php" method="post"><br>
<center><select name="year">
<?php
for($i=date('Y'); $i>1999; $i=$i-2) {
$selected = '';
$year2 = $i-2;
if ($year == $i) $selected = ' selected="selected"';
echo ('<option value="'.$year2. "-" . $i .'" '.$selected.'> '.$year2.'-'.$i.'</option>'."\n");
}
?>
</select></center>
<?php
include_once('dbcontroller.php');
$sql = "SELECT * FROM positions ORDER BY pos_id ASC";
$result = mysqli_query($conn, $sql);
/* assign an onchange event handler */
while ($row = mysqli_fetch_array($result)) {
$position = $row['position'];
?>
<br><br>
<table id="options-table">
<tr>
<td><input type="file" name="file" /></td>
<td><input type="hidden" name="position" /><?php echo $position; ?></td>
<td><input type="text" name="name" /></td>
</tr>
</table>
<?php
}
?>
<input type="submit" name="submit" value="SAVE"/>
</form>
<script>
$("input[name='file']").each(function(ind) {
$(this).attr(ind + 1);
});
$("input[name='position']").each(function(ind) {
$(this).attr(ind + 1);
});
$("input[name='name']").each(function(ind) {
$(this).attr(ind + 1);
});
</script>
And this is my php code:
<?php
include ('dbcontroller.php');
date_default_timezone_set('Asia/Manila');
$year = mysqli_real_escape_string($conn,$_POST['year']);
if(isset($_POST['submit'])) {
$result = mysqli_query($conn,"SELECT * FROM officers WHERE year = '$year'");
$num_rows = mysqli_num_rows($result);
if($num_rows>0){
echo "<script type='text/javascript'>alert('Year already exists.'); window.location.href='create_alumni_officers.php';</script>";
}
else {
for ($i = 1; $i <= 8; $i++) {
$name = mysqli_real_escape_string($conn,$_POST['name'.$i]);
$position = mysqli_real_escape_string($conn,$_POST['position'.$i]);
$file=(rand(1000,100000)."-".$_FILES['file'.$i]['name']);
$type=($_FILES['file'.$i]['type']);
$size=$_FILES['file'.$i]['size'];
$loc=($_FILES['file'.$i]['tmp_name']);
$new_size=$size/1024; // file size in KB
// make file name in lower case
$new_file_name = strtolower($file);
// make file name in lower case
$final_file=str_replace(' ','-',$new_file_name);
if(move_uploaded_file($loc, '../officers-avatars/'.$final_file)) {
echo "Page is loading, please wait...";
$result = mysqli_query($conn,"INSERT INTO officers VALUES (id, '$year', '$position', '$name', '$final_file', '$new_size', '$type')")
or die(mysqli_error($conn));
echo ("<script type='text/javascript'>window.location.href='alumni_officers.php';</script>");
}
}
}
}
?>
And this doesn't work at all. Any help? I hope you guys understood what I'm trying to ask.
This is the best way to do it:
<?php
include_once('dbcontroller.php');
$sql = "SELECT * FROM positions ORDER BY pos_id ASC";
$result = mysqli_query($conn, $sql);
/* assign an onchange event handler */
while ($row = mysqli_fetch_array($result)) {
$position = $row['position'];
?>
<table id="options-table">
<tr>
<td><input type="file" name="file[<?php echo $position; ?>]" /></td>
<td><input type="hidden" name="position[<?php echo $position; ?>]" value="<?php echo $position; ?>" /><?php echo $position; ?></td>
<td><input type="text" name="name[<?php echo $position; ?>]" /></td>
</tr>
</table>
<?php
}
?>
You don't need the javascript to change input attributes. Remove it.
In php use foreach loop like:
If you are still getting errors I will need to see the output of print_r($_POST);
<?php
$files = $_FILES['file'];
$positions = $_POST['position']; //use this for the foreach loop because it will always have a value
$names = $_POST['name'];
foreach($positions as $key=>$position){
$file = #$files[$key];
$name= #$names[$key];
//Do your magic for each user here
$name = mysqli_real_escape_string($conn,$name);
$position = mysqli_real_escape_string($conn,$position);
$filename = rand(1000,100000)."-".$file['name'];
$type = $file['type'];
$size = $file['size'];
$loc = $file['tmp_name'];
$new_size=$size/1024; // file size in KB
// make file name in lower case
$new_file_name = strtolower($filename);
// make file name in lower case
$final_file = str_replace(' ','-',$new_file_name);
if(move_uploaded_file($loc, '../officers-avatars/'.$final_file)) {
echo "Page is loading, please wait...";
$result = mysqli_query($conn,"INSERT INTO officers VALUES (id, '$year', '$position', '$name', '$final_file', '$new_size', '$type')")
or die(mysqli_error($conn));
echo ("<script type='text/javascript'>window.location.href='alumni_officers.php';</script>");
}
}
?>
As I indicated in the contents, removing context switches miss fide will greatly increase the readability of your code. I'll illustrate below a bit as well as answer the question.
To get what you're after, you could do this:
while ($row = mysqli_fetch_array($result)) {
$position = $row['position'];
?>
<br><br>
<table id="options-table">
<tr>
<td><input type="file" name="file" /></td>
<td><input type="hidden" name="position" /><?php echo $position; ?></td>
<td><input type="text" name="name<?php echo $position; ?>" /></td>
</tr>
</table>
<?php
}
However, to illustrate a small example of removing these contextual switches mid code, see below and pardon but this is air code, if you want a more specific example, just ask.
Let's say you often use the tag thoughout your site in forms. You could drop out of php each time and just write out the straight html. Or, you could create a class, or even a simple function for the html output thusly:
Function opt($int, $parms = '') {
Return '<Option '.$parms.'>'. $int.'</option>';
}
Now your code would look more like this:
While ($r =mysqli_fetch_array ($result)) {
Extract ($r); // learn this, no sense assigning them 1 by 1
$options .= opt($databaseobject, 'name="foo" value="'. $databaseobjectid.'"');
}
Echo $options;
I have a form that enables the user to insert multiple data into the database. I have been trying to insert them but to no avail.
Below is the form
<tr>
<td>
<select title = "Please choose" name="menutype[]">
<option value="-1" >--Select--</option>
<?php
$query = "SELECT * FROM MenuType";
$result = $mysqli->query($query);
if ($result==false) {
die( mysqli_error($mysqli));
}
while ($menutype = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $menutype['MenuTypeID'] ?>"><?php echo $menutype['MenuTypeName'] ?></option>
<?php
}
?>
</select>
</td>
<td><input type="text" name="name[]" /></td>
<td><input type="file" name="picture[]" /></td>
<td><textarea rows="4" cols="40" name="description[]"></textarea></td>
<td><input type="text" name="price[]" value=""/></td>
<td>
<select title="Please choose" name="status[]">
<option value="-1" />--Select--</option>
<option value="Available" />Available</option>
<option value="Limited" />Limited</option>
</select>
</td>
</tr>
Below is the php code
$name = $_POST['name'];
$description = $_POST['description'];
$price = $_POST['price'];
$status = $_POST['status'];
$menutypeid = $_POST['menutype'];
if(isset($_FILES['picture'])){
$name_array = $_FILES['picture']['name'];
$tmp_name_array = $_FILES['picture']['name'];
for($i = 0; $i < count($tmp_name_array); $i++){
if(move_uploaded_file($tmp_name_array[$i], "images/menu/".$name_array[$i])){
echo $name_array[$i]." upload is complete<br>";
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]. "<br>";
}
}
$imageup = $tmp_name_array; // save the whole url address of the uploaded file into variable
foreach ($name as $value){
$query = "INSERT INTO menu (MenuID, MenuName, MenuPicture, MenuDescription, MenuPrice, MenuStatus, MenuTypeID)
VALUES ('', '$name', '$imageup', '$description', '$price', '$status', '$menutypeid' )";
$mysqli->query($query) or die(mysqli_error($mysqli));
//header('Location:view_menu_for_manager.php');}}
?>
I also have trouble uploading multiple files/images. Help
edited query
foreach ($name as $value){
$query = "INSERT INTO menu (MenuName, MenuPicture, MenuDescription, MenuPrice, MenuStatus, MenuTypeID)
VALUES ('$name', '$imageup', '$description', '$price', '$status', '$menutypeid' )";
try like this
<?php
$name = $_POST['name'];
$description = $_POST['description'];
$price = $_POST['price'];
$status = $_POST['status'];
$menutypeid = $_POST['menutype'];
$data= array('name'=>$name,
'description'=>$description,
'price'=>$price,
'menutypeid'=>$status ,
'status'=>$menutypeid);
if(isset($_FILES['picture'])){
$name_array = $_FILES['picture']['name'];
$tmp_name_array = $_FILES['picture']['name'];
for($i = 0; $i < count($tmp_name_array); $i++){
if(move_uploaded_file($tmp_name_array[$i], "images/menu/".$name_array[$i])){
echo $name_array[$i]." upload is complete<br>";
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]. "<br>";
}
}
$imageup = $tmp_name_array; // save the whole url address of the uploaded file into variable
$i=0;
foreach($data as $value){
$name=$value[$i]['name'];
$description=$value[$i]['description'];
$price=$value[$i]['price'];
$status=$value[$i]['status'];
$menutypeid=$value[$i]['menutypeid'];
$query = "INSERT INTO menu (MenuName, MenuPicture, MenuDescription, MenuPrice, MenuStatus, MenuTypeID)
VALUES ('$name', '$imageup', '$description', '$price', '$status', '$menutypeid' )";
$mysqli->query($query) or die(mysqli_error($mysqli));
//header('Location:view_menu_for_manager.php');}
}
?>
Remove foreach because you are getting only one row from html form. I think there is no need of foreach. Echo each variable before inserting into database just to check that you are getting corrct value or not.
Please check this link.
Link