Get the ID of the selected check box - php

I am currently working on a php and MySQL application. In my application I load a table from MySQL and I display it in my Website. The table consists of the columns (ID,Name,SurName). When I load the table I also create another column which consists of different checkboxes. My source code for the creation of the table is the following:
function user_clients_table() {
$con = mysql_connect("localhost","root",'');
if(!$con){
die("Cannot Connect" . mysql_error());
}
mysql_select_db("client_app",$con);
$get_user_clients = "SELECT `ID`,`Name`,`SurName` FROM `clients` ";
$clients = mysql_query($get_user_clients,$con);
echo "<table border=2>
<tr>
<th>Client</th>
<th>Name</th>
<th>SurName</th>
<th>Receive Message</th>
</tr>";
while($record = mysql_fetch_array($clients)){
echo "<form action=pushnotification.php method=post>";
echo "<tr>";
echo "<td>".$record['ID']." </td>";
echo "<td>".$record['Name']." </td>";
echo "<td>".$record['SurName']." </td>";
echo "<td>"."<input type=checkbox name= checkbox[".$record['ID']."] "."</td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysql_close();
}
The table looks Lke that in the Website:
What i want to do is to echo the client id from the first column of the table if the checkbox of the client isset after i click the send button on the website. For example if the top checkbox isset i want to echo "1" , if the checkbox in the third row is checked i want to echo "3".
I ve done this so far:
if (isset($_POST['checkbox']))
{
foreach ($_POST['checkbox'] as $key => $value)
{
$receivemsg = $key;
}
echo '<span style="color:#AFA;text-align:center;">'.$receivemsg.'</span>';
}
But it works only for the first checkbox the other ones are not working.
Can someone please help me to do this?
Thanks in Regards

(In HTML, you put the attributes in "", like type="checkbox". Use '' for your tags, so you can use "" for the attributes. You are also missing a " />" at the end of your input tag.)
With the isset you actually check only the first one. Remove it, with foreach, you don't need it anyway, as it loops through the checked checkboxes (if you send them from HTML as an array). If none of the checkboxes are selected, the loop will run 0 times anyway.
foreach ($_POST['checkbox'] as $key => $value)
{
$receivemsg = $key;
}
If you write it this way, it will only save the very last checked checkbox. Maybe you want
foreach ($_POST['checkbox'] as $key => $value)
{
$receivemsg[] = $key;
}
And of course, injection, mysqli, and others what has been mentioned in the comments.
(Personally I find it kind of strange that if checkboxes are sent as an array, isset doesn't work on them anymore. Or to be more precise, it works on them as elements of the array.)
As #Johannes said, you also declare a form for each checkbox.

Related

Updating data in MySQL database based on checked dynamic checkboxes in the table

I'm sorry about my question, but I'm starting with PHP and I want to ask you for a help with my problem.
In my web application I work with a table, which has a dynamic count of rows based on the number of rows in a source table in MySQL database. In the application should be a checkbox in each row of the table. After clicking on the submitt button there should be update of records in the source table and it should be update just of these records where the checkboxes were checked.
The table in the application looks simillar like in the picture.
The primary key in the source table is in the column NUMBER. As a first try I simulated that after clicking on submitt button there will be shown the msgbox with the values from the column NUMBER for the rows, where the checkboxes were checked.
<html>
<head>
<title>APLICATIONa</title>
<script type="text/javascript">
function GetSelected() {
//Reference the Table.
var grid = document.getElementById("Table");
//Reference the CheckBoxes in Table.
var checkBoxes = grid.getElementsByTagName("INPUT");
var message = "\n";
//Loop through the CheckBoxes.
for (var i = 0; i < checkBoxes.length; i++) {
if (checkBoxes[i].checked) {
var row = checkBoxes[i].parentNode.parentNode;
message += " " + row.cells[1].innerHTML;
message += "\n";
}
}
//Display selected Row data in Alert Box.
alert(message);
}
</script>
</head>
<body>
<?php
$values = mysql_query("SELECT * FROM table_03_2020");
echo "<br><form action='main.php' method='POST'>";
echo "<input type='submit' name='button' value='Get Selected' class='btn btn-primary' onclick='GetSelected()' />";
echo "<table id = 'Table' border='0px' bordercolor='silver' cellpadding='1' cellspacing='2' width='100%'>";
echo "<tr bgcolor='#EEEEEE' height='45px'><th></th><th><b>NUMBER</b></th><th><b>NAME</b></th></tr>";
while ($zaznam=MySQL_Fetch_Array($values)):
echo "<tr onmouseover=\"highlight_row(this, 1, '#F2F2F2');\" onmouseout=\"highlight_row(this, 0, '#F2F2F2');\">";
echo "<td><input type='checkbox' name='cbox[]' ></td>";
echo "<td><font color='red'>".$zaznam["number"]."</font></td>";
echo "<td>".$zaznam["name"]."</td>";
echo "</tr>";
endwhile;
echo "</table><br>";
echo "</form>";
?>
</body>
</html>
The msgbox is just an illustration. Instead of msgbox, I need that after clicking on the submit button, there should be an update for these records in the source table, where the checkboxes were selected (so of these records, which are now shown in the msgbox). So I need something like:
"UPDATE table_03_2020 SET column1 = 'xy' where NUMBER in ('values of NUMBER from rows, where the checkbox was checked)"
There'll be also a second submit button and after clicking on it, there should be another different update. So after clicking on the second button, I need something like:
"UPDATE table_03_2020 SET column1 = 'ab' where NUMBER in ('values of NUMBER from rows, where the checkbox was checked)"
I'm sorry if my question is not so clear, but I'd really appreciate any help.
Thank you very much.
Add key values with the number to the cbox form variable:
echo "<td><input type='checkbox' name='cbox[" .$zaznam["number"]. "]' ></td>";
Then use the following PHP to get the number list.
if (isset($_POST["cbox"])) {
$checked = array();
foreach($_POST["cbox"] as $number => $val) {
$checked[] = addslashes($number);
}
$checked_list = implode(",", $checked);
}
The addslashes function is for SQL Injection protection.
This will create a list with comma separated numbers.
Than, you can insert it in the the SQL query.
UPDATE table_03_2020 SET column1 = 'xy' where NUMBER in ('. $checked_list .')
If you assign a value to the checkboxes, like this:
<input type='checkbox' name='cbox[]' value='{$zaznam["number"]}' >
When the form is submitted the cbox variable will contain an array of these numbers, which means that you can process them like this:
<?php
include 'db.php'; #your database connection!!!
$sql='update table_03_2020 set `column1`="XY" where `column2` in ( ? )';
$stmt=$db->prepare( $sql );
$ids=implode(',',$_POST['cbox']);
$stmt->bind_param('s',$ids);
$stmt->execute();
?>
Note that the above has not been tested so there might be errors but I hope it'll give the idea.
Thank you, I tried to improve the part of the code to:
echo "<input type='submit' name='buttonupdate' value='Get Selected' >";
echo "<table id = 'Table' border='0px' bordercolor='silver' cellpadding='1' cellspacing='2' width='100%'>";
echo "<tr bgcolor='#EEEEEE' height='45px'><th></th><th><b>NUMBER</b></th><th><b>NAME</b></th></tr>";
while ($zaznam=MySQL_Fetch_Array($values)):
echo "<tr onmouseover=\"highlight_row(this, 1, '#F2F2F2');\" onmouseout=\"highlight_row(this, 0, '#F2F2F2');\">";
if ($_POST["buttonupdate"]) {
if (isset($_POST["cbox"])) {
$checked = array();
foreach($_POST["cbox"] as $number => $val) {
$checked[] = addslashes($number);
}
$checked_list = implode(",", $checked);
}
}
echo "<td><input type='checkbox' name='cbox[" .$zaznam["cflot"]. "]' ></td>";
It didn't work, there was no update. Did I edited the code incorrectly?
Actually I forgot to mention the second button, so I edited my first post. Would it be possible to distinguish between the first and the second button? Thank you very much for any help.

Get the values of the ticked checkboxes in php

I am currently building a web application. In my application, a load some data from mysql and I display them as a table in my website. Additionally I add another column that consists of different checkboxes. My source code of displaying the table is called by a function that is located in another page. The source code odf the function is the following :
function user_clients_table() {
$con = mysql_connect("localhost","root",'');
if(!$con){
die("Cannot Connect" . mysql_error());
}
mysql_select_db("client_app",$con);
$get_user_clients = "SELECT `ID`,`Name`,`SurName` FROM `clients` ";
$clients = mysql_query($get_user_clients,$con);
echo "<table border=2>
<tr>
<th>ID</th>
<th>Name</th>
<th>SurName</th>
<th>Receive Message</th>
</tr>";
while($record = mysql_fetch_array($clients)){
echo "<form action=pushnotification.php method=post>";
echo "<tr>";
echo "<td>".$record['ID']." </td>";
echo "<td>".$record['Name']." </td>";
echo "<td>".$record['SurName']." </td>";
echo "<td>"."<input type=checkbox name=checkbox[] value=".$record['ID']." />". "</td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysql_close();
}
The function works fine, after i call the function my webpage looks like this:
I want next to display the client number whose check box has been checked after i click the button send. For example if i checked only the first check box and submit it, i want to echo the client id that matches thsi checkbox, in this case i will echo '2'. My approach to this is the following:
if(isset($_POST['send'])){
if(!empty($_POST['checkbox'])) {
// Counting number of checked checkboxes.
$checked_count = count($_POST['checkbox']);
echo "You have selected following ".$checked_count." option(s): <br/>";
// Loop to store and display values of individual checked checkbox.
foreach($_POST['checkbox'] as $selected) {
echo "<p>".$selected ."</p>";
}
echo "<br/><b>Note :</b> <span>Similarily, You Can Also Perform CRUD Operations using These Selected Values.</span>";
}
else{
echo "<b>Please Select Atleast One Option.</b>";
}
}
It works but only for the first checkbox, if I select the other checkboxes without the first one I doesn't display anything.
Can someone please help me?
Thanks in Regards
Each checkbox is in it's own form, so when you are submitting you are submitting the first form (the first checkbox), and that is why you are getting the current action. Put the form tags outside the loop

PHP MySQL save a row id to a database based on user checkbox

I am attempting to get the sql row that a user checks with a checkbox and post the id to a script that will save the users selected rows to a db so they can pull "saved" rows at a later data.
Below is my code -- the issue is when I post the checkbox value it is appearing as "1" and I am not sure why this is happening. All checkbox values are appearing as "1".
require('./wp-blog-header.php');
$current_user = wp_get_current_user();
$school = $_POST['school'];
$connection = mysql_connect('198.71.225.63:3306', 'newmslsuper', '');
mysql_select_db('msl_data');
$query = "INSERT INTO searches (ID, school, type) VALUES('$current_user->ID', '$school', '1')";
mysql_query($query);
$search = mysql_query("SELECT * FROM `data` WHERE `school` LIKE '%$school%'");
$count=mysql_num_rows($search);
if ($count==0) {
echo 'Sorry your search for'; echo " $school "; echo 'returned no results. Please try again.';
}
else {
$fields_num1 = mysql_num_fields($search);
echo "<form action='save.php' method='post'>";
echo "<p>Check the box next to a Scholarship you would like to save and hit the SAVE button.<p/><table><tr><th>Save Search</th>";
// printing table headers
for($i=0; $i<$fields_num1; $i++)
{
$field1 = mysql_fetch_field($search);
echo "<th>{$field1->name}</th>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_array($search)){
foreach($row as $rowarray)
while($row1 = mysql_fetch_row($search)){
echo "<tr>";
echo "<td><input type='checkbox' value='$rowarray' name='cell'></td>";
// $row is array... foreach( .. ) puts every element
// of $row1 to $cell1 variable
foreach($row1 as $cell1)
echo "<td>$cell1</td>";
echo "</tr>\n";
}
}
}
echo "<input type='submit' value='SAVE'>";
mysql_close(); //Make sure to close out the database connection
Your checkboxes should be as array as they are multiple. The reason why you get them all as 1 as they override each other.
<form method='post' id='form' action='page.php'>
<input type='checkbox' name='checkboxvar[]' value='Option One'>1
<input type='checkbox' name='checkboxvar[]' value='Option Two'>2
<input type='checkbox' name='checkboxvar[]' value='Option Three'>3
<input type='submit'>
</form>
<?php
if(isset($_POST['submit']){
$v = $_POST['checkboxvar'];
foreach ($v as $key=>$value) {
echo "Checkbox: ".$value."<br />";
}
}
?>
TBH, this thing was a mess. The base of your problem was a) only having a single named element (as the other answer pointed out) and b) trying to give it an array as a value. But even after fixing that this was never going to work.
You had your database results inside four separate loops, I don't know what the thinking was there. As well, if you presented me with this web page, I could easily erase your entire database with a single click.
Here's what it looks like after 5 minutes of work. I'd still not call this a reasonable script, but hopefully it will give you something to learn from. You need to make a priority to learn about preventing SQL injection, and the first way to do this is to stop using a database engine that's been unsupported for 5 years. PDO is the easiest alternative as it's built into PHP for nearly a decade now. It provides convenient methods for dumping a result set into an array easily.
<html>
<head>
<link rel="stylesheet" type="text/css" href="results.css">
</head>
</html>
<?php
require('./wp-blog-header.php');
$current_user = wp_get_current_user();
$school = $_POST['school'];
$db = new PDO("mysql:host=198.71.225.63;dbname=msl_data", "newmslsuper", "");
$stmt = $db->prepare("INSERT INTO searches (ID, school, type) VALUES(?,?,?)";
$stmt->execute(array($current_user->ID, $school, 1));
$stmt = $db->prepare("SELECT * FROM `data` WHERE `school` LIKE ?");
$stmt->execute(array("%$school%"));
// put it in an array. presto!
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (count($result) === 0) {
echo "Sorry your search for '$school' returned no results. Please try again.";
}
else {
$fields = array_keys($result[0]);
echo "<form action='save.php' method='post'>";
echo "<p>Check the box next to a Scholarship you would like to save and hit the SAVE button.<p/><table><tr><th>Save Search</th>";
// assume "id" field is first
unset($fields[0]);
// printing table headers
foreach($fields as $field) {
echo "<th>$key</th>";
}
echo "</tr>\n";
// printing table rows
// just one loop
foreach($result as $row) {
echo "<tr>";
// assume the column is named "id"
echo "<td><input type='checkbox' value='$row[id]' name='cell[]'></td>";
unset($row["id"]);
foreach($row as $cell) {
echo "<td>$cell</td>";
}
echo "</tr>\n";
}
echo "<input type='submit' value='SAVE'>";
echo "</form>";
}
?>

Checkbox looping in php while posting to database

I am building at the moment an achievement system that works on the foundation of checkboxes (since its not post related) However, I bumped into a problem, and I cant seem to wrap my head arround it, since I am not that handy with loops and Arrays.
Okay, So I made group of checkboxes, that are posted on this page and filled appropiately, as see the code below that helps me fill that part of the page.
function MakeProfessionlist(){
$result = LoadListProffesion();
$i = 0;
echo '<table class="Overview">';
while($row = mysqli_fetch_array($result)){
$i++;
if(($i % 2) == 0){
echo "<td class='small'><td><input id='achievementHidden' type='hidden' value='0' name='IsChecked[]'>";
echo "<input type='checkbox' id='achievement' name='IsChecked[]' value = '1'>";
echo "<input name='AchievementId[]' type='hidden' value='".$row['AchievementId']."'></td>";
echo "<td class='big'>".$row["AchievementName"]."</td></tr>";
}else{
echo "<tr><td class='small'><input id='achievementHidden' type='hidden' value='0' name='IsChecked[]'>";
echo "<input type='checkbox'id='achievement' name='IsChecked[]' value = '1'>" ;
echo "<input name='AchievementId[]' type='hidden' value='".$row['AchievementId']."'></td>";
echo "<td class='big'>".$row["AchievementName"]."</td>";
}
}
echo '</table>';
}
As you see, i try to shoot through 2 variables, namely the AchievementId, and the IsChecked value (can be either 0 or 1)The problem occurs when I am going to save this information. I set up a table within the database that acts as mediator (The Achievement_User, with just 3 entries, which are UserId, AchievementId and the IsChecked Value)
My start was that I shoot through all the achievements that come through here with the AchievementId's that are posted together with the checkbox through the code down below.
if(isset($_POST['AchievementSaveData']))
{
// print_r($_POST);
$checkbox = isset($_POST['IsChecked']) ? $_POST['IsChecked'] : array();
$Achievement = isset($_POST['AchievementId']) ? $_POST['AchievementId'] : array();
foreach (array_combine($checkbox, $Achievement) as $IsChecked => $AchievementId){
$sql="SELECT * FROM Achievement_User WHERE UserId='".$UserId."' AND AchievementId ='".$AchievementId."'" ;
$result=mysqli_query($sql);
$count=mysqli_num_rows($result);
if ($count==1){
echo 'Update datarow with UserID '.$UserId.', AchievementId '. $AchievementId.' and with a value of '.$IsChecked;' <br>';
}
else{
echo 'Create datarow with UserID '.$UserId.', AchievementId '. $AchievementId.' and with a value of '.$IsChecked.' <br>';
}
}
}
Now the problem lies in the fact that when I check a checkbox, appearantly the Array gets increased. Instead of the 40 entrees it makes (which is how many AchievementId's are posted, and when checked everything off is the default) it creates an extra array space for each checked value, which makes my comparison useless, cause i get an error then that the arrays can be combined.
Is there any way I can work arround it what would make my array of AchievementId's match up with my IsChecked Value?
Edit: Next to that, the whole foreach loop doesn't seem to work anymore when I tried to merge the arrays (even if they match in values). So my thought here is maybe is there a way I can post the array from IsChecked with already the value of the AchievementId attached to it. If that is so, how could I work this out?
why don't you just give the checkbox the value of the achievement and get rid of the hidden input
<input type='checkbox' id='achievement' name='IsChecked[]' value = '<?php echo $row['AchievementId'];?>'>
then in the php
foreach ($IsChecked as $AchievementId){

Deletion of rows from populated table

I'm currently facing a strange issue whereby I did not get any errors from my debugging page. My table consists of several rows and only the first row of the table can't be deleted.
Sample form:
$DB = new PDO('sqlite:database/Sample.db');
$result = $DB->query("select * from staff");
foreach ($result as $row)
{
$StaffNo= $row['StaffNo'];
$Name= $row['Name'];
$TelNo= $row ['TelNo'];
echo "<tr>";
//Go to remove.php to remove
echo "<form action=\"Remove.php\" method=\"post\">";
echo "<input type=\"hidden\" name=\"StaffNo\" value=\"$StaffNo\">";
echo "<input type=\"submit\" onclick=\"return confirm('Yes/No')\"/>";
echo "</form>";
echo "</td>";
echo '<td data-column-name="Name" char="data">'.$Name.'</td>';
echo '<td data-column-name="TelNo" char="data">'.$TelNo.'</td>';
</tr>
}
Remove.php:
$StaffNo= $_POST["StaffNo"];
$DB = new PDO('sqlite:database/Sample.db');
$DB->query("DELETE FROM Staff WHERE StaffNo=".$StaffNo);
#header("location:view.php");
From my code above, I can delete all my sample records except for the first row. It doesn't get deleted... Kindly advise if i did wrong somewhere....
I've tried your code and apart from the broken table code, everything seems fine. Make sure your table is correct (<table><tr><td>Content</td></tr></table>). In your question, you're missing an opening <td> on line 9 of the first file, as well as missing <table> tags. Some browsers don't handle broken tables very well and that might mess up your form.
Your query will also break if $StaffNo is an empty string, so double check that.
You can also try removing the header() call and print out errors using $DB->errorInfo().
To inject your variable i the hidden field you should type
".$StaffNo."
instead of
"$StaffNo".
probably it doesn't delete the first row of your table becouse it's the only one with a StaffNo defined.

Categories