Save mysql while loop data into arrays and then save into database - php

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.

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

Inserting an array of checkbox values into a database including unchecked

In the form below, students are selected from student table in my DB. For each student selected a checkbox is checked if the student is absent and left unchecked if the student is present. The form is later on submitted for it to be inserted in the exam_status table in my DB.
<form method="POST" action="action.php">
<?php
$query = "SELECT * from student ORDER BY student_name,student_surname";
$result=mysqli_query($conn,$query);
if(false===$result)
{
printf("error: %s \n",mysqli_error($conn));
}
while($row= $result->fetch_assoc())
{
$studentmatricule = $row['student_matricule'];
$studentname = $row['student_name'];
$studentsurname = $row['student_surname'];
?>
<div id="studentdiv">
<label>Matricule</label>
<input type="text" name="matricule[]" value="<?php echo "$studentmatricule)"; ?>" readonly>
<label>Name</label>
<input type="text" name="name[]" value="<?php echo "{$studentname} {$studentsurname}"; ?>" readonly>
<label > Absent
<input type="checkbox" name="absent[]" value="absent" />
</label>
</div> <br><br>
<?php
}
?>
<input type="submit" name="submit" value="submit">
</form>
and my action page "action.php" is as follows
$matricule = $_POST['matricule'];
$absent=$_POST['absent'];
for ($i=0; $i<sizeof($matricule); $i++)
{
if($absent[$i]=='absent')
{
$status='absent';
}else{
$status='present';
}
$query = "INSERT INTO exam_status (student_matricule,status) VALUES ('". $matricule[$i] . "','". $status . "')";
$result=mysqli_query($conn,$query);
}
Now the issue is it doesn't just work as i want. the result always gives the first student absent and the rest present. I have tried all i can and have really researched too but with no success at all. Please anyone around to help me out?
Thanks in advance!
<form method="POST" action="action.php">
<?php
$query = "SELECT * from student ORDER BY student_name,student_surname";
$result=mysqli_query($conn,$query);
if(false===$result)
{
printf("error: %s \n",mysqli_error($conn));
}
$index = 0;
while($row= $result->fetch_assoc())
{
$index++;
$studentmatricule = $row['student_matricule'];
$studentname = $row['student_name'];
$studentsurname = $row['student_surname'];
?>
<div id="studentdiv">
<label>Matricule</label>
<input type="text" name="studenInfo[<?php echo $index; ?>][matriculate]" value="<?php echo $studentmatricule; ?>" readonly>
<label>Name</label>
<input type="text" name="studenInfo[<?php echo $index; ?>][name]" value="<?php echo $studentname." ".$studentsurname; ?>" readonly>
<label > Absent
<input type="checkbox" name="studenInfo[<?php echo $index; ?>][status]" value="absent" />
</label>
</div> <br><br>
<?php
}
?>
<input type="submit" name="submit" value="submit">
Update your mail file like this. I have changed the form names into a single array. The reason is the checkbox values won't post to the page when the values are not checked. So its not possible to track which one was checked and which is not if you have same name.
And update your action.php like this,
<?php
$conn = mysqli_connect("localhost","username","password","db_name"); // update this values as per your configuration
$studenInfo = (!empty($_POST['studenInfo'])) ? $_POST['studenInfo'] : [];
foreach($studenInfo as $value ) {
$status = (isset($value['status'])) ? 'absent' : 'present';
$query = "INSERT INTO exam_status (student_name, student_matricule,status) VALUES ('". $value['name'] . "','". $value['matriculate'] . "','". $status . "')";
$result=mysqli_query($conn,$query);
}
?>
I have used my own table schema where i have added student_name in exam_status table for better tracking. Now you can see the values updating correctly. Also we can use bulk insert if we need to insert multiple data (Note : I haved used the bulk insert in this answer, i just followed the way you used)

looped list always inserts first in list using checkboxes

I have a list that is populated from a database table as below.
<?php
while($row=mysql_fetch_array($result))
{
?>
<tr>
<td>
<input type="checkbox" name="name[]" value="<?php echo
$row['AnalysisID']; ?>">
<?php echo $row["CustomerName"]; ?>
<input type="hidden" name="Site[]" value="<?php echo $row["Site"]; ?>">
<input type="hidden" name="Unit[]" value="<?php echo $row["Unit"]; ?>">
</td>
<td><?php echo $row['Site']; ?></td>
<td><?php echo $row['Unit']; ?></td>
</tr>
<?php
}
?>
This displays the data perfectly, and in inspect all data is correct.
However I want to be able to check the various check-boxes and insert those rows to another table.
to achieve this I am using:
$counter = count($_POST["name"]);
for($x=0; $x<=$counter; $x++){
if(!empty($_POST["name"][$x])){
$PI_NO = mysql_real_escape_string($_POST["name"][$x]);
$CUSTOMER_NAME = mysql_real_escape_string($_POST["Site"][$x]);
$PI_ADDRESS = mysql_real_escape_string($_POST["Unit"][$x]);
$qry="INSERT INTO test1 (AnalysisID, Elem, Lube) VALUES ('$PI_NO','$CUSTOMER_NAME','$PI_ADDRESS')";
mysql_query($qry);
}
}
The problem is it doesn't matter what rows I check it always inserts the first in the list, it inserts the correct number just from the start of the list.
For example if I check the last 4 in the list I get the first 3.
Any pointers would be a great help.
Checkbox values are only sent if the checkboxes are checked, so the index will be different in the $_POST["name"] and the other $_POST arrays.
(Unchecked checkbox inputs are seen as "unsuccessful" https://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.2 )
Try adding the ID as index instead, then selected data will keep together.
(I renamed the name array to aid to better match the contents)
<td>
<input type="checkbox" name="aid[<?php echo $row['AnalysisID']; ?>]" value="1">
<?php echo $row["CustomerName"]; ?>
<input type="hidden" name="Site[<?php echo $row['AnalysisID']; ?>]" value="<?php echo $row["Site"]; ?>">
<input type="hidden" name="Unit[<?php echo $row['AnalysisID']; ?>]" value="<?php echo $row["Unit"]; ?>">
</td>
Then looping through the post data with foreach(). Only the checked ID's will be posted so no need for if (!empty() check.
if (isset($_POST["aid"])) { // to avoid php undefined notice if none selected
foreach ($_POST["aid"] as $id=>$value){ // the index is what we need, using $id
$PI_NO = mysql_real_escape_string($id);
$CUSTOMER_NAME = mysql_real_escape_string($_POST["Site"][$id]);
$PI_ADDRESS = mysql_real_escape_string($_POST["Unit"][$id]);
$qry="INSERT INTO test1 (AnalysisID, Elem, Lube) VALUES ('$PI_NO','$CUSTOMER_NAME','$PI_ADDRESS')";
mysql_query($qry);
}
}
Also I strongly advice you to change from using deprecated mysql_* functions, use mysqli or PDO instead. Why shouldn't I use mysql_* functions in PHP?

Working with checkbox from form array in php

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.

Need help for database update query in php form - Joomla database

Let's say I have a table with 10 records and I want to take name, lastname and rank from those 10 records. First I do something like this:
<?php // DATABASE SELECT QUERY
$db =& JFactory::getDBO();
$query="SELECT name, lastname, rank
FROM table
ORDER BY rank ASC";
$db->setQuery($query);
$rows = $db->loadObjectList(); ?>
Then, I add some fields in to my form that contain table's values, so I can edit them through form:
<form action="#" method="post" name="form">
<table><?php $count = 0; while ($count < 10){
$name = $rows[$count]->name;
$lastname = $rows[$count]->lastname;
$rank = $rows[$count]->rank; ?>
<tr>
<td><input name="name" value="<?php echo $name ?>" type="text" /></td>
<td><input name="lastname" value="<?php echo $lastname ?>" type="text" /></td>
<td><select name="rank">
<option value="<?php echo $rank ?>"><?php echo $rank ?></option>
<option disabled="disabled" value="...">...</option>
<?php for ($i = 0; $i <= 100; $i++){ ?>
<option value="<?php echo $i ?>"><?php echo $i ?></option> <?php } ?>
</select></td>
</tr><?php $count++;}?>
</table>
<input class="something" name="updatemod" type="submit" value="UPDATE" />
</form>
Next, before Select query, I have add an update query using this method below, so when I press the update button, update my DB:
// DATABASE UPDATE QUERY
if (isset($_POST['updatemod']) or isset($_GET['updatemod'])){
$db =& JFactory::getDBO();
$query = "UPDATE table
SET name = '".$_POST["name"]."',
SET lastname = '".$_POST["lastname"]."',
SET rank = '".$_POST["rank"]."'
";
$db->setQuery($query);
$db->query();}
But... Nothing is working!!! I have done exactly the same thing for an other form and it's working perfect! The only difference between those two forms, is that I am not using this while loop at the other form. So, maybe it has to do with this or something??? I don't know, at this point is where my knowledge confused, so I need your help!
I think you are trying to update all the rows in your table.
If that is the case,You need to do something like this.
<?php // DATABASE SELECT QUERY // also you should select your unique id field
$db =& JFactory::getDBO();
$query="SELECT name, lastname, rank,id
FROM table
ORDER BY rank ASC";
$db->setQuery($query);
$rows = $db->loadObjectList(); ?>
In your form you are placing element name as single but your requirement is to edit all the rows at one click you should use input names as array.Also here you have to introduce a new id field too for update condition
<form action="#" method="post" name="form">
<table><?php $count = 0; while ($count < 10){
$name = $rows[$count]->name;
$lastname = $rows[$count]->lastname;
$rank = $rows[$count]->rank;
$id = $rows[$count]->id; ?>
<tr>
<td><input name="uid[]" value="<?php echo $id?>" type="hidden" />
<input name="name[]" value="<?php echo $name ?>" type="text" /></td>
<td><input name="lastname[]" value="<?php echo $lastname ?>" type="text" /></td>
<td><select name="rank[]">
<option value="<?php echo $rank ?>"><?php echo $rank ?></option>
<option disabled="disabled" value="...">...</option>
<?php for ($i = 0; $i <= 100; $i++){ ?>
<option value="<?php echo $i ?>"><?php echo $i ?></option> <?php } ?>
</select></td>
</tr><?php $count++;}?>
</table>
<input class="something" name="updatemod" type="submit" value="UPDATE" />
</form>
Also in your Update Query also required loop and where cluase
// DATABASE UPDATE QUERY
if (isset($_POST['updatemod']) or isset($_GET['updatemod'])){
$db =& JFactory::getDBO();
$total_rows = sizeof($_POST["uid"]);
for($i =0; $i<$total_rows;$i++){
$query = "UPDATE table
SET name = '".$_POST["name"][$i]."',
lastname = '".$_POST["lastname"][$i]."',
rank = '".$_POST["rank"][$i]."'
WHERE id = '".$_POST["uid"][$i]."'
";
$db->setQuery($query);
$db->query();
}
}
I think this will solve your problem.
Here i just mentioned the "id" as your unique key of the table that may differ.But you will get the idea , i hopes
But this is a worst case update condition Bcoz you just imagine the table with 1000 rows.
It will take too long to get the result.
Try to update single row with proper method.It is the best method.
Hope this may help you.

Categories