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();
}
Related
I want to get three values separated by a comma when the form is submitted. The value from the checkbox, textbox 1 and textbox 2.
This is my code that retrieves values from mysql database and generates checkboxes and two corresponding textboxes.
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
$query = "SELECT * FROM subject";
$data = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($data)){
$s = $row['sub'];
echo $s;
?>
<input type="checkbox" name="req_sub[]" value= "<?php echo $s; ?>" />
<input type="text" name="<?php echo $s; ?>" placeholder="Total Number" />
<input type="text" name="<?php echo $s; ?>" placeholder="Pass Number" />
<?php
}
?>
<input type="submit" name="submit" value="Add">
</form>
Suppose the user checks the first three boxes , and enters the values like in this picture -
when I click add, I get the values --
Physics
Math
Chemistry
by using the code below:
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['req_sub'])) {
foreach ($_POST['req_sub'] as $selected) {
echo $selected."</br>";
}
}
}
?>
but how do I get the values like this-
Physics,40,30
Math,40,30
Chemistry,30,25
I want this output in a variable so that I can store it in my database table.
I have spent several hours behind this in last few days. Please help me with this one.
you need to assign unique names to the <input type="text" ... /> so you can recieve its values in the PHP.
Second, you need to write PHP code, that's concatenating those values.
For example, your HTML code might be:
<input type="checkbox" name="req_sub[]" value= "<?php echo $s; ?>" />
<input type="text" name="total[<?php echo $s; ?>]" placeholder="Total Number" />
<input type="text" name="pass[<?php echo $s; ?>]" placeholder="Pass Number" />
and your PHP code might be:
if (isset($_POST['submit'])) {
if (!empty($_POST['req_sub'])) {
foreach ($_POST['req_sub'] as $selected) {
$total = $_POST['total'][$selected];
$pass = $_POST['pass'][$selected];
$var = $selected . ',' . $total . ',' . $pass;
echo $var . '<br />';
}
}
}
Am looping products out from product table to add them to cart table. only the selected product by checking the checkbox should be added, but if you select, the selected ones do not correspond..
HERE IS THE HTML GETTING THE PRODUCTS OUT
<html>
<form action="#" id="" class="horizontal-form" method="post">
<?php
$LISTP = "SELECT * FROM products ORDER BY id";
$sn = 0;
$stmt = $pdo->prepare($LISTP);
$stmt->execute();
while($list = $stmt->fetch(PDO::FETCH_ASSOC)){
$sn = $sn + 1;
$ID = $list['id'];
$NAME = $list['name'];
?>
<input type="checkbox" name="slected[]" class="checkboxes" value="1" />
<input type="hidden" name="productid[]" class="" value="<?php echo $ID;?>" />
<input type="text" name="name[]" class="" value="<?php echo $NAME;?>" />
<?php }?> </form>
<?php
// now when we submot the form
$slected = $_POST['slected'];
$prod = $_POST['productid'];
$name = $_POST['name'];
foreach($prod as $key => $product){
if($slected[$key]>0){
echo $product.' '.$name[$key].' '.#$slected[#$key].'--<br>';
}
// the problem is here, if you check all product it will work well, but if you check the second one
// it would echo the second one giving it the name of the first one which was not checked at all
?>
I used to do this the same way in the past, and have discovered what I think is a better way. Rather than having a hidden input that stores the ID, just use the ID as the index for all of the form variable keys:
<input type="checkbox" name="slected[<?php echo $ID; ?>]" class="checkboxes" value="1" />
<input type="text" name="name[<?php echo $ID; ?>]" class="" value="<?php echo $NAME;?>" />
Then, your PHP can be simplified:
// now when we submot the form
$slected = $_POST['slected'];
$name = $_POST['name'];
foreach( (array)$slected as $ID => $on ) {
echo $product . ' ' . $name[$ID] . ' ' . $ID . '--<br>';
}
So - basically, your $slected variable will contain an array of only items that are selected, AND you have the product ID built in to the $slected array.
First of all my apopoliges , this may b a possible duplicate question, I searched and found few answered but they are not very helpfull in my case.
I have the follwing form with static and dynamic values
<input type="hidden" value="<?php echo $Quote ?>" id="amount" name="amount"/>
<input type="hidden" value="<?php echo $NoDays?>" id="total_days" name="total_days"/>
<?php $sql = mysql_query("select * from tbloffers ORDER BY Sequence"); ?>
<?php while($rows = mysql_fetch_array($sql)) { ?>
<input type="hidden" value="<?php echo $rows['Id']; ?>" name="offerid[]" />
<input type="hidden" value="<?php echo $rows['Name']; ?>" name="offername[]" />
<input type="hidden" value="<?php echo $rows['Price']; ?>" name="offercharges[]" />
<?php } ?>
<input type="email" id="customeremail" name="customeremail" required/>
And my save.php file is
$date = date("j M, Y");
$total_days = mysql_real_escape_string($_POST["total_days"]);
$amount = mysql_real_escape_string($_POST["amount"]);
$customeremail = mysql_real_escape_string($_POST["customeremail"]);
$offerid = $_POST["offerid"];
$offername = $_POST["offername"];
$offercharges = $_POST["offercharges"];
when I hit Submit I would like to be able to have all those values inserted into database through a loop. I tried foreach and struggled.
Note: The static values will repeat with dynamic values.
e.g $date, $amount will remain same on Insertion.
$sql = "INSERT INTO table < What comes next?
Thanks in advance.
You can use a foreach loop to loop over one of the repeated inputs, and then use the index to access the corresponding elements in the others:
foreach ($offerid as $i => $offer) {
$offer = mysql_real_escape_string($offer);
$name = mysql_real_escape_string($offername[$i]);
$charges = mysql_real_escape_string($offercharges[$i]);
mysql_query("INSERT INTO table (date, total_days, amount, customer_email, offerid, offername, offfercharges)
VALUES ('$date', '$total_days', '$amount', '$customeremail', '$offer', '$name', $charges')");
}
P.S. You really should stop using the mysql extension and upgrade to mysqli or PDO, so you can use prepared queries instead of string substitution.
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 a list
Each row has a common input field "sort_order" that's stored in MySQL db.
<input name="sort_order" type="text" value="<?php echo $cat['sort_order']; ?>" size="3" />
I want to be able to change the sort order inline, without going into the edit form.
How do I get all the values into the database. I think I need to loop through each row adding the sort_order[row_id] and value to an array. But I am stuck on how to achieve this.
all the values are posting according to firePHP. sort_order[50] 1, sort_order[51] 2 etc.
New Attempt at explaining:
I have a list view with 2 input fields.
<input name="cat_id" type="hidden" value="<?php echo $cat['cat_id']; ?>" />
<input name="sort_order" type="text" value="<?php echo $cat['sort_order']; ?>" size="3" />
I have a function that's called on post in the controller:
public function sortOrderUpdate(){
//collect the values of cat_id and sort_order from each input into a array
//$this->request->post['sort_order']
//$this->request->post['cat_id']
//send to the model
$this->model_cat->updateCatSortOrder($sortorderarray);
}
And the database model file function:
public function updateCatSortOrder($sortorderarray){
foreach((int)$sortorderarray as $sort){
$this->db->query("UPDATE cat SET sort_order='" . (int)$sort['sort_order'] . "' WHERE cat_id = '" . (int)$sort['cat_id'] . "'");
}
}
Whats the best way to achieve this?
Just use empty square brackets:
<input type="text" name="sort_order[]" value"<?php echo $sort_order; ?>" />
You can then access the input as an array, saving you from building it yourself. It'll be stored as $_POST['sort_order'] (or $_GET, depending on the method attribute specified in your <form> tag).
On a related note, you should probably escape $sort_order when echoing it:
<input type="text" name="sort_order[]" value"<?php echo htmlspecialchars($sort_order); ?>" />
i would not recommend using [ ] in html names.
<input type="text" name="sort_order_<?php echo $row_id; ?>" value"<?php echo $sort_order; ?>" />
say, you have 50 input fields, when posted, you can build an array this way:
$sortorder = array();
for($i=0; $i<50; $i++){
$sortorder[] = $_REQUEST['sort_order_' . $i];
}
Ok this seems to work:
<input name="cat_id[]" type="hidden" value="<?php echo $cat['cat_id']; ?>" />
<input name="sort_order[]" type="text" value="<?php echo $cat['sort_order']; ?>" size="3" />
Controller:
public function updateCatSortOrder(){
$sortvals = $this->request->post['sort_order']; //$this->request->post same as $_POST
$row = $this->request->post['cat_id'];
$n = count($this->request->post['cat_id']);
$sortorder = array();
for($i=0; $i<$n; $i++){
$sortorder[] = array(
'cat_id' => $row[$i],
'sort_order' => $sortvals[$i]
);
}
$this->model_cat->updateCatSortOrder($sortorder);
}
Model:
//UPDATE CAT SORT ORDER
public function updateCatSortOrder($sortorder){
foreach($sortorder as $sort){
$this->db->query("UPDATE cat SET sort_order='" . $this->db->escape($sort['sort_order']) . "' WHERE cat_id = '" . $this->db->escape($sort['cat_id']). "'");
}
}