multiple arrays data posting and mysql insert using foreach php - php

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
}

Related

POST value from html select list?

i am trying to send some information to insert-event.php. Every piece of data comes through, except the options listed in my SELECT.
<form action="php/insert-event.php" method="post">
<select id="skoleDropdown" name="skole"><option hidden>Velg skole</option>"' . $skoleAttributter . '" </select>
<input type="text" name="Title" placeholder="Tittel" class="ico-title" required></input>
<input type="text" name="description" placeholder="Beskrivelse" class="ico-title" required></input>
<input type="text" name="pris" placeholder="Pris i NOK" class="ico-title" required></input>
<input type="date" name="date" class="ico-title" required></input>
<input type="text" name="img_url" placeholder="Bildelenke" class="ico-title" required></input>
<input type="text" name="type" placeholder="Type arrangement" class="ico-title" required></input>
<input type="submit" name="submit" value="LEGG TIL"></input>
</form>
</div>';
And then i have my insert-event.php:
<?php
$title = $_POST['Title'];
$pris = $_POST['pris'];
$date = $_POST['date'];
$url = $_POST['img_url'];
$description = $_POST['description'];
$school = $_POST['skole'];
$schoolId = '';
$type = $_POST['type'];
switch($school) {
case 'Campus Brennerviveien';
$schoolId == 1;
break;
case 'Campus Vulkan';
$schoolId == 2;
break;
case 'Campus Fjerdingen';
$schoolId == 3;
break;
}
// Connect and select DB
$connect = mysqli_connect('localhost', 'chris', 'chris');
if (!$connect) {
echo 'Not connected';
}
if (!mysqli_select_db($connect, 'eksamen')) {
echo 'Database not selected';
}
// Submit
$sql = "INSERT INTO events (id, title, description, pris, img_url, date, type, skole_id)
VALUES (NULL, '$title', '$description', '$pris', '$url', '$date', '$type', '$schoolId')";
if ($connect->query($sql) === TRUE) {
header("Location:../index.php");
exit;
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
$connect->close();
?>
I think maybe this speaks for itself.
Appreciate help.
Thanks!
proper method of select is
<select name="skole" id="skole">
<option value="test"> option one text here </option>
<option value="test2"> option two text here </option>
</select>
when your request to select like
$school = $_POST['skole']; ====> $school = 'test'
when select have selected then it will gives you the value of option other it can not give any value.
thanks
you have to use value attribute for select tag to send data on post page
<select id="skoleDropdown" name="skole">
<option hidden value="Velg skole">Velg skole</option>"' . $skoleAttributter . '"
</select>
then this should be like
<form action="php/insert-event.php" method="post">
<select id="skoleDropdown" name="skole"><option hidden value="Velg skole">Velg skole</option>"' . $skoleAttributter . '" </select>
<input type="text" name="Title" placeholder="Tittel" class="ico-title" required></input>
<input type="text" name="description" placeholder="Beskrivelse" class="ico-title" required></input>
<input type="text" name="pris" placeholder="Pris i NOK" class="ico-title" required></input>
<input type="date" name="date" class="ico-title" required></input>
<input type="text" name="img_url" placeholder="Bildelenke" class="ico-title" required></input>
<input type="text" name="type" placeholder="Type arrangement" class="ico-title" required></input>
<input type="submit" name="submit" value="LEGG TIL"></input>
</form>
</div>';
And then this will be like this
$skoleListe = Skole::all();
$skoleAttributter = '';
foreach($skoleListe as $skole)
{
$skoleAttributter.= '<option value="' .$skole['id'] . '">' . $skole['navn'] . '</option>';
}
you have added "" this double time remove one from option value attibute
Extra double quotes problem so values is setting empty
$skoleAttributter.= '<option value=""' .$skole['id'] . '">' . $skole['navn'] . '</option>';
^^^
change to
$skoleAttributter.= '<option value="' .$skole['id'] . '">' . $skole['navn'] . '</option>';
^^^^
1) And no need switch case because your setting id as a value attribute . so you can directly use it as schoolId
Try to use prepared statement or pdo to avoid sql injection .

PHP inserting multiple checkbox AND textbox arrays into MySQL Database

I'm having trouble with the array results in my php. My first problem is this :
It shows everything even if the checkbox isn't checked. My second problem is that it won't insert the values to the database even though it's connected to the database (as you can see in the previous screenshot, it says "connected successfully").
This is my html form:
<form method="POST">
<input type="hidden" name="item[]" value="cupcake">
<input type="text" name="items" value="cupcake" readonly><br>
<b>Price :</b> <span name="price" value="3.00">$17.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[]" type="checkbox" value="17" /><span>Add to Cart</span></label></div></div></td><br>
<input type="hidden" name="item[]" value="cake">
<input type="text" name="items" value="cake" readonly><br>
<b>Price :</b> <span name="price" value="20.00">$20.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[]" type="checkbox" value="20" /><span>Add to Cart</span></label></div></div></td><br>
<input type="submit" name="insertBT"><br>
</form>
PHP:
if(isset($_POST['insertBT']))
{
class db_conn
{
public function create_conn($servername, $username, $password, $db)
{
global $conn;
$conn = new mysqli ($servername, $username, $password, $db);
}
public function check_conn()
{
global $conn;
if($conn->connect_error)
{
die ("Connection Failed : " . $conn->connect_error);
}
else
{
echo ("Connected Successfully <br>");
}
}
public function insert()
{
if(isset($_POST['checkbox'])) {
foreach($_POST['checkbox'] as $check) {
$check = implode(',', $_POST['checkbox']);
$name = implode(',', $_POST['item']);
$quantity = implode(',', $_POST['quantity']);
}
echo $check . "<br>";
echo $name . "<br>";
echo $quantity . "<br>";
mysql_query("INSERT INTO purchases(Product, Quantity, Price) VALUES('$name', '$quantity','$check')");
}
}
}
$obj1 = new db_conn;
$obj1->create_conn("localhost","root","", "dbtest");
$obj1->check_conn();
$obj1->insert();
}
You shouldn't be using implode. That puts a comma-separated list of everything in the form into each row that you insert, and repeats this for every box that's checked. You should just insert one item in each row, by indexing the arrays.
However, when you have a checkbox in a form, it only submits the ones that are checked. The result of this is that the indexes of the $_POST['checkbox'] array won't match up with the corresponding $_POST['item'] and $_POST['quantity'] elements. You need to put explicit indexes into the checkbox names so you can relate them.
<form method = "POST">
<input type = "hidden" name = "item[]" value = "cupcake">
<input type = "text" name = "items" value = "cupcake" readonly><br>
<b>Price :</b> <span name = "price" value = "3.00">$17.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[0]" type="checkbox" value="17" /><span>Add to Cart</span></label></div></div></td><br>
<input type = "hidden" name = "item[]" value = "cake">
<input type = "text" name = "items" value = "cake" readonly><br>
<b>Price :</b> <span name = "price" value = "20.00">$20.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[1]" type="checkbox" value="20" /><span>Add to Cart</span></label></div></div></td><br>
<input type = "submit" name = "insertBT"><br>
</form>
Then your PHP code can be like this:
$stmt = $conn->prepare("INSERT INTO purchases (Product, Quantity, Price) VALUES (?, ?, ?)");
$stmt->bind_param("sis", $name, $quantity, $price);
foreach ($_POST['checkbox'] as $i => $price) {
$name = $_POST['name'][$i];
$quantity = $_POST['quantity'][$i];
$stmt->execute();
}
BTW, putting the prices in your HTML seems like a bad idea. Nothing stops the user from modifying HTML using the web inspector before they submit the form, so they could lower the price. You should get the prices from the database when processing the form.
Also, notice that in your original code you opened the database connection using MySQLi, but then you tried to do the insert using mysql_query instead of $conn->query(). You can't mix APIs like that; myql_query can only be used when you open the connection with mysql_connect.

How to get two arrays values within one foreach()

There are two values I want to get from user that is name and price. I have made an auto generating rows function that generate input boxes with same name. Now the thing is I want to store them in database. I using foreach but that only get one array. I want to store both name as well as price. How can I do that. Here is my code.
HTML Form
<form method="post">
<input type="text" name="name[]" /><input type="text" name="price[]" />
<input type="text" name="name[]" /><input type="text" name="price[]" />
<input type="text" name="name[]" /><input type="text" name="price[]" />
<input type="text" name="name[]" /><input type="text" name="price[]" />
<input type="submit" value="Submit" name="submit" />
</form>
PHP Code
if(isset($_POST['submit']))
{
foreach($_POST['name'] as $name)
{
echo $name;
}
}
Call the index in the loop as well and then select the corresponding value from the other array.
foreach($_POST['name'] as $id => $name)
{
echo $name;
echo $_POST['price'][$id]
}
How about this
if(isset($_POST['submit']))
{
$names = $_POST['name']; # array
$prices = $_POST['price']; # array
foreach($names as $id => $name)
{
echo $name;
echo "<br>";
echo $prices[$id]
}
}
Provided you know both arrays will be the same length, a simple for loop will do:
if(isset($_POST['submit']) && count($_POST['name']) == count($_POST['price']))
{
for($i=0; $i < count($_POST['name']); $i++)
{
echo $_POST['name'][$i] . ' ' . $_POST['price'][$i];
}
}
Try this
$names = array_combine($_POST['name'], $_POST['price']);
foreach($names as $firstname => $price) {
echo $firstname . ' ' . $price . '<br>';
}

Insert array values + single form values into all rows

I am trying to insert values from a form into my mysql database. I have single value forms + array values from the form. How can I insert the array values into my database with the single form values attached to all rows?
The HTML:
Start:<br>
<input type="text" name="start" id="start">
End:<br>
<input type="text" name="end" id="end">
<input type="text" name="item[]" placeholder="Manufacturer #" /><br>
<input type="text" name="description[]" placeholder="Description" /><br>
<input type="text" name="item[]" placeholder="Manufacturer #" /><br>
<input type="text" name="description[]" placeholder="Description" /><br>
<input type="text" name="item[]" placeholder="Manufacturer #" /><br>
<input type="text" name="description[]" placeholder="Description" /><br>
The PHP:
if (isset($_POST['submit']))
{
$link = mysql_connect('localhost', 'user', 'pass');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydb") or die(mysql_error());
echo 'Connected successfully';
$query = "INSERT INTO agreement (start, end, item_number, item_description) VALUES ";
foreach($_POST['item'] as $i => $item)
{
// Get values from post.
$item = mysql_real_escape_string($item);
$description = mysql_real_escape_string($_POST['description'][$i]);
$start = mysql_real_escape_string($_POST['start'][$i]);
$end = mysql_real_escape_string($_POST['end'][$i]);
// Add to database
$query = $query." ('$start','$end','$item','$description') ,";
}
$query = substr($query,0,-1); //remove last char
$result = mysql_query($query);
}
I will be changing the code to mysqli/pdo, I know that the current code is unsecure.
Any help is appreciated, thanks!
Just use $_POST['start'] and $_POST['end'] without array access since they will be the same each time. You can use array access for item and description.

php add multiple input fields to mysql

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.

Categories