I cannot update multiple columns, only one will update - php

I figured out how to update a table with multiple columns using checkboxes, except when more than one checkbox is selected the update will only happen for one of the columns not both. Could someone please help? Thank you!
Here is the working code for the table:
<table width="100%" border="0" cellspacing="1" cellpadding="0">
<tr>
<td><form name="frmactive" method="GET" action="assigncases1.php">
<table width="100%" border="0" cellpadding="3" cellspacing="1">
<tr>
<select name="assigned_to">
<option value=""></option>
<option value="Kristin Dodd"> Kristin Dodd </option>
<option value="Matt Ursetto"> Matt Ursetto </option>
<option value="Derek Bird"> Derek Bird </option>
<option value="John Castle"> John Castle </option>
<option value="Martin Delgado"> Martin Delgado </option>
</select>
<br>
<input type='submit' value = 'Assign'>
</tr>
<tr>
<td> </td>
<td colspan="4" align="center"><strong>Update multiple rows in mysql with checkbox<br>
</strong></td>
</tr><tr>
<td align="center" bgcolor="#FFFFFF"></td>
<td align="left"><strong>Name</strong></td>
<td align="left"><strong>SSO</strong></td>
<td align="left"><strong>case_status</strong></td>
<td align="left"><strong>Assigned To:</strong></td>
</tr>
<?php
$result=mysql_query($sql);
$count=mysql_num_rows($result);
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td align="center"><input name="checkbox" type="checkbox" id="checkbox[]" value="<?
echo $rows['id']; ?>"></td>
<td><? echo $rows['full_name']; ?></td>
<td><? echo $rows['sso']; ?></td>
<td><? echo $rows['case_status']; ?></td>
<td><? echo $rows['assigned_to']; ?></td>
</tr>
<?php
}
?>
<tr>
<td colspan="5" align="center"> </td>
</tr>
</table>
</form>
</td>
</tr>
</table>
And this is what I have for the php page that take the info.
// Retrieve data from database
$checkbox = $_GET['checkbox'];
$assigned_to = $_GET['assigned_to'];
// update data in mysql database
$sql="UPDATE rmstable2 SET assigned_to='$assigned_to' WHERE id='$checkbox'";
$result = mysql_query($sql);
$count = mysql_numrows($result);
{
mysql_query("UPDATE `rmstable2` SET `assigned_to` = '$assigned_to'
WHERE `id` = '$checkbox'")
or die(mysql_error());
}
//If they did not enter a search term we give them an error
if ($assigned_to == "")
{
echo "<h3>You forgot to enter a required field. Please try again.</h3><br>";
}
// if successfully updated.
else if($assigned_to !== "")
{
echo "<b>Update Successful</b><br>";
echo "<br>This case was assigned to:<b> $assigned_to</b><br>";
echo "<br>To see the change go back and click on <b>Refresh Page</b> if you assigned it
to someone other than you, the case will disappear and show up in their list of
assigned cases.";
}
else {
echo "ERROR";
}
?>

In your HTML, you're defining your checkboxes with the name checkbox - so only one value will be sent to PHP. To get an array of values, update the checkboxes to be created with name="checkbox[]" and when the form is submitted, you can use the selected values like an array.
In that case, you'll be able to loop through each item with:
$checkbox = $_GET['checkbox'];
$assigned_to = $_GET['assigned_to'];
foreach ($checkbox as $id) {
// do a very basic validation to see if the ID is numeric
if (!is_numeric($id)) continue;
$sql = 'UPDATE rmstable2 SET assigned_to="' . mysql_real_escape_string($assigned_to) . '" WHERE id=' . (int)$id;
mysql_query($sql);
}
Also, as always worth noting, the mysql_* functions are being deprecated and you should consider to start using either mysqli_* or PDO methods.

Related

MySQL table page not loading correct data

I'm creating a table that uses PHP to pull from a MySQL database that I have. I think I've got everything where I want it to be, however the only problem I'm having is that the results seem to be (for lack of a better word) "behind". What I mean by that is that my first page index.php is where I'm accepting user edits to the database. Once they click Update it sends them to my results.php file that is supposed to actually perform the SQL UPDATE and then display the updated table.
It updates the table just fine according to XAMPP's database editor. However, when I said "behind" I mean that the page loads, updates but doesn't display the updated data until either the user refreshes the page or returns to the first page THEN comes back. I'm not sure what could be causing it, so I'm hoping someone here can help me. I feel like the reason is something as simple as I'm just running the code in the wrong order, but I don't know for sure. My code is below:
index.php
<html>
<body>
<?php
include('dbconnect.php');
$query = "SELECT * FROM vw_events";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
?>
<form name="form1" method="post" action="results.php">
<table width="auto" border="1" cellspacing="1" cellpadding="5">
<tr>
<td align="center"><strong>Event ID</strong></td>
<td align="center"><strong>Title</strong></td>
<td align="center"><strong>Topic</strong></td>
<td align="center"><strong>Description</strong></td>
<td align="center"><strong>Event Date</strong></td>
<td align="center"><strong>Speaker</strong></td>
<td align="center"><strong>Building</strong></td>
<td align="center"><strong>Room</strong></td>
</tr>
<?php
while($rows=mysqli_fetch_array($result)) {
?>
<tr>
<input name="event_id[]" type="hidden" id="event_id" value="<?php echo $rows['event_id']; ?>">
<td align="center">
<?php echo $rows['event_id'];?>
</td>
<td align="center">
<input name="title[]" type="text" id="title">
</td>
<td align="center">
<?php echo $rows['topic_name']; ?>
</td>
<td align="center">
<?php echo $rows['topic_description']; ?>
</td>
<td align="center">
<input name="date[]" type="date" id="date">
</td>
<td align="center">
<input title="Use reference tables below to enter speaker ID" name="speaker[]" type="text" id="speaker">
</td>
<td align="center">
<input title="Use reference tables below to enter building ID" name="building[]" type="text" id="building">
</td>
<td align="center">
<input title="Use reference tables below to enter Room ID" name="room[]" type="text" id="room">
</td>
</tr>
<?php
}
?>
<tr>
<td colspan="8" align="center"><input type="submit" name="Update" value="UPDATE"></td>
</tr>
</table>
</form>
</body>
</html>
results.php
<html>
<body>
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
ini_set('display_errors',1);
require_once('dbconnect.php');
$query = "SELECT * FROM vw_events";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$id = $_POST['event_id'];
$title2 = $_POST['title'];
$date2 = $_POST['date'];
$speaker2 = $_POST['speaker'];
$building2 = $_POST['building'];
$room2 = $_POST['room'];
for($i=0;$i<$count;$i++) {
$sql="UPDATE events SET title='$title2[$i]', event_date='$date2[$i]', speaker='$speaker2[$i]', building='$building2[$i]', room='$room2[$i]' WHERE event_id='$id[$i]'";
$result1=mysqli_query($conn, $sql);
}
}
?>
<form name="form1" method="post" action="index.php">
<table width="auto" border="1" cellspacing="1" cellpadding="5">
<tr>
<td align="center"><strong>Event ID</strong></td>
<td align="center"><strong>Title</strong></td>
<td align="center"><strong>Topic</strong></td>
<td align="center"><strong>Description</strong></td>
<td align="center"><strong>Event Date</strong></td>
<td align="center"><strong>Speaker</strong></td>
<td align="center"><strong>Building</strong></td>
<td align="center"><strong>Room</strong></td>
</tr>
<?php
while($rows=mysqli_fetch_array($result)) {
?>
<tr>
<td align="center">
<?php echo $rows['event_id'];?>
</td>
<td align="center">
<?php echo $rows['title']; ?>
</td>
<td align="center">
<?php echo $rows['topic_name']; ?>
</td>
<td align="center">
<?php echo $rows['topic_description']; ?>
</td>
<td align="center">
<?php echo $rows['event_date']; ?>
</td>
<td align="center">
<?php echo $rows['speaker_name']; ?>
</td>
<td align="center">
<?php echo $rows['building_name']; ?>
</td>
<td align="center">
<?php echo $rows['room_name']; ?>
</td>
</tr>
<?php
}
?>
<tr>
<td colspan="8" align="center"><input type="submit" name="Return" value="Return"></td>
</tr>
</table>
</form>
</body>
</html>
Also if someone can give me some guidance as to how to run the htmlspecialchars function on my arrays within results.php I'd really appreciate it. I've already tried to create a for loop for literally each array but that didn't work. I've tried using ->
<?php
function htmlspecial_array(&$variable) {
foreach ($variable as &$value) {
if (!is_array($value)) { $value = htmlspecialchars($value); }
else { htmlspecial_array($value); }
}
}
but that also didn't work, and I've tried using the array_walk_recursive but to no avail. I want to try and do something like W3Schools' example here W3Schools Form Validation towards the bottom of the page where it says Validate Form Data With PHP and then gives an example.
The result you get from the UPDATE query is the number of affected rows in your database. To correctly display the updated data, you need to re-fetch from the database before you generate the HTML. You should rearrange your code in results.php like this:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
ini_set('display_errors',1);
require_once('dbconnect.php');
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$id = $_POST['event_id'];
$title2 = $_POST['title'];
$date2 = $_POST['date'];
$speaker2 = $_POST['speaker'];
$building2 = $_POST['building'];
$room2 = $_POST['room'];
$query = "SELECT * FROM vw_events";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
for($i=0;$i<$count;$i++) {
$sql="UPDATE events SET title='$title2[$i]', event_date='$date2[$i]', speaker='$speaker2[$i]', building='$building2[$i]', room='$room2[$i]' WHERE event_id='$id[$i]'";
$result1=mysqli_query($conn, $sql);
}
}
$query = "SELECT * FROM vw_events";
$result = mysqli_query($conn, $query);
Side note: If your data is sensitive, you may want to read about mysqli prepared statement so hackers cannot tamper with your queries.
Regarding your question about htmlspecialchars, see Stackoverflow "Execute htmlspecialchars on a multi level array".

How do I edit a specific row in SQL using PHP

I am fairly new to PHP and SQL.
I want to be able to assign a task to a certain user and the update that row in the database with the user's name assigned to that task.
Here is my code:
<table border="0" width="1100px" style= "font-size: 12px" >
<thead>
<tr valign="top" align="left">
<th height="20"></th>
<th height="20">Customer</th>
<th>Vehicle</th>
<th>Appt Time</th>
<th>Notes</th>
<th>Assign</th>
<th>Action</th>
<tr><td valign="top" colspan="6"><hr><br></td></tr>
</tr>
</thead>
<tbody>
<?php
while( $row = mysql_fetch_assoc( $result ) ){
echo
"<tr valign='center'>
<td width='50'><b>{$row['id']}</td>
<td width='220' height='70'><b>{$row['firstname']}
</td>
<td width='240'><b>{$row['car']}</b> <br>{$row['reg']}</td>
<td width='170'>Monday<br>24 September<br>17:00</td>
<td width='240'>{$row['notes']}<br><b>Status:</td>
<td width='240'>
<form action='bookings.php' method='post'>
<select style='width:90px' class='reg' name='assign'required>
<option value=''></option>
<option value='User1'>User1</option>
<option value='User2'>User2</option>
<option value='User3'>User3</option>
<option value='User4'>User4</option>
<option value='User5'>User5</option>
</select><input type='submit' value='>' class='assignButton'/></form>
</td><td>
<button class='myButton'>Edit</button>
</td>
<tr><td colspan='6'><hr class='hrTitle'></td></tr>
</tr>\n";
}
?>
</tbody>
</table>
As you can see, I have a number of users that can be selected, I want to be able to assign that task to a user from the select list.
Any help is much appreciated.
Try the following steps.
Give a name to your submit button.
<input type='submit' value='>' name='submit' class='assignButton'>
Add a hidden input field to your form. Give it the value of the id of the current row. Give it a name. I chose id.
This is very important so you can know which customer to edit. Please double check the value that you will set. From your code, I see it is $row['id'].
<input type="hidden" name="id" value='$row["id"]''>
In your PHP file bookings.php (assuming you have a connection to your database), process the submitted form.
if(isset($_POST["submit"])){ //checks if the form was submitted
$id = $_POST["id"]; //id of the customer
$assign = $_POST["assign"]; //your selected value
$query = "UPDATE table SET columnToModify = '$assign' WHERE id = '$id'";
$result = $connection->query($query); //run the query
}
Hope it helps.

passing variables from dynamic table

Good morning,
I was searching, but couldn't find answer :(
I have a table created dynamically with data taken from MSSQL:
$tabelka = '
<form action="index.php" method="post">
<table border =1 width=40% class="hoverTable"><tr>
<td width=10%><B>Biuro</B></td>
<td width=10%><b>Drukarka</b></td>
<td width=20%><b>Toner</b></td>
<td width=10%><b>Na stanie</b></td>
<td width=10%><b>Zamówionych</b></td>
<td width=10%><b>Akcja</b></td></tr>';
$sql = 'select * from raportTonerow';
if ($result = sqlsrv_query($conn, $sql)) {
while ($row = sqlsrv_fetch_array($result)) {
$tabelka .= '
<tr><td width=10%>'.$row['kodBiura'].'</td>
<td width=10%>'.$row['nazwaDrukarki'].'</td>
<td width=20%>'.$row['toner'].'</td>
<td width=10%>
<input type="number" name="naStanie" size=10% maxlength=1 value="'.$row['naStanie'].'"></td>
<td width=10%><input type="number" name="zamowionych" size=10% maxlength=1 value="'.$row['zamowionych'].'"></td>
<td width=10%><input type="submit" value="Aktualizuj" name="akt"></td>';
}
}
$tabelka .= '</form></table>';
and
if (isset($_POST['akt'])) {
echo "test ".$_POST['zamowionych'];
}
it is showing me only last data from table. How can I pass variables from each row?
What I want to have is: when user click on button on the row only data from that row will be send in form.
thank you
Lukasz
<?php
while($row=mysql_fetch_array($sql))
{
?>
<td> <?php echo $row->kodBiura;?></td>
<td> <?php echo $row->nazwaDrukarki; ?></td>
<td> <?php echo $row->toner; ?></td>
<?php }?>

increment variable on submit to update mysql query

I am new to PHP(loving it already)
I have a form that looks up a table that sends 'golf hole' info back and allows a golfer to input their score of the hole. Problem I have is that I can present the first hole by looking up the hole_detail table but then cant figure out how loop through the table for hole 2, 3.....18 when the form is submitted. I have searched stackoverflow but cant find anything that specific about it. I have tried an if statement, if (isset($_POST['Submit'])) to try increment the $hole_id. Am I completely going about it the wrong way? Thanks in advance.
<?php
include ('../scripts/dbconfig.php');
# get the most recent course name:
$get_course_name = mysql_query("SELECT course_name FROM comp ORDER BY PID DESC LIMIT 1");
$show_course_name = mysql_fetch_array($get_course_name);
if (isset($_POST['Submit'])) {
$hole_id =1;
else {
$hole_id = $hole_id + 1;
}
}
# get the hole yardage and SI from most recent selected golf course:
$get_course_detail = mysql_query("SELECT * FROM `course_detail` WHERE course_name = '". $show_course_name['course_name'] . "'");
$show_course_detail = mysql_fetch_array($get_course_detail);
$get_hole_detail = mysql_query("SELECT * FROM `course_detail`,`phoenix_hole` WHERE Course_ID = 6 AND hole_id = $hole_id");
$show_hole_detail = mysql_fetch_array($get_hole_detail);
?>
</head>
<body>
<table width="300" cellspacing="0" cellpadding="0">
<tr>
<td width="40"><?php echo $show_course_name['course_name'];?></td>
</tr>
<tr>
<td width="20">HOLE <?php echo $show_hole_detail['hole_id']?></td>
<td width="5"> PAR <?php echo $show_hole_detail['hole_par'];?></td>
</tr>
<tr>
<td width="20">Yards</td>
<td width="20">S.I</td>
</tr>
<tr>
<td bgcolor="yellow"><?php echo $show_hole_detail['yellow_yards'];?></td>
<td><?php echo $show_hole_detail['hole_si'];?></td>
</tr>
<tr>
<td border="1px" bgcolor="white"><?php echo $show_hole_detail['white_yards'];?></td>
<td><?php echo $show_hole_detail['hole_si'];?></td>
</tr>
<tr>
<td bgcolor="red"><?php echo $show_hole_detail['red_yards'];?></td>
<td><?php echo $show_hole_detail['hole_si'];?></td>
</tr>
</table>
</p>
<form id="game_form" name="game_form" method="post" action="game_form.php">
<table width="300" border="0" align="left" cellpadding="2" cellspacing="0">
<tr>
<td><b>Hole Shots</b></td>
<td><input name="hole_shots" type="text" class="textfield" id="hole_shots" maxlength="2" size="3" ></td>
<td><b>Putts</b></td>
<td><input name="putts" type="text" class="textfield" id="putts" maxlength="2" size="3"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Next Hole" align="center" /></td>
</tr>
</table>
</form>
</body>
</html>
Or you can use a hidden field that keeps the hole number and you can increment it from php.
$hole_id, in this scenario, will always be 1, because when a user clicks the Submit button, $_POST['Submit'] will always have a value. What you should do instead is have $_POST['Submit'] contain the value of $hole + 1. PHP is not going to "remember" what $hole_id was last time around; it's up to you to remind it. As soon as a request is sent to the browser--unless you're using sessions--PHP forgets everything about that request (HTTP is "stateless").
<?php
if (isset($_POST['Submit'])) {
$hole_id = (int)$_POST['Submit'];
} else {
$hole_id = 1;
}
# other code here
?>
You are on hole #<?php echo $hole_id; ?>.
<form>
<!-- form stuff here -->
<button type="submit" name="Submit" value="<?php echo $hole_id + 1; ?>">Next hole</button>
</form>

display the content of table in checkbox form

I have a table called "project_name" in my database called "encrypt_decrypt". The table contains only 1 column called "name" which contains different values of name (ex : p1, p2, p3...). I have to retrieve this values(p1,p2,p3..) from my database and display it on a registration form with each value displaying one below the other having a checkbox with it so that user can select any of the name while registering! How do i do this in php ???
Thanks in advance!
<html>
<body>
<form name="reg" action="code_exec2.php" onsubmit="return validateForm()" method="post">
<table width="274" border="0" align="center" cellpadding="2" cellspacing="0">
<tr>
<td><div align="right" style="white-space:nowrap" >Please select the project:</td>
</tr>
<tr>
<td><div align="right"><input type="checkbox" name="project[]" ></div></td>
<td><?php
session_start();
include('connection2.php');
$row=mysql_query("select * from project_name");
$array= array();
$output = mysql_fetch_assoc($row);
while($output){
$array[] = $output;
}
print_r($array);
?></td>
</tr>
<tr>
<td><div align="right"><input type="checkbox" name="Select all"
value="select all" onclick="toggle(this)"></div></td>
<td>Select all</td>
</tr>
<tr>
<td><div align="right"></div></td>
<td><input name="submit" type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
Try this.
$result=mysql_query("select * from project_name");
$checkboxes=array();
while($r=mysql_fetch_assoc($result)){
$checkboxes[]='<input type="checkbox" name="names[]" value="'.$r['name'].'">'.$r['name'].'<br />';
}
Then echo below wherever you want the checkboxes to appear.
echo implode("\n",$checkboxes);
Assuming, that your connection to db is correct, you need to change the way you display results:
<?php
session_start();
include('connection2.php');
$row=mysql_query("select * from project_name");
$array= array();
while($output = mysql_fetch_assoc($row)){
//now you have row with name, and you need to display each name with new tr:
?>
<tr>
<td><div align="right"><input type="checkbox" name="project[]" value="<?php echo $output['name'] ?>"></div></td>
<td><?php echo $output['name'] ?></td>
</tr>
<?php } // closing while loop
?>
Note that I added value to checkbox - if you want to do something with checked project, you have to know which one it was.
And remember taht mysql_ functions are depreated! You should use PDO or mysqli_ instead
i tried this and i got: any ways thanks for all your help :)
<?php
include('connection.php');
$r=mysql_query("select distinct name from project_name");
$ProdArray=array();
while ($row = mysql_fetch_object($r)) {
array_push($ProdArray,$row->name);
}
foreach($ProdArray as $p) {
echo "<tr>";
echo "<td><div align='right'>";
echo "<input type='checkbox' name='project[]' value=" .$p. " />";
echo "</div></td>";
echo "<td>$p</td>";
echo "</tr>";
}
?>

Categories