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
));
}
Related
may I know is it possible for submit a table form to a selected table in mysqli database based on drop down selection ?
For an example, user can select which table A or B in a mysqli database using the drop down selection and click send.
Below code is just an example (but my exact code)
Requesting for the resolution.
Thank you.
<form method="post" action="">
<table name="userform" >
<tr><th>Full Name</th>
<th> Week </th></tr>
<tr><td><input name="name" type="text" id="name"></td>
<td><input name="week" type="number" id="week"></td></tr>
</table>
<select name="sendToWho" >
<option value="tableA" >table A</option>
<option value="tableB" >table B</option>
<option value="tableC">table C</option>
<input type="submit" name="save" id="save" value="Save Data">
</form>
I used '".$name[$tableName]."' because it is a add,delete,editable table before send to the mysqli database,
<?php
$conn = mysqli_connect("localhost","root","","mySystem");
$sendTO = [
"tableA" => "optionA",
"tableB" => "optionB",
"tableC" => "optionC",
];
foreach ($sendTO as $tableName => $optionName)
{
$table = isset($_POST["userform"], $sendTO[$_POST["name"]])
? $sendTO[$_POST["week"]]
: $sendTO[0];
$sql = "INSERT INTO `$table`(Name, Week) VALUES ('".$name[$tableName]."','".$week[$tableName]."')";
$query = mysqli_query($conn,$sql);
}
?>
Not entirely sure of what you are trying to achieve, but something like this could work:
$conn = mysqli_connect("localhost","root","","mySystem");
if (isset ($_POST['save'])){
$name = $_POST['name'];
$week = $_POST['week'];
$sendTo = $_POST['sendToWho'];
//check which option was selected and delegate the correct table accordingly
switch ($sendTo){
case 'tableA':
$stmt = $conn->prepare('INSERT INTO optionA (Name, Week) VALUES (?,?)');
break;
case 'tableB':
$stmt = $conn->prepare('INSERT INTO optionB (Name, Week) VALUES (?,?)');
break;
case 'tableC':
$stmt = $conn->prepare('INSERT INTO optionC (Name, Week) VALUES (?,?)');
break;
default:
echo "error";
break;
}
$stmt->bind_param('ss', $name, $week); // see www.php.net/manual/en/mysqli-stmt.bind-param.php
$stmt->execute();
}
Am having a problem inserting multiple rows of data into a table at once. The following is what i have.When i click on submit, only the last row is inserted with only the first digit of quantity. please help.
html form:
<form method="post" action="insert.php">
<p><input type="text" id="product_id" name="product_id[]"/>
<input type="text" id="quantity" name="quantity[]"/></p>
<p><input type="text" id="product_id" name="product_id[]"/>
<input type="text" id="quantity" name="quantity[]"/></p>
<p><input type="text" id="product_id" name="product_id[]"/>
<input type="text" id="quantity" name="quantity[]"/></p>
<input type="submit" name="submit" value="submit"/>
</form>
insert.php page:
<?php
include 'config/auth.php';//database connection
if(isset($_POST['submit'])){
$product = mysqli_real_escape_string($dbc, $_POST['product_id']);
$quantity = mysqli_real_escape_string($dbc, $_POST['quantity']);
$count = sizeof($product);
for ($i=0; $i < $count; $i++) {
$Inproduct = $product[$i];
$Inquantity = $quantity[$i];
$query = "INSERT INTO sales (product_id, quantity) VALUES ('$Inproduct','$Inquantity')";
$results = mysqli_query($dbc, $query);
}
if ($results) {
echo 'Success';
}
}
?>
the following code worked... thanks #kmdm
$product = $_POST['product_id'];
$quantity = $_POST['quantity'];
$count = sizeof($product);
for ($i=0; $i < $count; $i++) {
$Inproduct = mysqli_real_escape_string($dbc, $product[$i]);
$Inquantity = mysqli_real_escape_string($dbc, $quantity[$i]);
$query = "INSERT INTO sales (product_id, quantity) VALUES ('$Inproduct','$Inquantity')";
$results = mysqli_query($dbc, $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.
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;
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.