I am trying to make this form with checkboxes get values 1 or 0, sort of a boolean, and UPDATE it on mysql, but I havent found a way yet. Maybe you can help. I'll post the form and the code that receives it. I am sure there might be a conflict of loops, but I tryed everything and couldnt get it working. Tks in advance.
THE FORM
<form action="esconde_cat.php" method="post">
<table width="300px" align="center" width="140" border="1">
<tr>
<td></td>
<td width="200">Categoria</td>
<td width="100">Mostrar</td>
</tr>
<?php
include "conecta.php";
include "verifica.php";
$sql = "SELECT * FROM categorias ORDER BY ordem";
$res = mysql_query($sql) or die (mysql_error());
while ($linha=mysql_fetch_array($res)) {
?>
<tr>
<td><input name="user[]" type="checkbox" value="true"/></td>
<td><?=$linha['1']; ?></td>
<td><?php if ($linha['3'] == TRUE){ echo 'SIM'; } else {echo 'NÃO'; } ?></td>
</td>
</tr>
<?php
}
?>
</table>
<br/>
<table align="center">
<tr>
<td>
<input type="submit" name="Delete" type="button" value="Alterar">
</td>
</tr>
</table>
</form>
THE CODE THAT RECEIVES THE FORM AND UPDATE MYSQL
<?php
include "conecta.php";
include "verifica.php";
\\THIS PART WORKS, GETS IF THE CHECKBOX IS CHECKED AND RECORD IT ON DB
if(isset($_POST['user'])) {
foreach ($_POST['user'] as $key => $read){
$read =(#$_POST['user']=='0')? $_POST['user']:'1';
echo $read;
$sql = "UPDATE categorias SET mostrar='$read' WHERE ordem='$key'";
$res = mysql_query($sql) or die ("Erro ao excluir") . mysql.error();
}
}
\\ON THIS PART OF THE CODE THAT I CANT GET THE VARIABLE TO GET THE
\\VALUE FROM CHEBOXES THAT ARE UNCHECKED RECORDED TO DATABASE
if (!isset($_POST['user'])) {
foreach ($_POST['user'] as $chave => $leia) {
$leia =(#$_POST['user']=='1')? $_POST['user']:'0';
echo $leia;
$sql = "UPDATE categorias SET mostrar='$leia' WHERE ordem='$chave'";
$res = mysql_query($sql) or die ("Erro ao excluir") . mysql.error();
}
}
?>
If a checkbox is left unchecked you will get NO key in the $_POST variable. If it's checked the key will be set and the value will be the value of the checkbox.
Assuming a name of "user[]" works, with something like:
<input type="checkbox" name="user[]" value="aa" />
<input type="checkbox" name="user[]" value="bb" checked="checked" />
<input type="checkbox" name="user[]" value="cc" checked="checked" />
<input type="checkbox" name="user[]" value="dd" />
<input type="checkbox" name="user[]" value="ee" checked="checked" />
You would expect $_POST to be:
array(
"user" => array(
"1" => "bb"
"2" => "cc"
"4" => "ee"
)
);
Related
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");
?>
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, ...
I have tried out some code for dynamic insertion of data using array but the issue am facing is in a single row same data is been inserted and even if check box are left un-checked data value is inserted ignoring the checked value inside a "while-loop"..I am new to this array concept please help me out.
.php
<form id="form" name ="form" method = "POST" action="move_ppl.php" class="wizard-big" autocomplete = "off" enctype="multipart/form-data">
<div class="col-md-12">
<?php
$con = mysqli_connect("localhost","***","***","***");
$query = ("SELECT * FROM profile");
$result = mysqli_query($con, $query);
while ($row = $result->fetch_assoc())
{
echo '
<tr>
<td align="left">' . $row['via'] . '<input type="hidden" name="type[]" value="' . $row['via'] . '"></td>
<td align="left"> <input type="checkbox" name="type[]" value="macro"/> Macro </td>
<td align="left"> <input type="checkbox" name="type[]" value="micro"/> Micro </td>
<td align="left"> <input type="checkbox" name="type[]" value="nano"/> Nano </td>
</tr>';
}
?>
<input style="width: 100%;" type="submit" name = "submit" id = "submit" value="Move" class="btn btn-info"><br><br>
</form>
DB.php
<?php
session_start();
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$response = array();
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
if(isset($_POST["submit"]) && isset($_POST["type"])){
//receiving post parameters
$types = $_POST["type"];
if(sizeof($types) > 0 ){
foreach($types as $type){
// create a new user profile
$sql = "INSERT INTO ppl_tbl (vault_no, via, gname, ppl, macro, micro, nano, created_at) VALUES ('".$_SESSION['via']."', '".$_SESSION['vault_no']."', '".$_SESSION['gname']."', '".$type."','".$type."','".$type."','".$type."', NOW())";
if(mysqli_query($con,$sql)){
header('Location: macro_ppl.php');
}else{
$response["error"] = true;
$response["error_msg"] = "INSERT operation failed";
echo json_encode($response);
}
}
}
}
?>
First of all checkbox values will not be present in the post if they are not set.
Second of all you add many results cause you call insert sql in the loop.
You can use:
var_dump($_POST['type']);
so you will see how the structure actually look like.
There are many ways to make this work one could be:
//setting the variables first
$ppl = 0;
$macro = 0;
$micro = 0;
$nano = 0;
//then run the loop to set them
foreach($types as $type){
if(in_array($type,['ppl','macro','micro','nano'])) //just to be sure nobody pass something else so we will not override other variables
$$type = 1;
}
//then write the query
$sql = "INSERT INTO ppl_tbl (vault_no, via, gname, ppl, macro, micro, nano, created_at) VALUES ('".$_SESSION['via']."', '".$_SESSION['vault_no']."', '".$_SESSION['gname']."', '".$ppl."','".$macro."','".$micro."','".$nano."', NOW())";
You are doing it wrong, just submit a form with data array
Form
<form id="form" name ="form" method = "POST" action="someForm.php">
<tr>
<td align="left"> <input type="checkbox" name="type[]" value="macro"/> Macro </td>
<td align="left"> <input type="checkbox" name="type[]" value="micro"/> Micro </td>
<td align="left"> <input type="checkbox" name="type[]" value="nano"/> Nano </td>
</tr>
</form>
someForm.php
if (isset($_POST['type'])) {
foreach ($_POST['type'] as $myType) {
echo $myType
}
}
Your Form
<form id="form" name ="form" method = "POST" action="move_ppl.php" class="wizard-big" autocomplete = "off" enctype="multipart/form-data">
<?php
$con = mysqli_connect("localhost","***","***","***");
$query = ("SELECT * FROM profile");
$result = mysqli_query($con, $query);
while ($row = $result->fetch_assoc())
{
?>
<tr>
<td align="left"><?php echo $row['via'] ?><input type="hidden" name="type[]" value="<?php echo $row['via'] ?>"></td>
<td align="left"> <input type="checkbox" name="type[]" value="macro"/> Macro </td>
<td align="left"> <input type="checkbox" name="type[]" value="micro"/> Micro </td>
<td align="left"> <input type="checkbox" name="type[]" value="nano"/> Nano </td>
</tr>
<?php
}
?>
<input style="width: 100%;" type="submit" name = "submit" id = "submit" value="Move" class="btn btn-info"><br><br>
</form>
In PHP file
if (isset($_POST['submit'])) {
if(isset($_POST['type'])) {
foreach ($_POST['type'] as $value) {
echo $value;
/*add this in the query, this will return the value of checkbox which are checked*/
}
}
}
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");
?>
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?