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){
Related
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.
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.
I have a table with rows that are in the form:
ID, Name, First Name, IntA, IntB, IntC, ...
The last columns are textfields.
I want to select multiple rows with a Checkbox and send the ID and the recorded integers with POST to another PHP-File.
This is my code-example (with a little bit German in it):
echo "<td><input type='checkbox' name='auswahl[]' value='$daten[0]'></td>";
echo "<td>" . $daten['ID'] . "</td>";
echo "<td><input type='number' name='Schr' value='".$punkte['PktSchr']."'></td>";
echo "<td><input type='number' name='Mdl' value='".$punkte['PktMdl']."'></td>";
So in the other PHP-File I want to SQL for all checked rows like this (in a Loop):
$Eintraege = $_POST['auswahl'];
$Schr = $_POST['Schr'];
$Mdl = $_POST['Mdl'];
foreach ($Eintraege as $i){
$sql = "INSERT INTO aufnahme (IDSchueler, PktSchr, PktMdl) Values ('$i', '$Schr', '$Mdl')";
}
My problem is this: $Eintraege contains only the IDs of the selected rows (because of value='$daten[0]').
$Schr and $Mdl contains the values of the textfields of the last row (doesn't matter, wich rows are selected).
So I tried to set value='$daten' and use it lika an array, but then I get an Exception.
I think I have to change value='$daten[0]', but don't know how.
Thanks for your help!
Change two other names to array type too and you will get all values.
So do like below:-
echo "<td><input type='number' name='Schr[]' value='".$punkte['PktSchr']."'></td>";
echo "<td><input type='number' name='Mdl[]' value='".$punkte['PktMdl']."'></td>";
And then you can do like below:-
foreach ($Eintraege as $k=> $i){
$sql = "INSERT INTO aufnahme (IDSchueler, PktSchr, PktMdl) Values ('$i', '$Schr[$k]', '$Mdl[$k]')";
}
As #Alive-to-Die mentioned, turn the names into arrays.
<input type='checkbox' name='auswahl[]' value='$daten[0]'>
This itself doesn't look good. Consider making it
<input type='checkbox' name='auswahl[]' value='{$daten[0]}'>
or
<input type='checkbox' name='auswahl[]' value='".$daten[0]."'>
These are two proper ways to use variables inside strings.
I am doing a query and populating buttons with the results:
$query="select name from members where active=1 order by name";
If I do a simple:
while($row = $rs->fetch_assoc()) {
echo $row['name']."<br>;
}
I get a list:
Mary123
JOE
Robert Tables
However if I :
<table>
$column = 0;
while($row = $rs->fetch_assoc()) {
if ($column == 0) {
echo "<tr>";
}
echo "<td class='cellnopad'><input type='submit' class='submitbtn' name='name' value=".$row['name']."> </td>";
$column++;
if ($column >= 5) {echo "</tr>";
$row++;
$column=0;
}
}
echo "</table>";
My buttons look like
Mary123
JOE
Robert
As you can see the name Tables gets dropped from the name and only the value of Robert is shown.
I initially thought the name wasn't being displayed due to the size of the text versus button size, but I have proved that is not the case by removing the CSS and checking the $_POST value on individuals.php. Also,if I change the name in the database to Robert_Tables it works fine.
Is there something I am doing wrong? What do I need to change to get the value to show both words and the space?
Your problem relies on the fact that you forgot to quote the value parameter of the input with quotes ''. See here you have:
value=".$row['name'].">
when it should instead be:
value='".$row['name']."'>
And that is breaking your generated html markup, see simple snippet below on how the output is handled when you omit the quotes:
<input type='submit' class='submitbtn' name='name' value=asd asd>
<input type='submit' class='submitbtn' name='name' value="asd asd">
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.