How to retrieve value from the Check boxes? - php

I'm trying to get the emails corresponding to the checkbox using the following codes. But, I'm not getting the correct checked emails in the new variable. Can anyone please check ??
<?php
include("connection.php");
$username=$_SESSION['username'];
$query=mysql_query("SELECT * FROM contacts WHERE username='$username'");
$num=mysql_num_rows($query);
$info=mysql_fetch_array($query);
$i=0;
$msg='';
?>
<table width="672" border="0">
<?php
$i=0;
while($info)
{
?>
<form action="compose.php" method="post">
<tr style="font-size:14px;">
<td width="21" bgcolor="#f2f2f2"> <input type="checkbox" name="add" onSelect="<?php $msg=$msg.$info['email'].", ";?>"/> </td>
<td width="229" bgcolor="#f2f2f2"> <?php echo $info['email']; ?> </td>
<td width="408" bgcolor="#f2f2f2"> <?php echo $info['name']; ?> </td>
</tr>
<?php
$info=mysql_fetch_array($query);
$i++;
}
$_SESSION['contacts']=$msg;
?>
<tr><td></td><td></td><td><br />
<input class="new-button" type="submit" value="Insert & Compose" name="submit" /></td>
</tr>
</form>
</table>

To get any value back for checkboxes they must have a value=. In your case you probably would want the value to be the according email address.
One problem with your code is using onSelect= instead of value=, and second you didn't print the actual value into the page. Rewrite it to:
<td width="21" bgcolor="#f2f2f2">
<input type="checkbox" name="add"
value="<?php print $info['email']; ?>"/> </td>
If you need the $msg variable to do something, assemble it after the output.

<input type="checkbox" name="add" value="<?php echo $msg.$info['email'];?>"/>
checkbox does not have onSelect event probobly you got value in mind and in PHP code you should echo and what .", " is for?

Related

How to use form and its php processing inside a loop [duplicate]

I have outputted the results of a MySQL table to an HTML table. In the last column, I want to add a delete option which calls another form and deletes the user from the MySQL table. I can't seem to get it to work though.
This is my code for the results page:
<?php
$contacts = mysql_query("
SELECT * FROM contacts ORDER BY ID ASC") or die( mysql_error() );
// If results
if( mysql_num_rows( $contacts ) > 0 )
?>
<table id="contact-list">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Telephone</th>
<th>Address</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php while( $contact = mysql_fetch_array( $contacts ) ) : ?>
<tr>
<td class="contact-name"><?php echo $contact['name']; ?></td>
<td class="contact-email"><?php echo $contact['email']; ?></td>
<td class="contact-telephone"><?php echo $contact['telephone']; ?></td>
<td class="contact-address"><?php echo $contact['address']; ?></td>
<td class="contact-delete"><form action='delete.php' method="post">
<input type="hidden" name="name" value="">
<input type="submit" name="submit" value="Delete">
</form></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
and, this is my delete.php script
<?php
//Define the query
$query = "DELETE FROM contacts WHERE name={$_POST['name']} LIMIT 1";
//sends the query to delete the entry
mysql_query ($query);
if (mysql_affected_rows() == 1) {
//if it updated
?>
<strong>Contact Has Been Deleted</strong><br /><br />
<?php
} else {
//if it failed
?>
<strong>Deletion Failed</strong><br /><br />
<?php
}
?>
I cannot figure out why this is not working.
You have to pass a variable in the delete link. You have to pass <?php echo $contact['name']; ?> (the name value) in a hidden field or pass this value in URL:
Replace
<td class="contact-delete">
<form action='delete.php' method="post">
<input type="hidden" name="name" value="">
<input type="submit" name="submit" value="Delete">
</form>
</td>
With
<td class="contact-delete">
<form action='delete.php?name="<?php echo $contact['name']; ?>"' method="post">
<input type="hidden" name="name" value="<?php echo $contact['name']; ?>">
<input type="submit" name="submit" value="Delete">
</form>
</td>
USe javascript
<input name="Submit2" type="button" class="button" onclick="javascript:location.href='delete.php?id=<?php echo $your_id;?>';" value="« Back" />
and in delet.php
$id=$_GET['id'];
and put $id in your sql statement.
You are missing to pass name in this line:
<input type="hidden" name="name" value="">
You need to have something (<?php echo $contact['name']; ?>) in the value attribute.
BTW, do not use deprecated mysql_* functions, use PDO or mysqli_* instead.
<input type="hidden" name="name" value="">
You are missing a value which wil be picked up by this line in your delete file.
$query = "DELETE FROM contacts WHERE name={$_POST['name']} LIMIT 1";
Right now it isn't receiving anything, which is why it will not work.
So add a value to it and it will work. Example:
<input type="hidden" name="name" value="<?php echo $contact['name']; ?>">
First, you should not write the code in that way; the code has no protection against SQL injection.
1. Try to use primary IDs instead of using a name (what happens if 2 people has the same name?).
So, you can create a hidden field to know which 'person' you are dealing with.
<input type="hidden" name="contact_id" value="<?php $contact['contact_id']; ?>">
2. Sanitize variables to avoid attacks:
<?php $contact_id = isset($_POST['contact_id'])?intval($_POST['contact_id']):0;
// proceed with the query
if($contact_id>0) { $query = "DELETE FROM contacts WHERE contact_id = '$contact_id'";
}
// redirect to the main table with header("location: main.php");
?>

Cannot delete row in database using PHP

I can't seem to delete row in database by id in php
I think the the id is not passed to the $_POST['delete']
however, the popup "Your data is deleted" is displayed, but the data is not deleted.
So I'm not sure where is the error in this code.
I also try to delete the data by its id
for example: Delete book where no='4';
and the code seems to run fine because the data is deleted in the database.
<html>
<script>
function confirmDelete() {
return confirm('Are you sure?');
}
</script>
<!DOCTYPE html>
<head>
<form action="test.php" method="POST">
<br><br><br>
<table bordercolor="#FFCC66" align="center" bgcolor="#FFFFFF">
<tr>
<th>No</th>
<th>Title</th>
<th>Author</th>
<th>Year</th>
<th>Donor's Name</th>
<th>Call Number</th>
<th>Date Received</th>
<th>Handled By</th>
<th></th>
<th></th>
</tr>
<?php
include ('config.php');
$view=mysqli_query($conn,"SELECT * FROM book");
?>
<?php while($v=mysqli_fetch_array($view)){ ?>
<tr>
<td>
<?php echo $v["no"];?>
</td>
<td>
<?php echo $v["title"];?>
</td>
<td>
<?php echo $v["author"];?>
</td>
<td>
<?php echo $v["year"];?>
</td>
<td>
<?php echo $v["donorname"];?>
</td>
<td>
<?php echo $v["callnum"];?>
</td>
<td>
<?php echo $v["datereceived"];?>
</td>
<td>
<?php echo $v["handledby"];?>
</td>
<td><input type="submit" name="delete" value="Delete" onclick="return confirmDelete('Are you sure?');" /></td>
</tr>
<?php
} ?>
</tr>
</table>
<br><br>
</form>
</body>
</html>
<?php
if(isset($_POST['delete']))
{
include('config.php');
$no =$v["no"];
$d=mysqli_query($conn,"DELETE FROM `book` WHERE no='$no'");
if ($d)
{
echo "<script type='text/javascript'> alert('Your data is deleted!'); </script>";
echo"<meta http-equiv='Refresh' content='0' >";
}
else
{
echo "<script type='text/javascript'> alert('Your data cannot delete!'); </script>";
}
mysqli_close($conn);
}
?>
Change the submit element to
<td>
<input type="submit" name="delete" value="<?php echo $v['no'];?>" onclick="return confirmDelete('Are you sure?');" />
</td>
and
$no = $_POST["delete"];
Another solution si to add a hidden input with your value.
<td>
<?php echo $v["no"];?>
<input type="hidden" value="<?php echo $v["no"];?>" />
</td>
In your php you will find the value in $_POST['no']
This solution is better to pass multiple arguments in POST like a captcha or a confirmation (checkbox).
logic is not correct, while you press the delete button, all the data will be passed along with submitting because your tag is outside of the loop.
As my opinion, you should use ajax like functionality here, or follow this method.
<?php while($v=mysqli_fetch_array($view)){ ?>
<form action="test.php" method="POST">
<tr>
<td>
<?php echo $v["no"];?>
<input type="hidden" value="<?php echo $v["no"];?>" name="no" >
</td>
<td><input type="submit" name="delete" value="Delete" onclick="return confirmDelete('Are you sure?');" /></td>
</tr>
</form>
<?php } ?>
and in your post call use $no = $_POST['no']; instead of $no =$v["no"];

Storing data from attendance system

I'm trying to create a students attendance system and when I'm attempting to store information to the database, I'm getting various errors about the attendance status. I'm aware this isn't a typical problem for all but it would help a beginner of PHP.
<form action="tutor_attendance.php" method="post">
<table class="table table-striped">
<tr>
<th>Student ID</th> <th>Module Name</th> <th>Attendance Status </th>
</tr>
<?php $result=mysqli_query($conn, "SELECT * FROM student");
// $serialnumber=0;
$counter=0;
while($row=mysqli_fetch_array($result))
{
?>
<tr>
<td> <?php echo $row['stud_id']; ?> </td>
<input type="hidden" value="<?php echo $row['stud_id']; ?>" name="stud_id[]" >
<td> <?php echo $row['module_1']; ?> </td>
<input type="hidden" value="<?php echo $row['module_1']; ?>" name="module_1[]">
<td>
<input type="radio" name="attendance_status[<?php echo $counter; ?>]" value="Present">Present
<input type="radio" name="attendance_status[<?php echo $counter; ?>]" value="Absent">Absent
<input type="radio" name="attendance_status[<?php echo $counter; ?>]" value="Late">Late
</td>
</tr>
<?php
$counter++;
}
?>
</table>
<input type="submit" name="submit" class="btn btn-primary " value="submit" >
</form>
The code above is the form that I'm using to present data from the database and then capture their attendance with a radio button.
if(isset($_POST['submit']))
{
foreach($_POST['attendance_status'] as $id->$attendance_status)
{
$stud_id=$_POST['stud_id'][$id];
$module_1=$_POST['module_name'][$id];
$date=date("Y-m-d H:i:s");
mysqli_query($conn, "INSERT into attedance('stud_id, module_name, attendance_status, date) VALUES('$stud_id', '$module_1','$attendance_status','$date')");
}
}
Then the code above this is once the submit button has been pressed. The errors that I'm getting are: Undefined variable: attendance_status and Creating default object from empty value. Any help would be appreciated. The errors are occurring on line 8 - foreach($_POST['attendance_status'] as $id->$attendance_status)
I see a few different problems but the error you are getting is due to improper foreach syntax, which should be key => value not key->value
foreach($_POST['attendance_status'] as $id => $attendance_status) {
}
The errant quote in your SQL is not causing this error, but it is certainly another error. See this line:
"INSERT into attedance('stud_id, module_name, ...
Also did you really typo your table name for attendance? My guess is that it should be:
"INSERT into attendance(stud_id, module_name, ...

How to add a delete button to a PHP form that will delete a row from a MySQL table

I have outputted the results of a MySQL table to an HTML table. In the last column, I want to add a delete option which calls another form and deletes the user from the MySQL table. I can't seem to get it to work though.
This is my code for the results page:
<?php
$contacts = mysql_query("
SELECT * FROM contacts ORDER BY ID ASC") or die( mysql_error() );
// If results
if( mysql_num_rows( $contacts ) > 0 )
?>
<table id="contact-list">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Telephone</th>
<th>Address</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php while( $contact = mysql_fetch_array( $contacts ) ) : ?>
<tr>
<td class="contact-name"><?php echo $contact['name']; ?></td>
<td class="contact-email"><?php echo $contact['email']; ?></td>
<td class="contact-telephone"><?php echo $contact['telephone']; ?></td>
<td class="contact-address"><?php echo $contact['address']; ?></td>
<td class="contact-delete"><form action='delete.php' method="post">
<input type="hidden" name="name" value="">
<input type="submit" name="submit" value="Delete">
</form></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
and, this is my delete.php script
<?php
//Define the query
$query = "DELETE FROM contacts WHERE name={$_POST['name']} LIMIT 1";
//sends the query to delete the entry
mysql_query ($query);
if (mysql_affected_rows() == 1) {
//if it updated
?>
<strong>Contact Has Been Deleted</strong><br /><br />
<?php
} else {
//if it failed
?>
<strong>Deletion Failed</strong><br /><br />
<?php
}
?>
I cannot figure out why this is not working.
You have to pass a variable in the delete link. You have to pass <?php echo $contact['name']; ?> (the name value) in a hidden field or pass this value in URL:
Replace
<td class="contact-delete">
<form action='delete.php' method="post">
<input type="hidden" name="name" value="">
<input type="submit" name="submit" value="Delete">
</form>
</td>
With
<td class="contact-delete">
<form action='delete.php?name="<?php echo $contact['name']; ?>"' method="post">
<input type="hidden" name="name" value="<?php echo $contact['name']; ?>">
<input type="submit" name="submit" value="Delete">
</form>
</td>
USe javascript
<input name="Submit2" type="button" class="button" onclick="javascript:location.href='delete.php?id=<?php echo $your_id;?>';" value="« Back" />
and in delet.php
$id=$_GET['id'];
and put $id in your sql statement.
You are missing to pass name in this line:
<input type="hidden" name="name" value="">
You need to have something (<?php echo $contact['name']; ?>) in the value attribute.
BTW, do not use deprecated mysql_* functions, use PDO or mysqli_* instead.
<input type="hidden" name="name" value="">
You are missing a value which wil be picked up by this line in your delete file.
$query = "DELETE FROM contacts WHERE name={$_POST['name']} LIMIT 1";
Right now it isn't receiving anything, which is why it will not work.
So add a value to it and it will work. Example:
<input type="hidden" name="name" value="<?php echo $contact['name']; ?>">
First, you should not write the code in that way; the code has no protection against SQL injection.
1. Try to use primary IDs instead of using a name (what happens if 2 people has the same name?).
So, you can create a hidden field to know which 'person' you are dealing with.
<input type="hidden" name="contact_id" value="<?php $contact['contact_id']; ?>">
2. Sanitize variables to avoid attacks:
<?php $contact_id = isset($_POST['contact_id'])?intval($_POST['contact_id']):0;
// proceed with the query
if($contact_id>0) { $query = "DELETE FROM contacts WHERE contact_id = '$contact_id'";
}
// redirect to the main table with header("location: main.php");
?>

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