Dynamicly creating and checking checkboxes in php - php

I am trying to dynamically create php check-boxes linked to an MSSQL-Database. The idea is to List every item in the table, with a check box. From there the user will be able to check the check-boxes and click submit to change the value in 1 field of the Database to "A". I have the database linked to the php and It outputs the check-checkboxes and table values, however I do not know from there how to dynamically check the check-boxes to see if they are checked, or to use it from there.

This is roughly the approach you want to take to dynamically create checkboxes. There are of course prettier ways to accomplish this (i.e. Smarty templates).
<html>
...
<form method="post" action="submit.php">
<?php
// connect to DB here
$result = mysql_query("SELECT l.id, l.name, u.checked FROM List l LEFT JOIN UserAnswers u ON l.id = u.list_id WHERE u.user_id = 5");
while ($row = mysql_fetch_assoc($result))
{
echo '<input type="checkbox" name="cb_' . $row['id'] . '" ' .
'id="cb_' . $row['id'] . '" ';
if($row['checked'])
echo 'checked';
echo " />\n"
echo '<label for="cb_' . $row['id'] . '">' . $row['name'] . "</label><br />\n";
}
?>
<input type="submit" value="Submit" />
</form>
...
</html>
submit.php is a bit trickier. When a checkbox is checked, it will set a post item. However if it's unchecked, you won't get ANYTHING back, so you need to check your database for all the items you'll be expecting.
<?php
// connect to DB here
$result = mysql_query("SELECT id, name, checked FROM things");
$answers = Array();
while ($row = mysql_fetch_assoc($result))
{
$checked = isset($_POST['cb_' + $row['id']]);
$answers[$row['id']] = $checked;
}
// update your database here using $answers
foreach ($answers as $id => $checked)
{
$query = "REPLACE INTO UserAnswers SET user_id=5, list_id=" . $id . ", checked=";
if($checked)
$query .= "1";
else
$query .= "0";
mysql_query($query);
}
This is all off the top of my head, there are better ways to do most of this. It's just a general direction. I make no guarantees about any of this. Oh and it looks quite vulnerable to SQL injection, watch out for that.

Related

How does this code to create an array in HTML accessed by PHP?

I was going through Head First PHP and came by this piece of code.
<?php
$dbc = mysqli_connect('localhost', 'root', 'atlantis2016', 'elvis_store')
or die('Error connecting to MySQL server.');
if(isset($_POST['submit']))
{
foreach ($_POST['todelete'] as $delete_id)
{
$query = "DELETE FROM email_list WHERE id = $delete_id";
mysqli_query($dbc, $query);
}
echo 'Customer removed. <br />';
}
$query = "SELECT * FROM email_list";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($result))
{
echo '<input type="checkbox" value="' . $row['id'] . '" name="todelete[]" />';
echo $row['first_name'];
echo ' ' . $row['last_name'];
echo ' ' . $row['email'];
echo '<br />';
}
mysqli_close($dbc);
?>
I fully understand how we go through all the ids present in the array todelete by using the foreach loop.
What I don't get is how the array itself is created? Are there even arrays in HTML? IF not, how are we creating a PHP array using pure HTML in the following line?
echo '<input type="checkbox" value="' . $row['id'] . '" name="todelete[]" />';
Additionally, what I also find mysterious is how only those id's for which the checkboxes have been ticked end up in the array todelete while the others are ignored?
Basically, explain the origin and functioning of the todelete array for me, please.
By defining the input name as todelete[], we are saying that this input variable todelete will send any selected checkboxes upon form submission to a PHP script by POST or GET.
The PHP script defined in the parent form 'action' attribute will be able to access values under $_REQUEST['todelete'] which will be an array structure.
This syntax is useful if we want to send multiple values associated to a variable name.
See also: HTML input arrays
The top rated answer at this link describes the inner workings of the array beautifully. It cleared up almost all of my doubts.

PHP loop generated buttons - only last one works?

First time posting, and PHP is not my strongest area, so here goes...
My code below generates a list of buttons depending on how many values are found in my DB Table, then the second piece of code is supposed to trigger when the buttons are clicked. Everything is working except that the second piece of code only works for the last button generated. Any ideas?
<?php
$username = $_SESSION['sess_user'];
$con=mysql_connect('localhost','root','root') or die(mysql_error());
mysql_select_db('user_registration') or die("cannot select DB");
$loop = mysql_query("SELECT * FROM `vaults` WHERE username = '$username' ORDER BY vaultname asc") or die ('Error Getting User Data! <br />' .mysql_error());
$chk = mysql_num_rows($loop);
$myvalue = '';
while ($row = mysql_fetch_assoc($loop)) {
$myvalue = "{$row['vaultname']}";
echo '<form method="post"><input class="text-center" type="submit" name=' . $myvalue . ' value=' . $myvalue . ' id="vaultSelecter"></form>';
}
?>
<?php
if(isset($_POST[$myvalue])){
echo '<script type="text/javascript">window.onload = function() { document.getElementById("instructions").innerHTML = " HELLO WORLD! "; }</script>';}
?>
Thank you all for your replies, I appreciate it. I understand what everyone is saying, but the ID I reference in my getELementByID() is a separate DIV from the buttons, I want to change the content of the single DIV with the ID "instructions", when any of the buttons are clicked, but it only works for the last button created by the loop. Is that still due to the way I have my buttons ID'd?
For example say the above loop creates three buttons, I want each button to change the contents of the following DIV with "Hello Word".
<div id=instructions>
replace this text
</div>
I am guessing I have to store each of the $myvalues created by the loop into an array, so that each value can be assigned separately to each button, I just have no idea how to do that.
You're duplicating IDs in this line:
echo '<form method="post"><input class="text-center" type="submit" name=' . $myvalue . ' value=' . $myvalue . ' id="vaultSelecter"></form>';
and IDs must be unique. Try classes instead. Ex:
var elems = document.getElementsByClassName("text-center");
for (var i = 0; i < elems.length; i++) {
console.log('x')
elems[i].addEventListener('click', function () {
alert('hello');
}, false);
}
You're assigning multiple inputs to the same id, assign them to a class instead since id's have to be unique.
You're also making a form for every button, which seems kind of pointless to me, try this instead:
echo '<form method="post">';
while ($row = mysql_fetch_assoc($loop)) {
$myvalue = "{$row['vaultname']}";
echo '<input class="text-center vaultSelecter" type="submit" name=' . $myvalue . ' value=' . $myvalue . '>';
}
echo '</form>';
The id called vaultSelector is now a class, so can be accessed via getElementByClassName()
Instead of this:
name=' . $myvalue . ' value=' . $myvalue . ' id="vaultSelecter"
Maybe try
name="' . $myvalue . '" value=' . $myvalue . ' id="' . $myvalue . '"
In my opinion it is best to uniquely identify any elements that will be used as a programming element.
Just another piece of unsoliciated opinion. If you can put everything in one form it may make things easier. So when the button submits set a hidden field and continue with the form submit.

What is wrong with my code? Data is not deleted from database

I've updated the code but keep getting new errors.
I'm really hoping that someone can help me and look at my code to see what is wrong.
I have a database table on a webpage and I have one edit button and one delete button on each table row. At the moment I'm just trying to get the delete button to work and it will just not delete the row in the database even though I selected that ID. It looks like it's picking up the correct ID.
Can someone tell what is wrong? Below is the code...
<?php
require 'connect.inc.php';
if (isset($_POST['delete']) && isset($_POST['id'])) {
$id = get_post('id');
$query = "DELETE FROM movies WHERE id='.$id.' LIMIT 1";
if (!mysql_query($query, $db_server))
echo "DELETE failed: $query<br>".
mysql_error() . "<br><br>";
}
$query = "SELECT * FROM movies, categories WHERE movies.genre_id = categories.genre_id";
$result = mysql_query($query);
if (!$result) die ("Database access failed:" .mysql_error()) ;
$rows = mysql_num_rows($result);
echo '<table><tr><th>Title</th><th>Release year</th><th>Genre</th><th>Director</th><th>Update</th><th>Delete</th></tr>';
for ($j = 0 ; $j < $rows ; ++$j) {
$row = mysql_fetch_row($result);
//$id = $row[0];
echo '<tr><td>' .$row[1] . '</td>' ;
echo '<td>' .$row[2] . '</td>' ;
echo '<td>' .$row[3] . '</td>' ;
echo '<td>' .$row[4] . '</td>' ;
echo '<td>'."<a href='edit_movie.php?edit=" . $row[0] . "'>Edit</a>".'</td>';
echo '<td><form action="index.php" method="POST">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="id" value="'. $row[0] .'" />
<input type="submit" value="Delete" /></form>
</td></tr>' ;
}
echo '</table>';
include 'add_movie.php';
?>
You forget to close action attribute.
You have echo '<td><form action="index.php method="POST"> change it to
echo '<td><form action="index.php" method="POST">
Just to be clear: 'mysql_query' and accompanying commands is deprecated and should really not be used. The OP however stated that it was required for an assignment. The easiest way to replace them is to use 'mysqli_*' instead. For an example using parameter binding to avoid sql-injection:
http://www.php.net/manual/en/mysqli-stmt.bind-param.php
Shouldn't it be:
if (isset($_POST['delete']) && isset($_POST['id'])) {
$id = mysql_real_escape_string($_POST['id']);
...
See this link for some info on 'get_post':
PHP: Having a problem with get_post
The problem there was that the function 'get_post' was defined on the next page of the course literature, wich the asker hadn't noticed.
The variable $_POST['id'] contains the id-value sent from a form via an HTTP POST-request. You check if that value is set, and then you should assign it to '$id' like i wrote.
Your delete sql has wrong quotes
$query = "DELETE FROM movies WHERE id='.$id.' LIMIT 1";
change to either
$query = "DELETE FROM movies WHERE id=".$id." LIMIT 1";
or
$query = "DELETE FROM movies WHERE id=$id LIMIT 1";
Try changing the form action
'<td><form action="index.php" method="POST">
Also check your database connection is properly established
Perhaps this might help for get_post
PHP: Having a problem with get_post

Display checkbox values in HTML after select, submit and email results from process.php

I have a checklist that's broken down into days, stage, timeShow, and bandName. I am displaying the options from a database with this script and I'm trying to display the results (and eventually email them) to the user on the 'process' page. How do I carry over the $result_x to the following page?
Here's an example of one of the 'blocks' for Saturday, Stage 1 and the value of the selection is the 'ID' of the row.
UPDATE- Part one is solved. Now looking to get the results sent to an email address input by the user.
FORM SOLUTION- 'Selection.php'
$sql_Sat1 = "SELECT * FROM bandSched WHERE day='saturday' AND stage='stage 1'";
mysql_query($sql_Sat1);
$result_Sat1 = mysql_query($sql_Sat1);
while($row = mysql_fetch_array($result_Sat1))
{
echo "<ul><li>";
echo'<input type="checkbox" name="id[]" value="'.$row['id'].' " id="bandSched_' . $row['id'] . '" />';
echo '<label for="bandSched_' . $row['id'] . '">' . $row['timeShow']." ".$row['bandName'] . '</label>';
echo "</li></ul>";
}
SOLUTION- 'process.php'
if ( ! empty($_POST['id']))
{ foreach($_POST['id'] as $key => $id) { $_POST['id'][$key] = mysql_real_escape_string($_POST['id'][$key]); }
$in = implode(', ', $_POST['id']);
$sql_Sat2 = "SELECT * FROM bandSched WHERE id IN ($in) ORDER BY FIELD(id, $in)";
$result = mysql_query($sql_Sat2) or die('MySQL Error ' . mysql_errno() . ': ' . mysql_error());
}
if ( ! isset($result))
{
echo 'You did not select anything';
}
else
{
while ($row=mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>". $row['timeShow'] ."</td><td>" . $row['bandName'] . "</td>";
echo "</tr>";
}
}
Unless you have the attribute checked="checked" in your <input type="checkbox" />, the value will not be sent with the form data.
Try this:
echo '<input type="checkbox" value="' . $row['id'] .'"name="selected" checked="checked" />';
Does this solve the problem?
Carrying data from page to page can either be done with Sessions, Cookies, or posting hidden form elements containing the data.
Sessions provide you the data, but you still need to make a valid query. The only thing that sessions do are store data on the server. They do not keep any of the program execution, variables, etc.
Your error message is telling you that mysql_fetch_array was not supplied a MYSQL result resource (and it wasn't you supplied it an integer of the id value). The query will not be remembered across the session.
Also, mysql_* is deprecated, use PDO or mysqli.

PHP checkbox problem

I am going nuts here, I have an array of checkboxes from a form that I am trying to $_POST with PHP. EVERYTHING on my form posts fine except the check boxes. The checkboxes DO post, but in the wrong order. For instance when I want checkbox[0] and checkbox[2] I actually get checkbox[0] and checkbox[1].
I have tried many different ways to get the value of the checkbox, including isset but I still have the same problem. I just need the checkbox value of on to be stored in my database if the checkbox is indeed checked.
My code is below. $in_production is the checkbox. I can provide the code that generates the checkbox too if it is needed.
Thanks in advance.
if ($_GET['action'] == 'Edit_Product'){
include("../dbinfo.php");
$q_id = $_GET['q_id'];
for ($i = 0; $i < count($_POST['p_id']); $i++){
$result = mysql_query('SELECT * FROM products WHERE q_id = '.$q_id);
$num = mysql_num_rows($result);
$p_id = ($_POST['p_id'][$i]);
$in_production = ($_POST['in_production'][$i]);
$p_name = ($_POST['p_name'][$i]);
$p_price = ($_POST['p_price'][$i]);
$p_name_conflict = FALSE;
for ($ii = 0; $ii < $num; $ii++){
$row = mysql_fetch_array($result);
$p_name_conflict_check = $row['p_name'];
$p_id_conflict_check = $row['p_id'];
if($p_name_conflict_check == $p_name &&
$p_id_conflict_check != $p_id){
$p_name_conflict = TRUE;
}
}
if ($p_name_conflict == FALSE){
$query = "UPDATE products SET p_name='$p_name',
p_price='$p_price', in_production='$in_production',
last_modified=CURDATE() WHERE p_id = '$p_id'";
mysql_query($query);
}
else{
$update_failures =+1;
}
}
mysql_close($link);
if($update_failures == 0){
header("Location: Products_Updated.html");
}
elseif ($update_failures != 0){
header("Location: Products_Exist.php?update_failures=".$update_failures);
}
}
P.S. I don't know why but the code block icons are not present on SO right now... so my code is not all pretty. Also, I know my code is horribly inefficient, but I am just trying to get this working right now, then fine tune later. I am open to efficiency suggestions as well, but that is not my primary objective with this question.
EDIT: Here is the form from the HTML...
<form id="form" name="form" method="post" action="/Management/Products/Product_Management.php?action=Edit_Product&q_id=<?php echo "$q_id" ?>">
<?php
include("../dbinfo.php");
$result = mysql_query('SELECT * FROM products WHERE q_id =' . $q_id);
$num = mysql_num_rows($result);
mysql_close($link);
for ($i = 0; $i < $num; $i++){
$row = mysql_fetch_array($result);
$p_id = $row['p_id'];
$p_name = $row['p_name'];
$p_price = $row['p_price'];
$in_production = $row['in_production'];
$date_added = $row['date_added'];
$last_modified = $row['last_modified'];
if($in_production == 'on'){
$checked = 'checked';
}
else{
$checked = '';
}
echo "<div>Product ID# " . $p_id . "<label style=\"font-style:italic\"> (Originally added on " . $date_added . ", last modified on " . $last_modified . ")</label></div><br/>";
echo "<input id=\"p_id" . $p_id . "\" class=\"text\" type=\"hidden\" name=\"p_id[]\" value=\"" . $p_id . "\"/>";
echo "<label>Product Name *</label><br/>";
echo "<div><label style=\"font-style:italic\">(Product still in production <input type=\"checkbox\" name=\"in_production[]\"" . $checked . " style=\"width:15px\"/>)</label></div>";
echo "<input id=\"p_name" . $p_id . "\" class=\"text\" type=\"text\" name=\"p_name[]\" maxlength=\"20\" onfocus=\"on_focus(this)\" onblur=\"on_blur(this)\" value=\"" . $p_name . "\"/><br/><br/>";
echo "<label>Product Price *</label><br/>";
echo "<div><label style=\"font-style:italic\">(Without taxes)</label></div>";
echo "<input id=\"p_price" . $p_id . "\" class=\"text\" type=\"text\" name=\"p_price[]\" maxlength=\"6\" onkeypress=\"return currency(this, event)\" onchange=\"currency_format(this)\" onfocus=\"on_focus(this)\" onblur=\"on_blur(this)\" value=\"" . $p_price . "\"/><br/><br/><br/><br/>";
}
?>
<input class="button" type="button" value="Submit" onclick="product_edit_form_check()"/><br/><br/>
</form>
It would be helpful if you could post some of the HTML-part so we could see how you create your form. It seems you're generating your checkboxes without indexes in your array, so all checkboxes have the name/id "checkbox[]", which is ok if you don't care about the index, but if posted, the array will be numbered starting from "0" and then counting up which is the reason why you'll get "0" and "1" posted, even if "0" and "2" were checked.
Try to give your checkboxes' name/id numbers when generating the HTML, like "checkbox[0]", "checkbox[1]", "checkbox[2]", and so on. So when checkbox 0 and 2 are checked, you should get those values (including the correct index) posted.
The thing you have to bear in mind with HTML checkboxes is that they only POST a value if they are checked. If they are not checked, they don't get posted.
With this in mind, you should give each checkbox a name and then test for it in the POST to detect whether or not it has been passed back.
if (isset($_POST['MyCheckbox'])) {
} // else it wasn't checked!
Show us the HTML for the checkboxes.
Also, you have an SQL injection attack waiting to happen - a user can get any SQL they like onto the end of your query. Something like this illustrates what you should do with untrusted data:
//we're expect a number, so ensure we get one
$q_id = intval($_GET['q_id']);
//get into the habit of quoting query params,
//or better yet, use a wrapper library to help you
$sql="select * from products where q_id='".mysql_real_escape_string($q_id)."'";
If you declare checkbox name like (p_id[]), it's like telling PHP "I'm adding element to an array, enumerate it for me". Like in php $array[] = 't'; If you have several form elements with different names and you want to have synchronised IDs you HAVE to add index because otherwise browser will/may send only selected ones and PHP will enumerate it continuously.
You can specify indexes by using p_id[INDEX] and so on, where index is anything (I suggest numeric or alphanumeric).
Also, checkbox value can be altered and I encourage you to do it. value="1" helps, then you're sure that you get it.
<input type="checkbox" name="p_id[0]" value="1" />
In PHP you'll receive
$_POST['p_id'] ===> array(0 => 1);
et caetera.

Categories