multiple update array query gone wrong :( - php

hey guys im having trouble with an array. all i need is for the query to update 2 columns on the table based on the records id
The table has a column called OffID and it looks for any record that has not yet been authorised. to mark it authorised the user will select a check box for either authorise or deny and then press the submit button. however at the moment i have 9 records which show in the table each with there own unique id but when submit is selected it will only update one. any help in showing where ive gone wrong would be grateful and cheers in advance :)
ok i edited the code but it is only now setting the first record. so if there are 8 records and i choose accept for the first record and deny for the second record both the accept and deny are set to the first record in the database my new code is below
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/Apollo/dbc.php";
include_once($path);
$rs_results = mysql_query("SELECT * FROM off WHERE IsItAuthorised='0' and isitsick='0' ORDER BY DayOff");
?>
<html>
<head>
<title>Administration Main Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php
if (isset($_POST['submit'])) {
//Assign each array to a variable
$id = $_POST['id'];
$approve = $_POST['approve'];
$deny = $_POST['deny'];
$limit = count($rs_results);
$values = array(); // initialize an empty array to hold the values
for($k=0;$k<$limit;$k++){
$msg[] = "$limit New KPI's Added";
$query = "UPDATE off SET Authorised = '$approve[$k]', Deny = '$deny[$k]' WHERE OffID = '$id[$k]'";
}
$Event = "INSERT INTO events (UserName, Event ) VALUES ('$_SESSION[user_name]', 'Entered New KPI' )";
echo $query;
if (!mysql_query($query,$link)){
die('Error: ' . mysql_error());
} else {
mysql_query($Event);
echo "<div class=\"msg\">" . $msg[0] . "</div>";
}
}
?>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="14%" valign="top"><?php
?>
</td>
<td width="74%" valign="top" style="padding: 10px;">
<p><?php
if(!empty($msg)) {
echo $msg[0];
}
?></p>
<p>
<?php
$cond = '';
$sql = "select * from off ";
$rs_total = mysql_query($sql) or die(mysql_error());
$total = mysql_num_rows($rs_total);
?>
<p>
<form name "searchform" action="/Apollo/Admin/HolidayRequests.php" method="post">
<table width="100%" border="0" align="center" cellpadding="2" cellspacing="0">
<tr class="mytables">
<td width="4%"><font color="white"><strong>ID</font></strong></td>
<td width="4%"> <font color="white"><strong>Staff Member</font></strong></td>
<td width="10%"><font color="white"><strong>Day Off</font></strong></div></td>
<td width="10%"><font color="white"><strong>Is It Authorized</font></strong></div></td>
<td width="15%"> </td>
</tr>
<tr>
<td> </td>
<td width="10%"> </td>
<td width="17%"><div align="center"></div></td>
<td> </td>
</tr>
<?php while ($rrows = mysql_fetch_array($rs_results)) {?>
<tr>
<td><input name="id[]" id="id[]" size="4" value="<?php echo $rrows['OffID'];?>" /></td>
<td><?php echo $rrows['StaffMember']; ?></td>
<td><?php echo date('d/m/Y', strtotime($rrows['DayOff']));?></div></td>
<td> <span id="approve<?php echo $rrows['id']; ?>">
<?php if(!$rrows['IsItAuthorised']) { echo "Pending"; } else {echo "Authorized"; }?>
</span> </td>
<td>
<input type="checkbox" name="approve[]" id="approve[]" value="1"> Approve
<input type="checkbox" name="deny[]" id="deny[]" value="1"> Deny
</td>
</tr>
<?php } ?>
</table>
<input name="submit" type="submit" id="submit" value="Submit">
</form>
</p>
<?php
?>
<p> </p>
<p> </p>
<p> </p>
<p> </p></td>
<td width="12%"> </td>
</tr>
</table>
</body>
</html>

isn't it because your $id etc isn't passes an array:
$id = $_POST['id'];
$approve = $_POST['approve'];
$deny = $_POST['deny'];

You're using $_POST['id'] but nowhere in your <form/> do I see any <input name="id[]"/> which could provide the data

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".

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>

Unlocked Forum Post saying it's locked?

All right, sorry for so many posts. Anyway, I have created an entire file of code; view_topic.php, that is just showing a forum post. I know it is messy and not in mysqli, I will be rewriting the ENTIRE code, once I finish this page. Anyway, on to the problem. When you visit any topic, locked or unclicked, it will ALWAYS say, "Sorry, this post is locked." There are no error messages. I have spent all day trying to find the error in my code, and I have turned to the internet for guidance. Here is the whole code, tell me if you need anything else:
<?php
require_once 'core/init.php';
// get value of id that sent from address bar
$id=$_GET['id'];
$sql="SELECT * FROM `forum_question` WHERE id='$id'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
if (!$result) { // add this check.
die('Invalid query: ' . mysql_error());
}
$thisql = "SELECT `locked` FROM `forum_question` WHERE `id`='$id'";
$mythisql = mysql_query($thisql);
$mythisql1 = mysql_fetch_array($mythisql);
if ($mythisql1 === false) { // add this check.
die('Invalid query: ' . mysql_error());
}
?>
<table width="700" align="center" class="outer">
<tr>
<td><table width="100%">
<tr>
<td class="back">Back to Forum Home?</td>
</tr>
<tr>
<td><center><h3>
<?php
echo $rows['topic'];
?>
</h3></center></td>
</tr>
<tr>
<td align="right"><?php
if ($user_data['username'] === $rows['name']) {
?>
<form action="lock.php" method="post">
Lock? <input type="checkbox" name="lock" value="1" />
<input type="hidden" name="id" value="<?php echo $rows['id']; ?>" />
<input type="submit" value="Submit">
</form>
<?php
} ?>
</td>
</tr>
<tr>
<td><?php echo $rows['detail']; ?></td>
</tr>
<tr>
<td class="forumreply">By <?php echo $rows['name']; ?>, On <?php echo $rows['datetime']; ?>
</tr>
</table></td>
</tr>
</table>
<BR>
<?php
$tbl_name2="forum_answer"; // Switch to table "forum_answer"
$sql2="SELECT * FROM $tbl_name2 WHERE question_id='$id'";
$result2=mysql_query($sql2);
while($rows=mysql_fetch_array($result2)){
?>
<table width="700" align="center" class="outer">
<tr>
<td><table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr><tr>
<td><?php echo $rows['a_answer']; ?></td>
</tr>
<td class="forumreply">By <?php echo $rows['a_name']; ?>, On <?php echo $rows['a_datetime']; ?></td>
</tr>
</table></td>
</tr>
</table><br>
<?php
}
$sql3="SELECT view FROM `forum_question` WHERE id='$id'";
$result3=mysql_query($sql3);
$rows=mysql_fetch_array($result3);
$view=$rows['view'];
// if have no counter value set counter = 1
if(empty($view)){
$view=1;
$sql4="INSERT INTO `forum_question`(view) VALUES('$view') WHERE id='$id'";
$result4=mysql_query($sql4);
}
// count more value
$addview=$view+1;
$sql5="update `forum_question` set view='$addview' WHERE id='$id'";
$result5=mysql_query($sql5);
?>
<?php
if (logged_in() === true) {
if ($mythisql1['locked']===0) {
?>
<BR>
<table width="400" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form1" method="post" action="add_answer.php">
<input type="hidden" value="<?php echo $user_data['username']; ?>" name="a_name">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td valign="top"><strong>Reply</strong></td>
<td valign="top">:</td>
<td><textarea name="a_answer" cols="45" rows="3" id="a_answer"></textarea></td>
</tr>
<tr>
<td> </td>
<td><input name="id" type="hidden" value="<?php echo $id; ?>"></td>
<td><input type="submit" name="submit" value="Submit"> <input type="reset" name="Submit2" value="Reset"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
<?php
} else {
echo "Sorry, this post is locked.";
}
}
ob_end_flush();
?>
If anyone can figure out my problem, I will be eternally grateful. Thanks.
I can not see you data so it's a guess
use onyl ==0 not ===0
if (logged_in() === true) {
if ($mythisql1['locked']==0) {
?>
or if $mythisql1['locked'] is a string
if (logged_in() === true) {
if ($mythisql1['locked']=='0') {
?>
This code has multiple problems. SQL Injection is one. This is a bad case alone. Also, when updating the views counter: do it properly in SQL! update forum_question set view=view+1 WHERE id='".mysql_real_escape_string($id)."'". This would eliminate race conditions... Also, the view column is not string (I hope), so you don't need the single quotes around the value... –

Delete multiple rows by selecting checkboxes using PHP

I want to delete multiple rows from my MYSQL database table. I have created this file to select various links and delete them using checkboxes.
This doesn't seem to delete any row. My data is populated in the table. I guess the problem is with my PHP code. Please check the below code and guide me to get out from this...
<html>
<head>
<title>Links Page</title>
</head>
<body>
<h2>Choose and delete selected links.</h2>
<?php
$dbc = mysqli_connect('localhost','root','admin','sample') or die('Error connecting to MySQL server');
$query = "select * from links ORDER BY link_id";
$result = mysqli_query($dbc,$query) or die('Error querying database');
$count=mysqli_num_rows($result);
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td>
<form name="form1" method="post" action="">
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td bgcolor="#FFFFFF"> </td>
<td colspan="3" bgcolor="#FFFFFF">
<strong>Delete multiple links</strong>
</td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF">
<strong>Link ID</strong>
</td>
<td align="center" bgcolor="#FFFFFF">
<strong>Link Name</strong>
</td>
<td align="center" bgcolor="#FFFFFF">
<strong>Link URL</strong>
</td>
</tr>
<?php
while ($row=mysqli_fetch_array($result)) {
?>
<tr>
<td align="center" bgcolor="#FFFFFF">
<input name="checkbox" type="checkbox" value="
<?php echo $row['link_id']; ?>">
</td>
<td bgcolor="#FFFFFF"> <?php echo $row['link_id']; ?> </td>
<td bgcolor="#FFFFFF"> <?php echo $row['link_name']; ?> </td>
<td bgcolor="#FFFFFF"> <?php echo $row['link_url']; ?> </td>
</tr>
<?php
}
?>
<tr>
<td colspan="4" align="center" bgcolor="#FFFFFF">
<input name="delete" type="submit" value="Delete">
</td>
</tr>
</table>
</form>
</td>
</tr>
</table>
<?php
// Check if delete button active, start this
if(isset($_POST['delete']))
{
$checkbox = $_POST['checkbox'];
for($i=0; $i<count($checkbox); $i++) {
$del_id = $checkbox[$i];
$sql = "DELETE FROM links WHERE link_id='$del_id'";
$result = mysqli_query($sql);
}
// if successful redirect to delete_multiple.php
if($result){
echo '<meta http-equiv="refresh" content="0;URL=view_links.php">';
}
}
mysqli_close($dbc);
?>
</body>
</html>
You should treat it as an array like this,
<input name="checkbox[]" type="checkbox" value="<?php echo $row['link_id']; ?>">
Then only, you can take its count and loop it for deletion.
You also need to pass the database connection to the query.
$result = mysqli_query($dbc, $sql);
Yours did not include it:
$result = mysqli_query($sql);
Use array notation like name="checkbox[]" in your input element. This will give you $_POST['checkbox'] as array. In the query you can utilize it as
$sql = "DELETE FROM links WHERE link_id in ";
$sql.= "('".implode("','",array_values($_POST['checkbox']))."')";
Thats one single query to delete them all.
Note: You need to escape the values passed in $_POST['checkbox'] with mysql_real_escape_string or similar to prevent SQL Injection.
<?php $sql = "SELECT * FROM guest_book";
$res = mysql_query($sql);
if (mysql_num_rows($res)) {
$query = mysql_query("SELECT * FROM guest_book ORDER BY id");
$i=1;
while($row = mysql_fetch_assoc($query)){
?>
<input type="checkbox" name="checkboxstatus[<?php echo $i; ?>]" value="<?php echo $row['id']; ?>" />
<?php $i++; }} ?>
<input type="submit" value="Delete" name="Delete" />
if($_REQUEST['Delete'] != '')
{
if(!empty($_REQUEST['checkboxstatus'])) {
$checked_values = $_REQUEST['checkboxstatus'];
foreach($checked_values as $val) {
$sqldel = "DELETE from guest_book WHERE id = '$val'";
mysql_query($sqldel);
}
}
}
Delete Multiple checkbox using PHP Code
<input type="checkbox" name="chkbox[] value=".$row[0]."/>
<input type="submit" name="delete" value="delete"/>
<?php
if(isset($_POST['delete']))
{
$cnt=array();
$cnt=count($_POST['chkbox']);
for($i=0;$i<$cnt;$i++)
{
$del_id=$_POST['chkbox'][$i];
$query="delete from $tablename where Id=".$del_id;
mysql_query($query);
}
}
Something that sometimes crops up you may/maynot be aware of
Won't always be picked up by by $_POST['delete'] when using IE. Firefox and chrome should work fine though. I use a seperate isntead which solves the problem for IE
As for your not deleting in your code above you appear to be echoing out 2x sets of check boxes both pulling the same data? Is this just a copy + paste mistake or is this actually how your code is?
If its how your code is that'll be the problem as the user could be ticking one checkbox array item but the other one will be unchecked so the php code for delete is getting confused. Either rename the 2nd check box or delete that block of html surely you don't need to display the same list twice ?
$deleted = $_POST['checkbox'];
$sql = "DELETE FROM $tbl_name WHERE id IN (".implode(",", $deleted ) . ")";

using radio buttons in a html table?

Rather noobish question but I have tried searching and just cannot find a solution. My problem is I have a table called Off, which stores all of the staffs holidays. However before a staff member may have that day off it has to be authorised. I have a query which gets all of the unauthorised holidays and I display them in a html table. The problem is that I need 2 radio buttons per record. one for authorise and one for deny. The radio buttons are displayed but when going through the records only one of the radio buttons is selectable. Is it possible to use radio buttons in this way?
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/Apollo/dbc.php";
include_once($path);
$rs_results = mysql_query("SELECT * FROM off WHERE IsItAuthorised='0' and isitsick='0' ORDER BY DayOff");
?>
<html>
<head>
<title>Administration Main Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php
$limit = count($OffID);
if (isset($_POST['submit'])) {
//Assign each array to a variable
$id = $_POST['OffID'];
$answer = $_POST['radio'];
$limit = count($OffID);
$values = array(); // initialize an empty array to hold the values
for($k=0;$k<$limit;$k++){
$msg[] = "$limit New KPI's Added";
$query = "UPDATE Off SET IsItAuthorised = '{$answer[$k]}' WHERE OffID = '{$OffID[$k]}'";
}
$Event = "INSERT INTO events (UserName, Event ) VALUES ('$_SESSION[user_name]', 'Entered New KPI' )";
if (!mysql_query($query,$link)){
die('Error: ' . mysql_error());
} else {
mysql_query($Event);
echo "<div class=\"msg\">" . $msg[0] . "</div>";
}
}
?>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="14%" valign="top"><?php
?>
</td>
<td width="74%" valign="top" style="padding: 10px;">
<p><?php
if(!empty($msg)) {
echo $msg[0];
}
?></p>
<p>
<?php
$cond = '';
$sql = "select * from off ";
$rs_total = mysql_query($sql) or die(mysql_error());
$total = mysql_num_rows($rs_total);
?>
<p>
<form name "searchform" action="/Apollo/Admin/HolidayRequests" method="post">
<table width="100%" border="0" align="center" cellpadding="2" cellspacing="0">
<tr class="mytables">
<td width="4%"><font color="white"><strong>ID</font></strong></td>
<td width="4%"> <font color="white"><strong>Staff Member</font></strong></td>
<td width="10%"><font color="white"><strong>Day Off</font></strong></div></td>
<td width="10%"><font color="white"><strong>Is It Authorized</font></strong></div></td>
<td width="15%"> </td>
</tr>
<tr>
<td> </td>
<td width="10%"> </td>
<td width="17%"><div align="center"></div></td>
<td> </td>
</tr>
<?php while ($rrows = mysql_fetch_array($rs_results)) {?>
<tr>
<td><input type="" name="id[]" id="id[]" size="4" value="<?php echo $rrows['OffID'];?>" /></td>
<td><?php echo $rrows['StaffMember']; ?></td>
<td><?php echo date('d/m/Y', strtotime($rrows['DayOff']));?></div></td>
<td> <span id="approve<?php echo $rrows['id']; ?>">
<?php if(!$rrows['IsItAuthorised']) { echo "Pending"; } else {echo "Authorized"; }?>
</span> </td>
<td>
<input type="radio" name="radio[0]" id="radio[0]" value="1" />Approve
<input type="radio" name="radio[1]" id="radio[1]" value="0" />Deny
</td>
</tr>
<?php } ?>
</table>
<input name="submit" type="submit" id="submit" value="Submit">
</form>
</p>
<?php
?>
<p> </p>
<p> </p>
<p> </p>
<p> </p></td>
<td width="12%"> </td>
</tr>
</table>
</body>
</html>
Your problem is to do with your use of the "name" attribute - this attribute is used in a special way on radio buttons.
When you click on a radio button, all the other radio buttons with the same name are deselected - in your case, you will have half of the radio buttons on the page in one group and half in another, which would probably explain why you can only select one. I'd imagine you can actually select two at the same time, if you click on the right radio buttons.
To fix this you'd need to have some kind of count for the while loop, ie:
$resultNumber = 0;
while ($rrows = mysql_fetch_array($rs_results)) {
Then you'd need to use this number in the name (and also id) of the radio buttons -
<input type="radio" name="radio<?php echo $resultNumber; ?>" id="radio<?php echo $resultNumber; ?>" value="1" />
Then simply increment the $resultNumber at the end of each iteration -
<?php
$resultNumber++;
}
?>
Alternatively, you could use the primary key of the row from the database table you're querying to distinguish groups, but not knowing the table structure I couldn't give sample code for that.
Further reading on radio buttons (also a source for the name attribute problem) :
http://www.echoecho.com/htmlforms10.htm
Instead of radio buttons, I used checkboxes, which I looped through. Each checkbox set a value to a different column. Should have been obvious to me to begin with.

Categories