How to add multiple input same name to database MySQL - php

Hi I want to add a lot of inputs with same name to my database.
I am working on a recipe submit form, that adds in ingredients with form input text. I have multiple inputs with same name, and want them all to be added to the database. By array of some sort.
I have a jquery that makes it possible to add in more ingredients and amount, don't think it is important for this question. So won't add.
Till now I have this html/php:
<form id="opskriftReg" name="opskriftReg" action="opskriftRegSave.php" method="post">
*Ingredienser:<br>
Ingrediens: <input type="text" name="ingredients[]">
Mængde: <input type="text" name="amount[]"><br>
<div id="InputsWrapper"></div>
<input type="button" id="AddMoreFileBox" value="Tilføj ingrediens"><br>
<input type="submit" value="Submit">
</form>
And this for php/database input:
$mysqli = new mysqli ("localhost","","","brugerreg");
//Add this php add to database:
$ingredients = $_POST['ingredients'];
$amount = $_POST['amount'];
echo $ingredients." ".$amount;
$sql = "INSERT INTO `brugerreg`.`opskriftreg` (`ingredients`,
`amount`) VALUES ('".$ingredients."', '".$amount."')";
$stmt = $mysqli->prepare($sql); $stmt->execute();

Make your jQuery print your inputs such as:
<input type="text" name="ingredients[]">
<input type="text" name="amount[]">
Note the [] in the name, these are called HTML input arrays.
Now you can access these inputs in your PHP as:
$ingredients = implode(',',$_POST['ingredients']);
$amount = implode(',',$_POST['amount']);
echo $ingredients."<br>".$amount; //you could comment this
$sql = "INSERT INTO `brugerreg`.`opskriftreg` (`ingredients`,
`amount`) VALUES ('".$ingredients."', '".$amount."')";
$stmt = $mysqli->prepare($sql); $stmt->execute();
You could use the implode() function to convert an array into a single string with a delimiter

Found here.
Every time you add new input with same name, append it with "[]", so in the end you get:
Ingrediens: <input type="text" name="ingredients[]">
Mængde: <input type="text" name="amount[]"><br>
Ingrediens: <input type="text" name="ingredients[]">
Mængde: <input type="text" name="amount[]"><br>
Ingrediens: <input type="text" name="ingredients[]">
Mængde: <input type="text" name="amount[]"><br>
And in php:
$ingredients = $_POST['ingredients']; // $ingredients is now an array
$amount = $_POST['amount']; // $amount is now an array
echo $amount[0];
echo $amount[1];
To insert it into database just prepare the query accordingly, for example iterate over the array and concatenate the "('".$ingredients."', '".$amount."')" for every pair.
$values = "".
for ($i = 0; $i < sizeof($amount); $i++) {
$values .= "('".$ingredients[$i]."', '".$amount[$i]."')";
if ($i != sizeof($amount) - 1) {
$values .= ", ";
}
}
$sql = "INSERT INTO `brugerreg`.`opskriftreg` (`ingredients`,`amount`) VALUES " . $values;

Related

Insert multiple arrays with PHP PDO

I am doing a program with PHP but this is the first time I need to enter many arrays in a table. In the input I must place [] but when making the query insert how should I do? What I present in the code only saves me the last value without the [], and in the console, it passes the values ​​that I need, but it only inserts the last value.
<form class="" action="asignar-fechas.php" method="post">
<?php foreach ($infoGrupo2 as $iGrupo2){
if(($iGrupo2['fechaInicio']==$fechaA['numero_fecha'])){
?>
<input type="hidden" name="id_grupo2[]" value="<?php echo $iGrupo2['id_grupo'];?>">
<input type="hidden" name="modo2[]" value="<?php echo $iGrupo2['modo'];?>">
<input type="hidden" name="fecha2[]" value="<?php echo $iGrupo2['fechaInicio'];?>">
<input type="hidden" name="participante[]" value="<?php echo $iGrupo['participante'];?>">
<input type="hidden" name="jugador<?php echo $juga;?>[]" value="<?php echo $in2['id_users'];?>">
}}?>
<input type="submit" name="enviar" value="ASIGNAR FECHAS">
asignar-fechas.php
$id_grupo = $_POST['id_grupo2'];
$modo = $_POST['modo2'];
$fecha = $_POST['fecha2'];
$participante = $_POST['participante'];
$j1 = $_POST['jugador1'];
$j2 = $_POST['jugador2'];
$j3 = $_POST['jugador3'];
$j4 = $_POST['jugador4'];
$insertarF = "INSERT INTO fechaxgrupo (grupo, fecha,estado) VALUES (:grupo, :fecha,0)";
$insertF = $conn->prepare($insertarF);
$insertF->bindParam(':grupo', $id_grupo);
$insertF->bindParam(':fecha', $fechaa);
$insertF->execute();
The $_POST variables elements will be arrays, you can loop over them. You need to bind to the iteration variables, not the arrays.
$insertarF = "INSERT INTO fechaxgrupo (grupo, fecha,estado) VALUES (:grupo, :fecha,0)";
$insertF = $conn->prepare($insertarF);
$insertF->bindParam(':grupo', $id_grupo);
$insertF->bindParam(':fecha', $fecha);
foreach ($_POST['id_grupo2'] AS $i => $id_grupo) {
$fecha = $_POST['fecha2'][$i];
$insertF->execute();
}

How to update multiple records in mysql with multiple ids

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

Using PHP “insert multiple” to insert all 4 rows at the same time

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.

Issues inserting muliple MySQL from PHP

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>');
});

PHP mysql: inserting data from an array

I'm having trouble extracting arrays to insert into the database. My form accepts multiple and dynamic number of inputs so I have the data in an array with inputs phonenos[] and phonetypes[]:
<form name="add" action="" method="POST">
<input name="name" type="text" placeholder="Name"></input><br />
<input name="qty" type="text" placeholder="Qty"></input><br /> -->
<input class="form-control required" name="phonenos[]" maxlength="14" type="text" placeholder="number..."><br>
<select class="form-control" name="phonetypes[]">
<option value="0">Choose a phone type</option>
<option value="Main">Main</option>
<option value="Fax">Fax</option>
<option value="Mobile/Direct">Mobile/Direct</option>
</select>
<div id="addmore">
<input type="button" value="Add More" onClick="addRow(this.form)"></input>
</div>
<input type="submit" value="submit" name="action"></input>
</form>
In my PDO query:
..... first query insertion...
$phonenos = $_POST['phonenos'];
foreach($_POST['phonenos'] as $phoneno) {
$phoneno;
}
$phonetypes = $_POST['phonetypes'];
foreach($_POST['phonetypes'] as $phonetype) {
$phonetype;
}
$sql = 'INSERT INTO phone (p_id, phoneno, phonetype) values (:p_id, :phoneno, :phonetype)';
$query = $conn->prepare($sql);
$query->execute( array(
':p_id'=>$lastid,
':phoneno'=>$phoneno,
':phonetype'=>$phonetype
));
So I did a var_dump on variables $phoneno and $phonetype after a submission of multiple phone numbers and it only printed out the last number and type whereas I wanted the entire list that was submitted. How do I get all the data so I can insert it into the database?
If you want all the numbers inserted in the same column, then the best solution I can think is to serialize them before you insert in db.
$phonenos = serialize($_POST['phonenos']);
$phonetypes = serialize($_POST['phonetypes']);
$sql = 'INSERT INTO phone (p_id, phoneno, phonetype) values (:p_id, :phoneno, :phonetype)';
$query = $conn->prepare($sql);
$query->execute( array(
':p_id'=>$lastid,
':phoneno'=>$phonenos,
':phonetype'=>$phonetypes
));
I figured out the solution through a for loop.
$phones = $_POST['phones'];
$phonetypes = $_POST['phonetypes'];
for($i = 0, $j = 0; $i <= $phones, $j <= $phonetypes; $i++, $j++) {
$phone = $phones[$i];
$phonetype = $phonetypes[$j];
$sql = "INSERT INTO phone (p_id, phone, phonetype) values (:p_id, :phone, :phonetype)";
$query = $conn->prepare($sql);
$query->execute( array(
':p_id'=>$lastid,
':phone'=>$phone,
':phonetype'=>$phonetype
));
}

Categories