I have this code:
<html>
<body>
<form id="myForm" method="post" action="add-data.php">
<input type="submit">
<input type="text" name="pollquestion">
<input type="text" name="polloption1">
<input type="text" name="polloption2">
</form>
Add option
<script>
var optionNumber = 3;
function addOption() {
var theForm = document.getElementById("myForm");
var newOption = document.createElement("input");
newOption.name = "polloption"+optionNumber+""; // poll[optionX]
newOption.type = "text";
theForm.appendChild(newOption);
optionNumber++;
}
</script>
</body>
</html>
If i add more inputs i will have something like this:
<input name="pollquestion" type="text">
<input name="polloption1" type="text">
<input name="polloption2" type="text">
<input name="polloption3" type="text">
<input name="polloption4" type="text">
<input name="polloption5" type="text">
<input name="polloption6" type="text">
The php code is something like this:
$qu = $_POST['pollquestion'];
$op1 = $_POST['polloption1'];
$op2 = $_POST['polloption2'];
$query = "INSERT into `".$db_table."` (question, option1, option2) VALUES ('" . $qu . "','" . $op1 . "','" . $op2 . "')";
How can i add this data to mysql for every added row? Thanks!
One way of many...
$query = "INSERT into `$db_table` SET `question` = '".mysql_real_escape_string($_POST['pollquestion'])."'";
foreach (range(1,6) as $idx) {
if (!empty($_POST['polloption'.$idx])) {
$query .= ", `option$idx` = '".mysql_real_escape_string($_POST['polloption'.$idx])."'";
}
}
of course the mysql_real_escape_string is important to avoid http://en.wikipedia.org/wiki/SQL_injection
First, you need to know how many options you're submitting so add another constant input to the form:
<input type="hidden" id="numOptions" name="numOptions"/>
In the addOption() function update its value (before incrementing optionNumber):
document.getElementById( "numOptions" ).value = optionNumber;
On the server side you need to create your query dynamically like so:
$options = array();
$values = array();
$numOptions = intval( $_POST[ "numOptions" ] );
for ( $i = 1; $i <= $numOptions; $i++ )
{
$options[] = "option$i";
$values [] = "'" . mysql_real_escape_string( $_POST[ "polloption$i" ] ) . "'";
}
$query = "INSERT INTO $db_table(" . implode( ',', $options ) . ") VALUES( '" .
implode( ',', $values );
Please mind the escaping of the received strings! very important to prevent SQL injections.
HTML
<input name="title" type="text">
<input name="descr" type="text">
<input name="question[1]" type="text">
<input name="option[1][1]" type="text">
<input name="option[1][2]" type="text">
<input name="option[1][3]" type="text">
<input name="right[1]" type="radio" value=1>
<input name="right[1]" type="radio" value=2>
<input name="right[1]" type="radio" value=3>
<input name="question[2]" type="text">
<input name="option[2][1]" type="text">
<input name="option[2][2]" type="text">
<input name="option[2][3]" type="text">
<input name="right[2]" type="radio" value=1>
<input name="right[2]" type="radio" value=2>
<input name="right[2]" type="radio" value=3>
PHP
$title = mysql_real_escape_string($_POST['title'])
$descr = mysql_real_escape_string($_POST['descr'])
$query = "INSERT into `polls` (title,descr) VALUES ('$title', '$descr')";
$id = $db->query($query);
foreach ($_POST['question'] as $num => $q) {
$q = mysql_real_escape_string($q)
$query = "INSERT into `poll questions` (poll,question) VALUES ($id,'$q')";
$db->query($query);
foreach ($_POST['option'][$num] as $i => $opt) {
$right = ($_POST['right'][$num]) == $i)?1:0;
$opt = mysql_real_escape_string($opt)
$num = intval($num);
$query = "INSERT into `poll options` (poll,num,option,right)
VALUES ($id,$num,'$opt',$right)";
}
}
You can iterate $_POST, matching keys with regular patterns, something like that:
foreach($_POST as $key => $value) {
preg_match('/(\w+)(\d+)/Uis', $key, $m);
if($m[1] == 'polloption') {
// concatenate new values to your query
}
}
Remembering relational databases, you have fixed number of attributes in your table. So you should add fixed number of options.
Related
I have a html form which has 2*12 input fields with name="links[]" and name="ids[]"...
I want to update column 'link' with those 12 links using those 12 ids
I know we need a loop for that.
But don't know how to make the sql query.
$ids=mysqli_real_escape_string($conn, $_POST['ids']);
foreach($ids as $id){....}
$links=mysqli_real_escape_string($conn, $_POST['links']);
foreach($links as $link){....}
$sql="update query.....";
EDIT:
It works with two variables $id and $season but when i add more than two variable like $episode etc. it doesn't work. it doesn't execute other variable only first two are executed and it sets the values of $season to 1 or sometimes 0 of all the entries in the table.
for($i=0 ; $i<count($record['id']); $i++){
$id=mysqli_real_escape_string($conn, $record['id'][$i]);
$season=mysqli_real_escape_string($conn, $record['season'][$i]);
$episode=mysqli_real_escape_string($conn, $record['episode'][$i]);
$rel_id=mysqli_real_escape_string($conn, $record['rel_id'][$i]);
$link=mysqli_real_escape_string($conn, $record['link'][$i]);
//sQl Query
$sql = "UPDATE series SET season='$season' and episode='$episode' and rel_id='$rel_id' and link='$link' WHERE id='$id'";
if ($conn->query($sql) === TRUE) {}
else { echo "Error: " . $sql . "<br>" . $conn->error; };
Try the below code.
<form name="rec" id="rec" method="post">
<input type="text" name="reord[id][]">
<input type="text" name="reord[season][]">
<input type="text" name="reord[episode][]">
<input type="text" name="reord[rel_id][]">
<input type="text" name="reord[link][]">
<br/>
<input type="text" name="reord[id][]">
<input type="text" name="reord[season][]">
<input type="text" name="reord[episode][]">
<input type="text" name="reord[rel_id][]">
<input type="text" name="reord[link][]">
<br/>
<input type="text" name="reord[id][]">
<input type="text" name="reord[season][]">
<input type="text" name="reord[episode][]">
<input type="text" name="reord[rel_id][]">
<input type="text" name="reord[link][]">
</br>
<input type="submit" name="submit" value="submit">
</form>
<?php
if(isset($_POST['submit'])){
$record = $_POST['reord'];
$id = $season = $episode = $rel_id = $link = '';
for($i=0 ; $i<count($record['id']); $i++){
$id= mysqli_real_escape_string($conn, $record['id'][$i]);
$season=mysqli_real_escape_string($conn, $record['season'][$i]);
$episode=mysqli_real_escape_string($conn, $record['episode'][$i]);
$rel_id=mysqli_real_escape_string($conn, $record['rel_id'][$i]);
$link= mysqli_real_escape_string($conn, $record['link'][$i]);
echo $sql = "UPDATE series SET season='$season' and episode='$episode' and rel_id='$rel_id' and link='$link' WHERE id=$id";
$conn->query($sql);
}
}
?>
$ids=mysqli_real_escape_string($conn, $_POST['ids']);
foreach($ids as $key => $id){
$sql="update tablename set fieldname=value where link=$_POST[links][$key] and id=$id";
}
This might work. If not give me more details.
UPDATE `tablename` SET `fieldname` = CASE
WHEN id = 1 AND xyz = 3 THEN `value 1`
WHEN id = 2 AND xyz = 3 THEN `value 2`
WHEN id = 3 AND xyz = 3 THEN `value 3`
END
In the scenario described I would use SET-WHEN-THEN query
I am trying to insert 4 forms that are the same. but with different values to mysql using PHP.
When I submit my data, the database only takes the values from the last form and inserts it 4 times. I am trying to get the values from all 4 on submit.
<div class="req3">
<h1>Requirement 4</h1>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<br>
Enter info for 4 teams and it will inserted into the database<br><br>
<div class="sqlForm">
<p class="formHead">Team 1</p>
<label>Team Name:</label> <input type="text" name="teamname"><br>
<label>City:</label> <input type="text" name="city"><br>
<label>Best Player:</label> <input type="text" name="bestplayer"><br>
<label>Year Formed:</label> <input type="text" name="yearformed"><br>
<label>Website:</label> <input type="text" name="website"><br>
</div>
<div class="sqlForm">
<p class="formHead">Team 2</p>
<label>Team Name:</label> <input type="text" name="teamname"><br>
<label>City:</label> <input type="text" name="city"><br>
<label>Best Player:</label> <input type="text" name="bestplayer"><br>
<label>Year Formed:</label> <input type="text" name="yearformed"><br>
<label>Website:</label> <input type="text" name="website"><br>
</div>
<div class="sqlForm">
<p class="formHead">Team 3</p>
<label>Team Name:</label> <input type="text" name="teamname"><br>
<label>City:</label> <input type="text" name="city"><br>
<label>Best Player:</label> <input type="text" name="bestplayer"><br>
<label>Year Formed:</label> <input type="text" name="yearformed"><br>
<label>Website:</label> <input type="text" name="website"><br>
</div>
<div class="sqlForm">
<p class="formHead">Team 4</p>
<label>Team Name:</label> <input type="text" name="teamname"><br>
<label>City:</label> <input type="text" name="city"><br>
<label>Best Player:</label> <input type="text" name="bestplayer"><br>
<label>Year Formed:</label> <input type="text" name="yearformed"><br>
<label>Website:</label> <input type="text" name="website"><br><br></div>
<input class="styled-button" type="submit" name="insert" value="Submit">
</form>
<?php
if (isset($_POST['insert'])) {
insertTable();
} else {
$conn->close();
}
function insertTable() {
$servername = "localhost:3306";
$username = "XXXXX";
$password = "XXXXX";
$dbname = "XXXXX";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
echo ("Connection failed: " . $conn->connect_error);
} else {
$varTname = $_POST['teamname'];
$varCity = $_POST['city'];
$varBplayer = $_POST['bestplayer'];
$varYearformed = $_POST['yearformed'];
$varWebsite = $_POST['website'];
$sql = "INSERT INTO Teams (teamname, city, bestplayer, yearformed, website)
VALUES ('$varTname', '$varCity', '$varBplayer', '$varYearformed', '$varWebsite'),
('$varTname', '$varCity', '$varBplayer', '$varYearformed', '$varWebsite'),
('$varTname', '$varCity', '$varBplayer', '$varYearformed', '$varWebsite'),
('$varTname', '$varCity', '$varBplayer', '$varYearformed', '$varWebsite')";
if ($conn->multi_query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysql_query($sql);
function PrepSQL($value)
{
// Stripslashes
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
}
}
?>
chnage the names of your controls so they Post as Arrays
<input type="text" name="teamname[G1]">
<input type="text" name="teamname[G2]">
this why when you use $varTname = $_POST['teamname']; $varTname is an array and each of the 4 values of teamname are set as $varTname['G#'] where # matches the number you set for that group of input fields.
then use a for loop to get the data and execute your query, something like bellow. while you at it you can also fix up your SQL Injection vulnerability. you may also want to so some more sanitation to the data just to be sure
$varTname = $_POST['teamname'];
$varCity = $_POST['city'];
$varBplayer = $_POST['bestplayer'];
$varYearformed = $_POST['yearformed'];
$varWebsite = $_POST['website'];
$stmt = $mysqli->prepare('INSERT INTO Teams (teamname, city, bestplayer, yearformed, website) VALUES (?,?,?,?,?,?)');
$varTname1Bind = "";
$varTnameBind = "";
$varCityBind = "";
$varBplayerBind = "";
$varWebsiteBind = "";
// assuming they are all strings, adjust where needed
$stmt->bind_param('sssssss',
$varTname1Bind,
$varTnameBind,
$varCityBind,
$varBplayerBind,
$varYearformedBind,
$varWebsiteBind);
for($i = 1; i < 5; $i++)
{
$varTname1Bind = $varTname['G'.$i];
$varTnameBind = $varTname['G'.$i];
$varCityBind = $varCity['G'.$i];
$varBplayerBind = $varBplayer['G'.$i];
$varYearformedBind = $varYearformed['G'.$i];
$varWebsiteBind = $varWebsite['G'.$i];
$stmt->execute();
}
will save you on how much code you need to do
You can convert your input names into arrays by adding [] then in your php loop through the array of the $_POST[] and built up your $sql by concatenating the values until you finish looping through all values and INSERT it as multiple values.
HTML:
<label>Team Name:</label> <input type="text" name="teamname[]"><br>
<label>City:</label> <input type="text" name="city[]"><br>
<label>Best Player:</label> <input type="text" name="bestplayer[]"><br>
<label>Year Formed:</label> <input type="text" name="yearformed[]"><br>
<label>Website:</label> <input type="text" name="website[]"><br>
PHP:
<?php
$sql = "INSERT INTO Teams (teamname, city, bestplayer, yearformed, website) VALUES ";
for($i = 0 ; $i < count($_POST['teamname']) ; $i++){
$varTname = $_POST['teamname'][$i];
$varCity = $_POST['city'][$i];
$varBplayer = $_POST['bestplayer'][$i];
$varYearformed = $_POST['yearformed'][$i];
$varWebsite = $_POST['website'][$i];
$sql .= "(" .$varTname. " , " .$varCity. " , " .$varBplayer. " , " .$varYearformed. " , " .$varWebsite. "),";
}
$sql = rtrim($sql, ','); // omit the last comma
// Then Excute your query
?>
This way you don't need to give them unique names name="test1", name="test2" and so, to see it in action check this PHP Fiddle in the bottom of the result page, I've already set the values of the input fields, just hit submit and go to the bottom of the result page to see the composed INSERT statement.
NOTE that the above SQL is just a demo on how to build it up, DO NOT use it like this without validation and sanitizing.. ALSO STOP querying this way and instead use Prepared Statements with PDO or MySQLi to avoid SQL Injection.
So for MySQLi prepared statements, procedural style - I work with PDO - as you see in this PHP Fiddle 2, the code is:
<?php
// you validation goes here
if (isset($_POST['insert'])) {
insertTable();
} else {
$conn->close();
}
function insertTable() {
// enter your credentials below and uncomment it to connect
//$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');
$sql = "INSERT INTO Teams (teamname, city, bestplayer, yearformed, website) VALUES";
$s = '';
$bind = '';
for($i = 0 ; $i < count($_POST['teamname']) ; $i++){
$sql .= " (?, ?, ?, ?, ?)";
$s .= 's';
$varTname = $_POST['teamname'][$i];
$varCity = $_POST['city'][$i];
$varBplayer = $_POST['bestplayer'][$i];
$varYearformed = $_POST['yearformed'][$i];
$varWebsite = $_POST['website'][$i];
$bind .= " , " . $varTname. " , " .$varCity. " , " .$varBplayer. " , " .$varYearformed. " , " .$varWebsite;
}
$sql = rtrim($sql, ','); // omit the last comma
$s = "'" .$s. "'";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($stmt, $s , $bind);
mysqli_stmt_execute($stmt);
}
?>
Normally this is done by creating arrays of form controller.
<input type="text" name="teamname[]">
<input type="text" name="city[]">
And then you can get an array in post request.
Hope this helps!
use different name like teamname1,teamname2,teamname3,teamname4
<input type="text" name="teamname1">
<input type="text" name="teamname2">
<input type="text" name="teamname3">
<input type="text" name="teamname4">
For get values :-
$varTname1 = $_POST['teamname1'];
$varTname2 = $_POST['teamname2'];
$varTname3 = $_POST['teamname3'];
$varTname4 = $_POST['teamname4'];
For insert values :-.
$sql = "INSERT INTO Teams (teamname)
VALUES ('$varTname1'),
('$varTname2'),
('$varTname3'),
('$varTname4')
or you can try this:-
<input type="text" name="teamname[]">
Get value like :-
$_POST['teamname'][0]
try this method
$sql = "INSERT INTO Teams (teamname, city, bestplayer,yearformed,website)
VALUES ('$varTname', '$varCity', '$varBplayer', '$varYearformed', '$varWebsite'),
";
$sql.= query same as abov
$sql.= query same as abov
$sql.= query same as abov
if (!$mysqli->multi_query($sql)) {
echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
note the . dot after the first query.
I think you should also use an auto increment keyThis should work.
I want to send the "fill[]" and the "item[]" and my problem is the function write cant get the values of the variables, why?
What is wrong? Im new in this stuff.
<form action="/fill_sites/fill.php" method="get">
<input type="text" size="24" maxlength="20" name="fill[0]"/>
<input type="hidden" name="item[0]value="hella_apfelschorle"/>
<input type="text" size="24" maxlength="20" name="fill[1]"/>
<input type="hidden" name="item[1]" value="volvic_wasser"/>
..... so on
<input type="submit" value="Abschicken"/>
------------------------------------------------------------>[fill/php]>
$fill[0] = $_GET["fill[0]"];
$fill[1] = $_GET["fill[1]"];
$fill[2] = $_GET["fill[2]"];
$fill[3] = $_GET["fill[3]"];
$fill[4] = $_GET["fill[4]"];
$fill[5] = $_GET["fill[5]"];
$fill[6] = $_GET["fill[6]"];
$fill[7] = $_GET["fill[7]"];
$fill[8] = $_GET["fill[8]"];
$fill[9] = $_GET["fill[9]"];
$item[0] = $_GET["item[0]"];
$item[1] = $_GET["item[1]"];
$item[2] = $_GET["item[2]"];
$item[3] = $_GET["item[3]"];
$item[4] = $_GET["item[4]"];
$item[5] = $_GET["item[5]"];
$item[6] = $_GET["item[6]"];
$item[7] = $_GET["item[7]"];
$item[8] = $_GET["item[8]"];
$item[9] = $_GET["item[9]"];
write($counterFilename[$item[]], $fill);
you can do this by following code. it will get complete array.
$item = $_Get['item'];
$fill= $_Get['fill'];
use php's foreach statement to retrieve the content of fill and item
$fills = $_GET['fill'];
foreach($fills as $fill)
{
//do something with $fill
}
and the same for $item
I'm trying to update a table of dishes with a new entry and cross reference it to an existing table of ingredients. For each dish added, the user is required to assign existing ingredients and the volume required on multiple lines. On submission, the Dish should be entered into the table 'Dishes' and the assigned ingredients should be entered into the 'DishIng' linked tabled.
My tables are set like this:
Table: "Dishes" Columns: DishID, DishName, Serves, etc...
Table: "DishIng" Columns: DishID, IngID, Volume
Table: "Ingredients" Columns: IngID, IngName, Packsize etc...
HTML:
<form action="Array.php" method="post">
<ul>
<li>DishID: <input type="text" name="DishID"></li>
<li>Name: <input type="text" name="DishName"></li>
<li>Catagory : <input type="text" name="DishCatID"></li>
<li>Serving: <input type="text" name="Serving"></li>
<li>SRP: <input type="text" name="SRP"></li>
<li>Method : <input type="text" name="Method"></li>
<li>Source : <input type="text" name="SourceID"></li>
<br>
<li>IngID: <input type="text" name="IngID"></li>
<li>Volume: <input type="text" name="Volume"></li>
<li>IngID: <input type="text" name="IngID"></li>
<li>Volume: <input type="text" name="Volume"></li>
<li>IngID: <input type="text" name="IngID"></li>
<li>Volume: <input type="text" name="Volume"></li>
</ul>
<input type="submit">
</form>
Any suggestions for dynamically adding a row of ingredients in HTML would be very welcome.
PHP:
<?php
require_once('db_connect.php');
$DishID = mysqli_real_escape_string($con, $_POST['DishID']);
$DishName = mysqli_real_escape_string($con, $_POST['DishName']);
$DishCatID = mysqli_real_escape_string($con, $_POST['DishCatID']);
$Serving = mysqli_real_escape_string($con, $_POST['Serving']);
$SRP = mysqli_real_escape_string($con, $_POST['SRP']);
$Method = mysqli_real_escape_string($con, $_POST['Method']);
$SourceID = mysqli_real_escape_string($con, $_POST['SourceID']);
$IngID = mysqli_real_escape_string($con, $_POST['IngID']);
$Volume = mysqli_real_escape_string($con, $_POST['Volume']);
$array = array('$DishID', '$IngID', '$Volume');
$sql="INSERT INTO Dishes (DishID, DishName, DishCatID, Serving, SRP, Method, SourceID)
VALUES ('$DishID', '$DishName', '$DishCatID', '$Serving', '$SRP', '$Method', '$SourceID')";
$sql2 = "INSERT INTO DishIng (DishID, IngID, Volume) VALUES ('$DishID', '$IngID', '$Volume')";
$it = new ArrayIterator ( $array );
$cit = new CachingIterator ( $it );
foreach ($cit as $value)
{
$sql2 .= "('".$cit->key()."','" .$cit->current()."')";
if( $cit->hasNext() )
{
$sql2 .= ",";
}
}
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
if (!mysqli_query($con,$sql2)) {
die('Error: ' . mysqli_error($con));
}
echo "records added";
require_once('db_disconnect.php');
php?>
Currently on submit, it only updates the 'Dishes' table and gives me this message: '1 record addedError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '('0','$DishID'),('1','$IngID'),('2','$Volume')' at line 1'
For your $sql2, the first row you add inside your foreach loop is not separated by a comma. It also does not have the same number of fields (3 and 2).
$sql2 = "INSERT INTO DishIng (DishID, IngID, Volume) VALUES ('$DishID', '$IngID', '$Volume')"; // 3 fields
...
$sql2 .= "('".$cit->key()."','" .$cit->current()."')"; // 2 fields
A good way to do this is to store your strings inside an array and use implode function with ',' as glue. A comma will be inserted automaticaly between two elements.
You need to change your form to use array-style names for the repeated inputs:
<form action="Array.php" method="post">
<ul>
<li>DishID: <input type="text" name="DishID"></li>
<li>Name: <input type="text" name="DishName"></li>
<li>Catagory : <input type="text" name="DishCatID"></li>
<li>Serving: <input type="text" name="Serving"></li>
<li>SRP: <input type="text" name="SRP"></li>
<li>Method : <input type="text" name="Method"></li>
<li>Source : <input type="text" name="SourceID"></li>
<br>
<li>IngID: <input type="text" name="IngID[]"></li>
<li>Volume: <input type="text" name="Volume[]"></li>
<li>IngID: <input type="text" name="IngID[]"></li>
<li>Volume: <input type="text" name="Volume[]"></li>
<li>IngID: <input type="text" name="IngID[]"></li>
<li>Volume: <input type="text" name="Volume[]"></li>
</ul>
<input type="submit">
</form>
Then your PHP should be:
$DishID = mysqli_real_escape_string($con, $_POST['DishID']);
$DishName = mysqli_real_escape_string($con, $_POST['DishName']);
$DishCatID = mysqli_real_escape_string($con, $_POST['DishCatID']);
$Serving = mysqli_real_escape_string($con, $_POST['Serving']);
$SRP = mysqli_real_escape_string($con, $_POST['SRP']);
$Method = mysqli_real_escape_string($con, $_POST['Method']);
$SourceID = mysqli_real_escape_string($con, $_POST['SourceID']);
$sql="INSERT INTO Dishes (DishID, DishName, DishCatID, Serving, SRP, Method, SourceID)
VALUES ('$DishID', '$DishName', '$DishCatID', '$Serving', '$SRP', '$Method', '$SourceID')";
mysqli_query($con, $sql) or die(mysqli_error($con));
$values = array();
foreach ($_POST['IngID'] as $i => $ingID) {
if (!empty($ingID)) {
$ingID = mysqli_real_escape_string($con, $ingID);
$volume = mysqli_real_escape_string($con, $_POST['Volume'][$i]);
$values[] = "('$DishID', '$ingID', '$volume')";
}
}
if (!empty($values)) {
$sql2 = 'INSERT INTO DishIng (DishID, IngID, Volume) VALUES ' . implode(', ', $values);
mysqli_query($con, $sql2) or die(mysqli_error($con));
}
You should have a look at the created Query.
There is a comma missing between your static sql2-string and the dynamic values. Also the values you want to insert are not correct I assume. With the query you create you want to insert 4 Lines and you'Re using dishID, IngID and Volume as IngID in your request what you don't want I think.
P.S.: You can use tools like MySQL Workbench to test your statements before implementing them. (And you can see their results)
Here's example for adding row dynamically using javascript, if you consider using table:
<div>
<input name='buttonadd' type='button' id='add_table' value='Add'>
</div>
<table id='mytable'>
<tr>
<td>DishID: <input type="text" name="DishID[]"></td>
<td>Name: <input type="text" name="DishName[]"></td>
<td>Catagory : <input type="text" name="DishCatID[]"></td>
</tr>
</table>
and here's the javascript:
$("#add_table").click(function(){
$('#mytable tr').last().after('<tr><td>DishID: <input type="text" name="DishID[]"></td><td>Name: <input type="text" name="DishName[]"></td><td>Catagory : <input type="text" name="DishCatID[]"></td>
</tr>');
});
i have form as below with same name text field columns, i want to insert multiple arrays data to mysql using this below form. pls tell me how to do this using foreach in php mysql
First Column
<input name="date[]" type="text" class="datepicker">
<input type="text" name="local[]" />
<input type="text" name="desc[]" />
<input type="text" name="ta[]" />
<input type="text" name="car[]" />
Second Column
<input name="date[]" type="text" class="datepicker">
<input type="text" name="local[]" />
<input type="text" name="desc[]" />
<input type="text" name="ta[]" />
<input type="text" name="car[]" />
First of all I would rename your form fields to make this easier:
<?php
$number_of_columns = 2;
for($i=0;$i<$number_of_columns;$i++) :?>
<input name="col[<?=$i?>][date]" type="text" class="datepicker">
<input type="text" name="col[<?=$i?>][local]" />
<input type="text" name="col[<?=$i?>][desc]" />
<input type="text" name="col[<?=$i?>][ta]" />
<input type="text" name="col[<?=$i?>][car]" />
<?php endfor;?>
And then once you get the data, you can just loop through the $_POST['col'] array and insert each one individually into the database. I'm assuming here that you've already connected to your database and are using the mysql library.
$cols = $_POST['col'];
$table = 'table_name';
foreach($cols as $col) {
$local = mysql_real_escape_string($col['local']);
$desc = mysql_real_escape_string($col['desc']);
$ta = mysql_real_escape_string($col['ta']);
$car = mysql_real_escape_string($col['car']);
mysql_query("INSERT INTO `{$table}` (`local`, `desc`, `ta`, `car`) VALUES('{$local}', '{$desc}', '{$ta}', '{$car}')") or die(mysql_error());
}
Try this code:
extract($_POST);
$n = count($date);
for ($i = 0; $i < n; $i++) {
$query = 'INSERT INTO `table` (`c1`, `c2`, `c3`, `c4`, `c5`) VALUES (\'' . $date[$i] . '\', \'' . $local[$i] . '\', \'' . $desc[$i] . '\', \'' . $ta[$i] . '\', \'' . $car[$i] . '\')';
// Here you must execute your query
}