I've got a question about databases and checkboxes. I've got a table looking like:
Website is looking like:
At the bottom of the page I also have a button, so when I submit the checked checkboxes will be updated to 1 or 0 in the database. (True or false)
So when I click on the 3rd checkbox under trained, it will update the trained column in the database with a user/room id of '3583'. (ID is shown right of the screen)
Code:
<form class='verwerkInfo' method='post' action='<?php echo $_SERVER['PHP_SELF']; ?>?license=6'>
<td>
<?php if($room->trained == 1) { ?> <input type='checkbox' name="<?php echo $room->room_id; ?>" checked> <?php echo "Y"; } else{ ?> <input type='checkbox' name="<?php echo $room->room_id; ?>"> <?php echo "N"; }?> </td>
<Td><?php if($room->active == 1) { ?> <input type='checkbox' name="<?php echo $room->room_id; ?>" checked> <?php echo "Active"; } else { ?> <input type='checkbox' name="<?php echo $room->room_id; ?>" <?php echo "Inactive"; } ?>
</td>
<Td><?php echo $room->configuration; ?></td>
<td><?php echo $room->room_id; ?></td>
<td><?php var_dump($room->user_id); }?></td>
</tr>
So I guess I have a problem in the names of the checkboxes.
The query is looking like:
$trainedQuery = "UPDATE room_users
SET trained = 1
WHERE user_id = $room->user_id";
The $room->user_id is referring to the user_id in the database.
Here's a way to give the checkboxes unique names and pass extra information with each element:
name="trained[<?php echo $room->room_id; ?>]" value="<?php echo $room->user_id; ?>"
Then in the PHP script that processes the form submission you can:
foreach ( $_POST['trained'] as $room_id => $user_id ) {
// This query needs protection from SQL Injection!
$trainedQuery = "UPDATE room_users SET trained = 1 WHERE user_id = $user_id";
}
It's not clear what the relationship is between room_id and user_id and why you're updating the room_user table with only user_id. What do you do with the room_id?
Is this what you actually need:
// This query needs protection from SQL Injection!
$trainedClear = "UPDATE room_users SET trained = 0 WHERE user_id = $user_id";
$db->exec($trainedClear); // first clear all
foreach ( $_POST['trained'] as $room_id => $user_id ) {
// This query needs protection from SQL Injection!
$trainedQuery = "UPDATE room_users SET trained = 1
WHERE user_id = $user_id AND room_id = $room_id";
$db->exec($trainedQuery); // then add selections
}
// assuming there's a database connection `$db-exec`.
// Replace with your actual connection and query method.
Refactored checkbox columns for clarity:
<?php
$room_id = $room->id;
$room_configuration = $room->configuration;
$room_user_id = $room->user_id;
if ( $room->trained == 1 ) {
$trained_checked = 'checked';
$trained_label = 'Y';
}
else {
$trained_checked = '';
$trained_label = 'N';
}
if ( $room->active == 1 ) {
$active_checked = 'checked';
$active_label = 'Active';
}
else {
$active_checked = '';
$active_label = 'Inactive';
}
echo <<<EOT
<td><input type="checkbox" name="trained[$room_id]" value="$room_user_id" $trained_checked> $trained_label</td>
<td><input type="checkbox" name="active[$room_id]" value="$room_user_id" $active_checked> $active_label</td>
<td>$room_configuration</td>
<td>$room_id</td>
<td>$room_user_id</td>
EOT;
?>
Just change the checkbox names attribute with adding yes,no and active
name="yes_<?php echo $room->room_id; ?>"
name="no_<?php echo $room->room_id; ?>"
name="act_<?php echo $room->room_id; ?>"
Related
So, I am doing a library system. A librarian can view all the books, and may choose to edit a book and it's details. However, when I click edit, the values do not show up in the input field.
This is my edit portion of the code. I am getting an error:
count(): Parameter must be an array or an object that implements
Countable on line 7
which is if (count($record) == 1 ) {:
<?php
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$update = true;
$record = mysqli_query($db, "SELECT * FROM bookinfo WHERE BookNo='$BookNo'");
if (count($record) == 1 ) {
$n = mysqli_fetch_array($record);
$BookNo = $n['BookNo'];
$ISBN = $n['ISBN'];
$title = $n['title'];
$author = $n['author'];
$publisher = $n['publisher'];
$status = $n['status'];
$cost = $n['cost'];
}
}
?>
This is my displaying of the data for the librarian, along with the edit button:
<?php while ($row = mysqli_fetch_array($results)) { ?>
<tr>
<td><?php echo $row['BookNo']; ?></td>
<td><?php echo $row['ISBN']; ?></td>
<td><?php echo $row['title']; ?></td>
<td><?php echo $row['author']; ?></td>
<td><?php echo $row['publisher']; ?></td>
<td><?php echo $row['status']; ?></td>
<td><?php echo $row['cost']; ?></td>
<td>
<a href="viewBook.php?edit=<?php echo $row['BookNo']; ?>" class="edit_btn" >Edit</a>
</td>
Followed by, the fields in which the librarian can edit the details.
<?php
if (isset($_GET['edit'])) { ?>
<form method="post" action = "viewBook.php">
<input type="hidden" name="BookNo" value="<?php echo $BookNo; ?>">
<input type="text" name="ISBN" value="<?php echo $ISBN; ?>">
<input type="text" name="title" value="<?php echo $title; ?>">
<input type="text" name="author" value="<?php echo $author; ?>">
<input type="text" name="publisher" value="<?php echo $publisher; ?>">
<input type="text" name="status" value="<?php echo $status; ?>">
<input type="text" name="cost" value="<?php echo $cost; ?>">
<?php if ($update == true): ?>
<button class="btn" type="submit" name="update" style="background: #556B2F;" >update</button>
<?php else: ?>
<button class="btn" type="submit" name="save" >Save</button>
<?php endif ?>
<?php } ?>
</form>
When I click the edit button, I get the error stated above, as well as the text fields not having the details already written inside.
count() function only works with arrays and other countable fields
use the mysqli_num_rows
<?php
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$update = true;
$record = mysqli_query($db, "SELECT * FROM bookinfo WHERE BookNo='$BookNo'");
if (mysqli_num_rows($record) == 1 ) {
$n = mysqli_fetch_array($record);
$BookNo = $n['BookNo'];
$ISBN = $n['ISBN'];
$title = $n['title'];
$author = $n['author'];
$publisher = $n['publisher'];
$status = $n['status'];
$cost = $n['cost'];
}
}
?>
this mysqli_num_rows can give you result of the count of amount of data from sql query
I think this will work for you.
use mysqli_fetch_assoc()
So, I am doing a library system. A librarian can view all the books, and may choose to edit a book and it's details. However, when I click edit, the values do not show up in the input field.
This is my edit portion of the code. I am getting an error:
count(): Parameter must be an array or an object that implements Countable on line 7
which is if (count($record) == 1 ) {:
<?php
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$update = true;
$record = mysqli_query($db, "SELECT * FROM bookinfo WHERE BookNo='$BookNo'");
if (count($record) == 1 ) {
$n = mysqli_fetch_assoc($record);
$BookNo = $n['BookNo'];
$ISBN = $n['ISBN'];
$title = $n['title'];
$author = $n['author'];
$publisher = $n['publisher'];
$status = $n['status'];
$cost = $n['cost'];
}
}
?>
I've got a question.
I've got a page with checkboxes generated with the database. When we press the checkbox and submit it, it is working fine and it is updating in the database. But when I try to uncheck "1" checkbox it is checking out all checkboxes which are selected.
Query:
if(isset($_POST['submit'])){
foreach ($_POST['untrain'] as $room_id => $user_id) {
// This query needs protection from SQL Injection!
$user_id;
$untrainQuery = "UPDATE room_users SET trained = '1' WHERE user_id = $user_id AND room_id = $room_id";
$db->update($untrainQuery);
}
}
if(isset($_POST['submit'])){
foreach ($_POST['amk'] as $room_id => $user_id) {
// This query needs protection from SQL Injection!
$user_id;
$untrainedQuery = "UPDATE room_users SET trained = '0' WHERE user_id = $user_id AND room_id = $room_id";
$db->update($untrainedQuery);
}
}
Checkboxes:
<?php if($room->trained == 1) { ?> <input type='hidden' value="<?php echo $room->user_id; ?>" name="amk[<?php echo $room->room_id; ?>]"> <input type='checkbox' value="<?php echo $room->user_id; ?>" name="trained[<?php echo $room->room_id; ?>]" checked> <?php echo "Y"; } else{ ?> <input type='checkbox' value="<?php echo $room->user_id; ?>" name="untrain[<?php echo $room->room_id; ?>]"> <?php echo "N"; }?> </td>
<Td><?php if($room->active == 1) { ?> <input type='checkbox' name="<?php echo $room->room_id; ?>" checked> <?php echo "Active"; } else { ?> <input type='checkbox' name="<?php echo $room->room_id; ?>" <?php echo "Inactive"; } ?>
I used the "trick" with the input type hidden, but it is checking out all checked checkboxes..
Thanks in advance!
I've got a page with checkboxes generated with the database. When we press the checkbox and submit it, it is working fine and it is updating in the database. But when I try to uncheck "1" checkbox it is checking out all checkboxes which are selected.
Query:
if(isset($_POST['submit'])){
foreach ($_POST['untrain'] as $room_id => $user_id) {
// This query needs protection from SQL Injection!
$user_id;
$untrainQuery = "UPDATE room_users SET trained = '1' WHERE user_id = $user_id AND room_id = $room_id";
$db->update($untrainQuery);
}
}
if(isset($_POST['submit'])){
foreach ($_POST['amk'] as $room_id => $user_id) {
// This query needs protection from SQL Injection!
$user_id;
$untrainedQuery = "UPDATE room_users SET trained = '0' WHERE user_id = $user_id AND room_id = $room_id";
$db->update($untrainedQuery);
}
}
Checkboxes:
<?php
if($room->trained == 1)
{ ?>
<input type='hidden' value="<?php echo $room->user_id; ?>" name="amk[<?php echo $room->room_id; ?>]">
<input type='checkbox' value="<?php echo $room->user_id; ?>" name="trained[<?php echo $room->room_id; ?>]" checked>
<?php echo "Y"; }
else{ ?>
<input type='checkbox' value="<?php echo $room->user_id; ?>" name="untrain[<?php echo $room->room_id; ?>]">
<?php echo "N";
}?>
</td>
<Td><?php
if($room->active == 1) {
?> <input type='checkbox' name="<?php echo $room->room_id; ?>" checked>
<?php echo "Active"; }
else { ?>
<input type='checkbox' name="<?php echo $room->room_id; ?>"
<?php echo "Inactive"; } ?>
I used the trick with the "hidden" input before the checkbox, but the only problem is that it is not working. When I click on it, it resets all checkboxes to 0.
I think you are missing how the combo checkbox + hidden input does work.
So here you go freely inspired by this answer:
<input id="foo" name="foo" type="checkbox" value="1" />
<input name="foo" type="hidden" value="0" />
Looks like you do know, if you use the trick, that, if the checkbox is unchecked, it will not be present in the post. So to trick the form, we will always add an hidden field. And if the checkbox is checked, then the fact that it will be included in the post is going to override the value of the hidden input.
So for your specific problem :
<td>
<input type="checkbox" value="1" name="trained[<?php echo $room->room_id; ?>_<?php echo $room->user_id; ?>]" <?php echo ($room->trained == 1) ? ' checked' : '' ?> /> Trained
<input type="hidden" value="0" name="trained[<?php echo $room->room_id; ?>_<?php echo $room->user_id; ?>]"/>
</td>
Please note the use of the ternary operator on this part of the code <?php echo ($room->trained == 1) ? ' checked' : '' ?> which I may use a lot when writing html template.
Please also note the trick on the name trained[<?php echo $room->room_id; ?>_<?php echo $room->user_id; ?>] which is needed because we cannot set the user_id as value of the input.
Then for the processing part :
if ( isset ( $_POST['submit'] ) ) {
foreach ( $_POST['trained'] as $ids => $value ) {
// This query needs protection from SQL Injection!
// ^ good point, on which I would suggest you using PDO and prepared statement :)
list($room_id,$user_id) = explode('_',$ids);
// ^ now need to explode the name on the underscore to get both user_id and room_id cf the trick above
$untrainQuery = "UPDATE room_users SET trained = '$value' WHERE user_id = $user_id AND room_id = $room_id";
$db->update ( $untrainQuery );
}
}
Wash, rinse, repeat for every checkbox you need and you should be good to go.
Currently, I am working on the attendance form. In this interface, it consists rows of student(get from student table). The list of students are viewed in the table. the first column is NO, second column in Birth No, third STudent Name, forth Attendance. in column attendance, there are three radio button which is PT, AT, and MC which their value is present, absent, and mc respectively. The outside of the table, there is a submit button. Teacher needs to click which attendance of the student, either pt, at or mc. Teacher needs to click for all students. When submit button clicked by teacher, attendance of the students will be inserted into the database. When I execute code below, there nothing value is inserted in the database. Can some please help me to figure it out where i went wrong? I worked on this code for past 2 weeks yet still not getting an expected result. Thank you.
$getdata = mysql_query("select * from student where
class = '$class' order by name ") or die(mysql_query);
if (isset($_POST['submit'])){
$id = 1;
while($row = mysql_fetch_assoc($getdata)){
if(isset($_POST['a'.$id])) {
$status = $_POST['a'.$id];
if(!empty($status)){
if(($status == "present" || $status == "mc")){
$attend = 1;
}
else if($status == "absent"){
$attend = 0;
}
$query = "INSERT INTO attendance(birth_no, date, status, attend)
VALUES ('$birth_no','$date','$status','$attend')";
if($query_run = mysql_query($query)){
echo 'Insert attendance done';
}
else{
echo'Attendance not inserted.';
}
}
else{
echo 'Please enter all fields';
}
}
$id ++;
}
}
else {
?>
<form action="addattend.php" method = "POST">
<table>
<?php
$id = 1;
while($row = mysql_fetch_assoc($getdata)){
$birth_no= $row['birth_no'];
$name = $row['name'];
?>
<tr>
<td><center><?php echo $id ?></center></td>
<td><center><?php echo $date ?></center></td>
<td><center><?php echo $birth_no ?></center></td>
<td><center><?php echo $name ?></center></td>
<td>
<input type="radio" name="a<?php echo $id; ?>" value="present">PT
<input type="radio" name="a<?php echo $id; ?>" value="absent">AT
<input type="radio" name="a<?php echo $id; ?>" value="mc">MC
</td>
</tr>
<?php
$id ++;
} // end while
?>
</table>
<center><input type="submit" name="submit" value="Submit"></center>
</form> <!-- end the form here -->
<?php
} // end else
?>
this is what i meant about the interface(picture below)
for every row, there are 3 radio buttons. The list of student was retrieved from the database. Teachers need to select the attendance for all students. with a single submit button, All the attendance will be inserted in the database with birth_no, date(selected earlier by teacher) and also $attend which is assigned after attendance selected.
I don't get it when you said use primary key instead of $id
Let me explain: When you use the while loop with $id you increment the $id for each while loop. What if your table is missing the primary key '1' or any one for that matter? Answer: The first row may not be correlating to the primary key of '1'. Let me further explain with some data:
An example table:
student_id | name
-----------+--------
1 | John
3 | Jane
4 | Bob
now lets loop through with a while using sudo code
$id = 1;
while(row exists){
print row['name']." has primary key of $id";
$id++;
}
This would print something similar to:
John has primary key of 1
Jane has primary key of 2
Bob has primary key of 3
Which would be incorrect.
Here is how I would go about doing something like this, this code may need slight adaptation for your specific use:
<?php
$getdata = mysql_query("select * from student where
class = '$class' order by name ") or die(mysql_query);
if (isset($_POST['submit'])){
while($row = mysql_fetch_assoc($getdata)){
//set the id equal to the primary key
$id = $row["birth_no"];
$date = date("Y-m-d");
if(isset($_POST['a'.$id])) {
$status = $_POST['a'.$id];
if(!empty($status)){
if(($status == "present" || $status == "mc")){
$attend = 1;
}
else {
$attend = 0;
}
$query = "INSERT INTO attendance(birth_no, date, status, attend)
VALUES ('$id','$date','$status','$attend')";
if($query_run = mysql_query($query)){
echo 'Insert attendance done';
}
else{
echo'Attendance not inserted.';
}
}
else{
echo 'Please enter all fields';
}
}
}
}
else {
?>
<form action="addattend.php" method = "POST">
<table>
<?php
while($row = mysql_fetch_assoc($getdata)){
$birth_no = $row['birth_no'];
$name = $row['name'];
?>
<tr>
<td><center><?php echo date("F j, Y") ?></center></td>
<td><center><?php echo $birth_no ?></center></td>
<td><center><?php echo $name ?></center></td>
<td>
<input type="radio" name="a<?php echo $birth_no; ?>" value="present">PT
<input type="radio" name="a<?php echo $birth_no; ?>" value="absent">AT
<input type="radio" name="a<?php echo $birth_no; ?>" value="mc">MC
</td>
</tr>
<?php
} // end while
?>
</table>
<center><input type="submit" name="submit" value="Submit"></center>
</form> <!-- end the form here -->
<?php
} // end else
?>
It's my first time posting a question:
I'm working on a WordPress plugin that allows the user to create rows of data in the database. I'm experiencing a problem when there are many (upwards of 100) rows of data to be updated by a form. Each row of data holds eight POST data variables, so when there are 100 rows in the form, over 800 post variables are sent. However, only a certain number of the variables update the database, right now only 112 rows update. I can't figure out what would stop the function from completing the update to the database. It almost seems like I'm overloaded with too many post variables or post data size?
Everything works perfectly with fewer entries, but once it goes over 100 rows, things stop working.
Here is my table structure:
$sql2 = "CREATE TABLE IF NOT EXISTS $item_table (
id smallint(5) NOT NULL AUTO_INCREMENT,
menu smallint(5) NOT NULL,
itemorder smallint(5) NOT NULL,
item text NOT NULL,
description text,
image tinytext NOT NULL,
value tinytext NOT NULL,
value2 tinytext NOT NULL,
UNIQUE KEY id (id)
) $charset_collate;";
}
Here is my POST data handler function:
foreach($_POST['id'] as $i){
$image = $_POST['image'][$i];
$item = $_POST['item'][$i];
$desc = $_POST['desc'][$i];
$value = $_POST['value'][$i];
$value2 = $_POST['value2'][$i];
$order = $_POST['order'][$i];
if ($_POST['strike'][$i] == 'checked' ){
$wpdb->query( $wpdb->prepare("DELETE FROM $item_table WHERE id = $i") );
}
else{
$wpdb->update( $item_table, array(
'image' => $image,
'item' => $item,
'itemorder' => $order,
'description' => $desc,
'value' => $value,
'value2' => $value2
),
array( 'id' => $i ) );
}
}
//Sort items by order, then rewrite the order with no gaps left from deleted items
$targetmenu = $_POST['targetmenu'];
$rows = "SELECT * FROM $item_table WHERE menu = $targetmenu ORDER by itemorder ASC";
$result = $wpdb->get_results($rows);
$n = 1;
foreach ($result as $r){
$id = $r->id;
$wpdb->update( $jsrm_item_table , array( 'itemorder' => $n ), array( 'id' => $id ) );
++$n;
}
$loc = "&mode=editmenu&targetmenu=".$targetmenu;
header("Location:".JSRM_SELF.$loc);
exit();
}
And here is my PHP Form:
$the_menu = $wpdb->get_row("SELECT * FROM $menu_table WHERE id = $_GET[targetmenu]");
$menuid = $the_menu->id;
$q = "SELECT * FROM $item_table WHERE menu = $menuid ORDER by itemorder ASC";
$result = $wpdb->get_results($q);
if ($result) {
?>
<form id="edit-menu-form" action="<?php echo _SELF; ?>" method="post">
<input type="hidden" name="targetmenu" value="<?php echo $menuid; ?>">
<input type="hidden" name="dbtouch" value="updateitems">
<table>
<?php
foreach ($result as $r) {
$order = $r->itemorder;
$image = $r->image;
$imagesrc = ($image) ? esc_html(stripslashes($r->image)) : 'addimage.jpg';
$item = esc_html(stripslashes( $r->item ));
$description = esc_html(stripslashes($r->description));
$value = esc_html(stripslashes($r->value));
$value2 = esc_html(stripslashes($r->value2));
$id = $r->id;
?>
<tr id="<?php echo $id ?>">
<td><?php echo $order ?></td>
<td><a class="edit-item-img" id="item-image-<?php echo $id ?>" style="background-image:url(<?php echo $imagesrc ?>);" title="Edit image"></a>
<input type="hidden" name="image[<?php echo $id ?>]" id="field-item-image-<?php echo $id ?>" value="<?php echo $image ?>" />
<img class="remove-image-button" id="image-<?php echo $id ?>" src="removeimage.png"
<?php if(!$image){ ?>
style="visibility:hidden;"
<?php } ?>
/>
</td>
<td><textarea name="item[<?php echo $id ?>]"><?php echo $item ?></textarea></td>
<td><textarea name="desc[<?php echo $id ?>]"><?php echo $description ?></textarea></td>
<td><input type="text" name="value[<?php echo $id ?>]" value="<?php echo $value ?>" /></td>
<td><input type="text" name="value2[<?php echo $id ?>]" value="<?php echo $value2 ?>" /></td>
<td><input type="checkbox" class="strike" name="strike[<?php echo $id ?>]" value="checked"/></td>
<input type="hidden" name="order[<?php echo $id ?>]" value="<?php echo $order ?>" id="order<?php echo $id ?>"/>
<input type="hidden" name="id[<?php echo $id ?>]" value="<?php echo $id ?>" id="id<?php echo $id ?>"/>
</tr>
<?php
}
?>
</table/>
<p><input type="submit" id="update-items-button" value="Update All" class="button-primary"/></p>
</form>
<?php
}
?>
I had a similar problem today. I had a form with 250+ rows and 5 variables per row, but the $_POST variable appeared to be truncated. In my case, it stopped after 1000 elements.
There is a PHP setting called max_input_vars that defaults to 1000. This setting sets an upper limit on how many variables it will pull into your PHP script. You may need to increase this value on your server settings to make your page work. There are some security implications that I don't fully understand with increasing this value that could enable a denial of service attack.
Since you are developing a Wordpress plugin, you may need to see if there are ways to change your form to reduce the number of variables you send, because you probably can't alter server configurations for people using your plugin.
Read more about the setting here: http://www.php.net/manual/en/info.configuration.php#ini.max-input-vars