PHP - How to update multiple row using foreach? - php

so i'm making a php file that updates multiple rows to mysql but I'm having a problem whenever i submit,and I have no idea if I'm using foreach well. here is my code:
$query = "SELECT id, departments, deptName, headOfOffice FROM aip";
$result = mysqli_query($db,$query);
$count = mysqli_num_rows($result);
while ($row = mysqli_fetch_assoc($result)) {
echo '<tr>';
echo '<td><input type="text" name="id[]" value="'.$row['id'].'" readonly></td>';
echo '<td><input type="text" id ="department_code" name="department_code[]" value="'.$row['departments'].'"></td>';
echo '<td><input type="text" id="department_name" name="department_name[]" value="'.$row['deptName'].'"></td>';
echo '<td><input type="text" id="department_head" name="department_head[]" value="'.$row['headOfOffice'].'"></td>';
echo '</tr>';
}
echo '<tr>';
echo '<td></td>';
echo '<td></td>';
echo '<td><input type="submit" name="update" value="Update">';
echo '</tr>';
if($_SERVER["REQUEST_METHOD"] == "POST"){
$deptid = $_POST['id'];
$code = $_POST['department_code'];
$dname = $_POST['department_name'];
$dhead =$_POST['department_head'];
foreach($_POST['id'] as $count){ \\ i don't know if this is right.
$query2 = "UPDATE aip SET deparments = '".$code[$count].'" WHERE id = "'.$deptid[$count]."'";
$result2 = mysqli_query($db,$query2);
}
}
the error says "Undefined offset: 2"
I'm a newbie here, and this is my first time using arrays. hope someone could help. please!

foreach($_POST['id'] as $count => $id){
$query2 = "UPDATE aip SET deparments = '".$code[$count]."' WHERE id = '".$deptid[$count]."'";
$result2 = mysqli_query($db,$query2);
}
P.S. your code is vulnerable to SQL injection

There are two ways of using foreach:
foreach($array as $key => $value){
...
}
or
foreach($array as $value){
...
}
The foreach loop will then iterate through all elements in array, executing the code in brackets for each element once, holding the key name and the value of the element in $key and $value respectively (you can use other than $value and $key as well).
I don't fully understand what exactly you are doing in your code, so if you add an explanation, I will be able to solve your particular case;

i have changed in your script..pls used my script. you do not need to changes any thing just copy and paste my script.
if($_SERVER["REQUEST_METHOD"] == "POST"){
$data = $_POST;
if(count($data['id'])>0){
foreach($data as $key=>$item){
$query2 = "UPDATE aip SET deparments = '".$item['department_code'][$key]."', deptName = '".$item['department_name'][$key]."',headOfOffice = '".$item['department_head'][$key]."' WHERE id = '".$item['id'][$key]."'";
$result2 = mysqli_query($db,$query2);
}
}
}

Related

problems with my submit

I'm using multiple forms to select what to update. only my last form disappears after submitting. I don't think it even processes the update it should do on submit.
please help me!
php code:
if ($collect == "foto"){
$sql = mysqli_query($link, "SELECT * FROM foto");
$row = mysqli_fetch_assoc($sql);
$array = array();
echo "<form method='POST'>";
while ($row = mysqli_fetch_assoc($sql))
{
echo "<input type='text' name='foto[]' value=".htmlspecialchars($row['foto'])."></input>";
}
echo "<input type='submit' name='submit3' value='update'></input></form>";
if (isset($_POST['submit3'])) {
echo "Finally!";
$array = $_POST['foto'];
$i = 0;
foreach ($array as $foto) {
$ufoto = $array[$i];
$sql ="
UPDATE
foto
SET
foto = '$ufoto'
WHERE
id = $i
";
mysqli_query($link, $sql);
$i ++;
var_dump($array);
}
}
}
$_POST['foto'] = $array['foto'];
should most likely be:
$array = $_POST['foto'];
your script is also open to SQL injection attacks.
Before the edit I saw you neglected to put an action-attribute in your form-tag. This action attribute specifies which php-site should process the form.
See more here: http://www.w3schools.com/tags/att_form_action.asp

Sum Values From Different Columns

I am having problem adding up the values in a column with php.
These values where sent from checkboxes and i want to count only the values that where checked from the unit column.
Here is my code:
<?php
$id = $_POST['course'];
foreach($id as $value)
{
//echo $value;
$query = " SELECT * FROM french WHERE id= $value ";
$result = mysql_query($query) or die('Error, query failed');
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$course = htmlspecialchars($row['course_name']);
$code = htmlspecialchars($row['course_code']);
$unit = $row['unit'];
$status = $row['status'];
?>
Are you trying like this? Getting form array of form checkboxs and checking on database via ID's?
HTML FORM
Check 1 <input type="checkbox" name="val[]" />
Check 2 <input type="checkbox" name="val[]" />
PHP RESULT
$val = $_POST['val'];
$count = count($val);
foreach ($val as $val_res)
{
$query = 'SELECT * FROM french WHERE id='.$val_res;
}

Updating multiple SQL records using a single submit button

Scenario: I have multiple text boxes in which a user will enter data into some of them / all of them / or none of them.
Goal: I need to be able to UPDATE multiple records based on what is in the text boxes where the users has entered their data.
Problem: The update statement is not working when I try to update each record for each text box.
Below is the code:
$conn = mysql_connect ($localhost, $user, $pass);
mysql_select_db($db_name, $conn) or die (mysql_error());
$myFile = "/var/www/html/JG/LSP/lsp_ref.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 5);
fclose($fh);
if (isset($_POST['submit'])) {
foreach ($_POST['notes'] as $key=>$value) {
echo $_POST['notes'][$key];
#echo "<br/>";
//echo "$key";
//echo "<br/>";
$query_update = "UPDATE lsp_active SET Notes = ".$_POST['notes'][$key];
$result_update = mysql_query($query_update);
}
#header ('Location:lsp_display.php');
}
$query = "SELECT * FROM lsp_active";
$result = mysql_query($query);
$field_num = mysql_num_fields($result);
echo "<form method='post' action='lsp_display.php'>";
echo "<table border=1>";
$cols = 0;
while ($row = mysql_fetch_assoc($result)) {
if ( $cols == 0) {
$cols = 1;
echo "<tr>";
foreach ($row as $col => $value) {
print "<th>$col</th>";
}
print "<th>Insert Ticket / Notes</th>";
echo "</tr>";
}
echo "<tr>";
foreach ($row as $cell) {
echo "<td>$cell</td>";
}
echo "<td><input type='text' name='notes[]'/></td>";
echo "</tr>\n";
}
echo "<tr><td colspan=8><input type='submit' name='submit' value='Update'/></td></tr>";
echo "</form>";
mysql_free_result($result);
?>
Now when I print out $_POST['notes'][$key] it spits back out what I give it in the text boxes.
However, the update statement that I have for my SQL isn't updating the database with what I put in.
I am not sure what could be wrong with it :(.
Any help is appreciated!
Thank you!
It looks like you probably need to surround your $_POST in single quotes.
Also use a function to clean the $_POST variable.
For example:
function escape($data) {
$magicQuotes = get_magic_quotes_gpc();
if(function_exists('mysql_real_escape_string')) {
if($magicQuotes) {
$data = stripslashes($data);
}
$data = mysql_real_escape_string($data);
}
else {
if(!$magicQuotes) {
$data = addslashes($data);
}
}
return $data;
}
And then your query:
$query_update = "UPDATE lsp_active SET Notes = '" . escape($_POST['notes'][$key]) . "'";
Edit:
You also might want to put a WHERE statement on the end of your UPDATE query, so that you don't update everything in the table.
"UPDATE lsp_active a SET a.Notes = '" . mysql_real_escape_string($_POST['notes'][$key]) ."' WHERE a.Index = '" . ($key + 1). "'"
Index is a keyword thar refers to indexes, not your column. So I defined an alias, and made it explicit that Im referring to the column. Also, the + 1 on the Where $key since Index is not zero-based like PHP arrays.

PHP Foreach loop problem with mySQL INSERT INTO

I am having a big issue.
This is the first time I sue a foreach and I do not even know if it's the right thing to use.
I have a textarea where my members can add some text.
They also have all the accounts where to send the posted text.
Accounts are of two types F and T.
They are shown as checkboxes.
So when a member types "submit" the text should be INSERTED in a specific table for EACH of the selected accounts. I thought php foreach was the right thing. But I am not sure anymore.
Please take in mind I do not know anything about foreach and arrays. So please when helping me, consider to provide the modded code =D . Thank you so much!
<?php
require_once('dbconnection.php');
$MembID = (int)$_COOKIE['Loggedin'];
?>
<form action="" method="post">
<p align="center"><textarea id="countable1" name="addit" cols="48" rows="10" style="border-color: #ccc; border-style: solid;"></textarea>
<br>
<?
$DB = new DBConfig();
$DB -> config();
$DB -> conn();
$on="on";
$queryF ="SELECT * FROM `TableF` WHERE `Active`='$on' AND `memberID`='$MembID' ORDER BY ID ASC";
$result=mysql_query($queryF) or die("Errore select from TableF: ".mysql_error());
$count = mysql_num_rows($result);
if ($count > 0)
{
while($row = mysql_fetch_array($result)) {
?><div style="width:400px; height:100px;margin-bottom:50px;"><?
$rowid = $row['ID'];
echo $row['Name'] . '</br>';
$checkit = "checked";
if ($row['Main'] == "")
$checkit = "";
if ($row['Locale'] =="")
$row['Locale'] ="None" . '</br>';
echo $row['Locale'] . '</br>';
if ($row['Link'] =="")
$row['Link'] ="javaScript:void(0);";
?>
<!-- HERE WE HAVE THE "F" CHECKBOXES. $rowid SHOULD BE TAKEN AND INSERTED IN THE FOREACH BELOW FOR ANY SELECTED CHECKBOX IN THE FIELD "Type".SEE BELOW -->
<input type="checkbox" name="f[<?php echo $rowid?>]" <?php echo $checkit;?>>
</div>
<?
}//END WHILE MYSQL
}else{
echo "you do not have any Active account";
}
$DB = new DBConfig();
$DB -> config();
$DB -> conn();
$queryTW ="SELECT * FROM `TableT` WHERE `Active`='$on' AND `memberID`='$MembID' ORDER BY ID ASC";
$result=mysql_query($queryTW) or die("Errore select TableT: ".mysql_error());
$count = mysql_num_rows($result);
if ($count > 0)
{
while($row = mysql_fetch_array($result)) {
?><div style="width:400px; height:100px;margin-bottom:50px;"><?
$rowid = $row['ID'];
echo $row['Name'] . '</br>';
$checkit = "checked";
if ($row['Main'] == "")
$checkit = "";
if ($row['Locale'] =="")
$row['Locale'] ="None" . '</br>';
echo $row['Locale'] . '</br>';
if ($row['Link'] =="")
$row['Link'] ="javaScript:void(0);";
?>
<!-- HERE WE HAVE THE "T" CHECKBOXES. $rowid SHOULD BE TAKEN AND INSERTED IN THE FOREACH BELOW FOR ANY SELECTED CHECKBOX IN THE FIELD "Type".SEE BELOW -->
<input type="checkbox" name="t[<?php echo $rowid?>]" <?php echo $checkit;?> >
</div>
<?
}//END 2° WHILE MYSQL
}else{
echo "you do not have any Active account";
}
?>
<input type="submit" value="submit">
</form>
<?
//WHEN CHECKBOXES "F" ARE FOUND, FOR EACH CHECKBOX IT SHOULD INSERT INTO TableG THE VALUES BELOW, FOR EACH SELECTED "F" CHECKBOX
if(!empty($_POST['addit']) && !empty($_POST['f'])){
$thispostF = $_POST['f'];
$f="F";
foreach ($thispostF as $valF)
//THE MOST IMPORTANT FIELD HERE IS "Type". THE ARRAY INSERT "on", I NEED INSTEAD THE VALUE $rowid AS ABOVE
$queryaddF="INSERT INTO TableG (ID,memberID,Type,IDAccount,Tuitting) VALUES (NULL,".$MembID.",'".$f."','".$valF."', '".$_POST['addit']."')";
$resultaddF=mysql_query($queryaddF) or die("Errore insert G: ".mysql_error());
}
//WHEN CHECKBOXES "T" ARE FOUND, FOR EACH CHECKBOX IT SHOULD INSERT INTO TableG THE VALUES BELOW, FOR EACH SELECTED "T" CHECKBOX
if(!empty($_POST['addit']) && !empty($_POST['t'])){
$thispostT = $_POST['t'];
$t="T";
foreach ($thispostT as $valF)
//THE MOST IMPORTANT VALUE HERE IS "Type". THE ARRAY GIVES "on", I NEED INSTEAD THE VALUE $rowid AS ABOVE
$queryaddT="INSERT INTO TableG (ID,memberID,Type,IDAccount,Tuitting) VALUES (NULL,".$MembID.",'".$t."','".$valF."', '".$_POST['addit']."')";
$resultaddF=mysql_query($queryaddF) or die("Errore insert G: ".mysql_error());
}
?>
foreach ($thispostT as $valF)
{
$queryaddT="INSERT INTO TableG (ID,memberID,Type,IDAccount,Tuitting) VALUES (NULL,".$MembID.",'".$t."','".$valF."', '".$_POST['addit']."')";
$resultaddF=mysql_query($queryaddF) or die("Errore insert G: ".mysql_error());
}
please put start and ending bracket to your foreach loop and try i have not read the whole code but just found you missing the brackets. hope that helps you.
I think I know what you're doing...
You're going to need to do:
foreach($_POST as $key => $value) {
$type = substr($key,0,1);
$id = substr($key,1);
if($type == 't') {
// do insert for t table here
} else if($type == 'f') {
// do insert for f table here
}
}
I didn't test it but it should be something like this.
My suggestion is
create field name as t[] (array)
onchecked value will be passed on the next page
the form checkbox field should be like that
<input type="checkbox" name="t[]" value="< ?php echo $rowid?>" <?php echo $checkit;? > >
and when you Submit the form
GET THE VALUE and insert in to database;
< ?
if($_POST['t'])
{
foreach($_POST['t'] as $v)
{
queryaddT="INSERT INTO TableG (ID,memberID,Type,IDAccount,Tuitting) VALUES (NULL,".$MembID.",'".$t."','".$valF."', '".$_POST['addit']."')";
$resultaddF=mysql_query($queryaddF) or die("Errore insert G: ".mysql_error());
}
}
? >

How to echo out table rows from the db (php)

i want to echo out everything from a particular query. If echo $res I only get one of the strings. If I change the 2nd mysql_result argument I can get the 2nd, 2rd etc but what I want is all of them, echoed out one after the other. How can I turn a mysql result into something I can use?
I tried:
$query="SELECT * FROM MY_TABLE";
$results = mysql_query($query);
$res = mysql_result($results, 0);
while ($res->fetchInto($row)) {
echo "<form id=\"$row[0]\" name=\"$row[0]\" method=post action=\"\"><td style=\"border-bottom:1px solid black\">$row[0]</td><td style=\"border-bottom:1px solid black\"><input type=hidden name=\"remove\" value=\"$row[0]\"><input type=submit value=Remove></td><tr></form>\n";
}
$sql = "SELECT * FROM MY_TABLE";
$result = mysqli_query($conn, $sql); // First parameter is just return of "mysqli_connect()" function
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result)) { // Important line !!! Check summary get row on array ..
echo "<tr>";
foreach ($row as $field => $value) { // I you want you can right this line like this: foreach($row as $value) {
echo "<td>" . $value . "</td>"; // I just did not use "htmlspecialchars()" function.
}
echo "</tr>";
}
echo "</table>";
Expanding on the accepted answer:
function mysql_query_or_die($query) {
$result = mysql_query($query);
if ($result)
return $result;
else {
$err = mysql_error();
die("<br>{$query}<br>*** {$err} ***<br>");
}
}
...
$query = "SELECT * FROM my_table";
$result = mysql_query_or_die($query);
echo("<table>");
$first_row = true;
while ($row = mysql_fetch_assoc($result)) {
if ($first_row) {
$first_row = false;
// Output header row from keys.
echo '<tr>';
foreach($row as $key => $field) {
echo '<th>' . htmlspecialchars($key) . '</th>';
}
echo '</tr>';
}
echo '<tr>';
foreach($row as $key => $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
}
echo("</table>");
Benefits:
Using mysql_fetch_assoc (instead of mysql_fetch_array with no 2nd parameter to specify type), we avoid getting each field twice, once for a numeric index (0, 1, 2, ..), and a second time for the associative key.
Shows field names as a header row of table.
Shows how to get both column name ($key) and value ($field) for each field, as iterate over the fields of a row.
Wrapped in <table> so displays properly.
(OPTIONAL) dies with display of query string and mysql_error, if query fails.
Example Output:
Id Name
777 Aardvark
50 Lion
9999 Zebra
$result= mysql_query("SELECT * FROM MY_TABLE");
while($row = mysql_fetch_array($result)){
echo $row['whatEverColumnName'];
}
$sql = "SELECT * FROM YOUR_TABLE_NAME";
$result = mysqli_query($conn, $sql); // First parameter is just return of "mysqli_connect()" function
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result)) { // Important line !!!
echo "<tr>";
foreach ($row as $field => $value) { // If you want you can right this line like this: foreach($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
In PHP 7.x You should use mysqli functions and most important one in while loop condition use "mysqli_fetch_assoc()" function not "mysqli_fetch_array()" one. If you would use "mysqli_fetch_array()", you will see your results are duplicated. Just try these two and see the difference.
Nested loop to display all rows & columns of resulting table:
$rows = mysql_num_rows($result);
$cols = mysql_num_fields($result);
for( $i = 0; $i<$rows; $i++ ) {
for( $j = 0; $j<$cols; $j++ ) {
echo mysql_result($result, $i, $j)."<br>";
}
}
Can be made more complex with data decryption/decoding, error checking & html formatting before display.
Tested in MS Edge & G Chrome, PHP 5.6
All of the snippets on this page can be dramatically reduced in size.
The mysqli result set object can be immediately fed to a foreach() (because it is "iterable") which eliminates the need to maked iterated _fetch() calls.
Imploding each row will allow your code to correctly print all columnar data in the result set without modifying the code.
$sql = "SELECT * FROM MY_TABLE";
echo '<table>';
foreach (mysqli_query($conn, $sql) as $row) {
echo '<tr><td>' . implode('</td><td>', $row) . '</td></tr>';
}
echo '</table>';
If you want to encode html entities, you can map each row:
implode('</td><td>' . array_map('htmlspecialchars', $row))
If you don't want to use implode, you can simply access all row data using associative array syntax. ($row['id'])

Categories