PHP Repeating Region and Checkboxes - php

--Edited for clarity.
Database:
tblModule, contains a list of modules that can be enabled or disabled.
tblData, contains a list of trusts and the modules they have enabled. This links to tblModule on tblData.M01 = tblModule.mod_key
The PHP page is accessed from an index page and passes a variable lstModTrust to this page, to limit the returned records from tblData for a single trust. tblData.trust_key
A query runs, qryModuleList which returns a list of all modules. This is used to generate a table of all available modules. Each row shows module name tblModules.mod_name, module code tblModules.mod_code and a checkbox.
qryModData will return a list of the modules that are enabled for a single trust, and the corresponding checkboxes need to be ticked in the table.
This page will then be used to enable and disable modules for a trust. If a module is unticked the entry will be deleted from tblData, if it is ticked an entry will be inserted, and if no change then no change in the DB.
At the moment I'm having trouble getting the checkboxes ticked correctly based on qryModData
Any thoughts anyone?
--Edited to include code--
<table width="50%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>Module</td>
<td>Module Code</td>
<td> </td>
</tr>
<?php do { ?>
<tr>
<td><?php echo $row_qryModuleList['mod_name']; ?></td>
<td><?php echo $row_qryModuleList['mod_code']; ?></td>
<td><input <?php if (!(strcmp($row_qryModData['M01'],$row_qryModuleList['mod_code']))) {echo "checked=\"checked\"";} ?>name="chkMod" type="checkbox" id="chkMod" value="<?php echo $row_qryModData['M01']; ?>" /></td>
</tr>
<?php } while ($row_qryModuleList = mysql_fetch_assoc($qryModuleList)); ?>
</table>
Then there's two SQL queries, one that generates the list to build the table, and the second which I'm trying to use to set the boxes to ticked.
qryModuleList
SELECT *
FROM tblmodules
ORDER BY mod_name ASC
qryModData
SELECT *
FROM tbldata
WHERE trust_key = varTrust
varTrust is pulled from a URL variable.
Apologies for not including the code in the first place.
--Edit for new code.
<?php while ($row_qryModuleList = mysql_fetch_assoc($qryModuleList)) { ?>
<tr>
<td><?php echo $row_qryModuleList['mod_name']; ?></td>
<td><?php echo $row_qryModuleList['mod_code']; ?></td>
<td><input <?php if (strcmp($row_qryModData['M01'],$row_qryModuleList['mod_key']) != 0) {echo "checked=\"checked\"";} ?>name="chkMod" type="checkbox" id="chkMod" value="<?php echo $row_qryModData['M01']; ?>" /></td>
</tr>
<?php } ; ?>
--Edited for new Code.
<tr class="tblHead">
<td>Module</td>
<td>Module Code</td>
<td>Enabled\Disabled</td>
</tr>
<?php
$mod_data = array();
while ($row_qryModData = mysql_fetch_assoc($qryModData))
array_push($mod_data, $row_qryModData['M01']);
$currentRow = 0;
while ($row_qryModuleList = mysql_fetch_assoc($qryModuleList)) {
?>
<tr bgcolor="<?php echo($currentRow++ % 2)?"#CCFFFF":"#FFCCFF";?>">
<td><?php echo $row_qryModuleList['mod_name']; ?></td>
<td><?php echo $row_qryModuleList['mod_code']; ?></td>
<td><input <?php if (false !== (array_search($mod_data, $row_qryModuleList['mod_key']))) echo "checked=\"checked\""; ?> name="chkMod" type="checkbox" id="chkMod" value="<?php echo $row_qryModData['M01']; ?>" /></td>
</tr>
<?php } ; ?>

I think I'm understanding this now. What you need to do is place all of the allowed modules into an array and use the array_search() function to find it.
Example:
$mod_data = array();
while ($row_qryModData = mysql_fetch_assoc($qryModData)) array_push($mod_data, $row_qryModData['M01']);
That will get all the available modules into one array.
Next, while you cycle through the 'ModuleList' query, use the array_search() method to try and find the 'ModKey' variable in it. If you do, check the box. If not, do nothing.
Example:
<td><input <? if (false !== (array_search($mod_data, $row_qryModuleList['mod_code'])) echo "checked=\"checked\" "; ?>name="chkMod" type="checkbox" id="chkMod" value="<?php echo $row_qryModData['M01']; ?>" /></td>
(The reason I use a "!==" is because the function can return false or something that might equal false and might not. Read the page I've linked above for more)

Related

How to make a button inside a table execute a mysql query

I have a simple html table that displays data from a mysql table containing a list of available tournaments.
<table>
<tr>
<th>Tournament Name</th>
<th>Platform</th>
<th>Date</th>
<th>Venue</th>
<th>Judge</th>
<th>Description</th>
<th>Limit</th>
<th>Register</th>
</tr>
<?php while($row = mysqli_fetch_array($result)):?>
<tr>
<td><?php echo $row['nTournament'];?></td>
<td><?php echo $row['pTournament'];?></td>
<td><?php echo $row['dTournament'];?></td>
<td><?php echo $row['vTournament'];?></td>
<td><?php echo $row['jTournament'];?></td>
<td><?php echo $row['dTournament'];?></td>
<td><?php echo $row['lTournament']; ?></td>
<td><form method="post" action="tournamentlist.php"><button type="submit" name="btn_register"></button></form></td>
</tr>
<?php endwhile; ?>
</table>
What I want to do is that once the current user clicks that button, the button executes a query which takes the current user's id and the tournament id of the selected row to add them to another mysql table. Something like a tournament inscription.
The query/function I want to run is:
if (isset($_POST['btn_register'])) {
singup();
}
function singup() {
global $db;
$idUser = $_POST['idUser'];
$idTournament= $_POST['idTournament'];
$query = "INSERT INTO registeredCompetitor(idUser, idTournament) VALUES ('$idUser', '$idTournament')";
mysqli_query($db, $query);
header('location: tournamentlist.php');
}
The query works just fine on it's own but I don't know if the function itself works because of the button.
Is it possible to do such thing without the use of a form? If not, What other ways are there to do something like this?
EDIT1: Button now is ready but nor the function or the query executes once it's clicked.
You can create a form on each row that has 2 hidden fields in it. Not sure what your DB fields are called though so you'll have to change user_id and tournament_id to something appropriate.
...
<td>
<form action="post" action="the_name_of_your_php_script.php">
<input type="hidden" name="idUser" value="<?php echo $row['user_id']; ?>">
<input type="hidden" name="idTournament" value="<?php echo $row['tournament_id']; ?>">
<button type="submit" name="btn_register"></button>
</form>
</td>
...
Can't wrap it because <form> is not allowed as a child of <td>
All the documentation I see online permits forms inside of <td>. The other alternative is to use a link instead of a form.
You can use javascript to execute this functionality.
<table>
<tr>
<th>Tournament Name</th>
<th>Platform</th>
<th>Date</th>
<th>Venue</th>
<th>Judge</th>
<th>Description</th>
<th>Limit</th>
<th>Register</th>
</tr>
<?php while($row = mysqli_fetch_array($result)):?>
<tr>
<td><?php echo $row['nTournament'];?></td>
<td><?php echo $row['pTournament'];?></td>
<td><?php echo $row['dTournament'];?></td>
<td><?php echo $row['vTournament'];?></td>
<td><?php echo $row['jTournament'];?></td>
<td><?php echo $row['dTournament'];?></td>
<td><?php echo $row['lTournament']; ?></td>
<td><button type="submit" onclick="sendRequest('<?php echo $idUser ?>','<?php echo $idTournament ?>')" name="btn_register"></button></td>
</tr>
<?php endwhile; ?>
</table>
Javascript code
function sendRequest(idUser,idTournament ){
// i am using jquery
$.post(other_page_url,{idUser:idUser,idTournament :idTournament},function(data)
{
window.location = 'tournamentlist.php';
} )}
I hope it's gonna help you
You don't need to wrap this in a <form> inside the table, you can do it all via Javascript / Jquery if you wish. On the html side, add the data you need to the button in data sets:
<td><button type="submit" name="btn_register" id="btn_register" data-user-id="<?php echo $userId ?>" data-tournament-id="<?php echo $row['idTournament']; ?>"></button></td>
Then in your script, you can call the data and send to post via ajax and either load the new page after INSERT, or load as a modal, or whatever you like. You can do something like below if loading a modal (change the load part to refresh the page if you want to go directly):
$('#btn_register').on('click', function () {
var t_id = $(this).data('tournament-id');
var u_id = $(this).data('user-id');
$.ajax({
url: "YourURL",
type: "POST",
data:{
t_id:t_id,
u_id:u_id
},
success: function (h) {
$(".modal-title").text("Table with new stuff");
$(".modal-body").html(h);
$('#modal').modal();
// lots of options here - you could even reload above if desired
}
})
});

Give the submit button a Php variable

I cannot find the solution to my issue on this forum. I'm trying to give the submit button a PHP value (unique ID) by extracting data from my database. I would also like to store the value in a SESSION. The submit button doesn't work when I I give it something other than a String as value.
Student View:
<pre>
<?php foreach ($tabinternships as $internship) { ?>
<tr>
<td><span class="html"><?php echo $internship->id_internship() ?></span></td>
<td><?php echo $internship->email_teacher1_internship() ?></span></td>
<td><?php echo $internship->email_teacher2_internship() ?></span></td>
<td><?php echo $internship->email_responsible_internship() ?></span></td>
<td><?php echo $internship->id_promoter_internship() ?></span></td>
<td><?php echo $internship->name_enterprise_internship() ?></span></td>
<td><?php echo $internship->stage_internship() ?></span></td>
<td><input type="radio" name="apply" value="<?php $tabinternship->id_internship() ?>"></td> <!-- Method calls an Object rather than an Array because I'm only displaying the attributes of 1 Object therefore the Array is not required here-->
</tr>
<?php } ?>
</pre>
StudentController:
<pre>
$tabinternships = Db::getInstance()->select_internships();
if(isset($_POST['apply']) && isset($_POST['application'])){
$_SESSION['apply']= $_POST['apply'];
$_SESSION['application']= $_POST['application'];
$_SESSION['redirect']='redirect';
}
if(!empty($_SESSION['application']) && !empty($_SESSION['apply']) && !empty($_SESSION['redirect'])){
$_SESSION['redirect']='';
header("Location: index.php?action=formdeux");
die();
}
</pre>
Thanks for your help.
I have found the error, I wasn't using echo when giving a value to the radio input
echo $tabinternship->id_internship()

How to get checkboxes remained checked after being checked in another device

I am facing some issues trying to get checkboxes to stay checked in another device, I am able to get check boxes stay checked within the browser, so after the browser refreshed, the checkboxes remained checked, so is there any idea how i can do this?
so here is my code, firstly i included the dcConnect.php to connect to the database then i retrieve the data from the database to be displayed on a website
<?php
include_once("dcConnect.php");
$dcData = "SELECT dcID, dcServerName, dcServerAge, dcServerGender, dcServerMarital FROM dcUsers";
$result = $link->query($dcData);
if($result->num_rows >0){
echo"<table><tr><th></th><th>ID</th><th>Name</th><th>Age Group</th><th>Gender</th><th>Marital Status</th></tr>";
while($row = $result->fetch_assoc()){
echo"<tr><td><input type='checkbox' id='". $row["dcID"] ."' name='". $row["dcID"] ."' value='off' ></input></td><td>". $row["dcID"] ."</td><td>". $row["dcServerName"] ."</td><td>". $row["dcServerAge"] ."</td><td>". $row["dcServerGender"] ."</td><td>". $row["dcServerMarital"] ."</td></tr>";
}
echo "</table>";
}else{
echo"no results";
}
$link->close();
?>
Here is my website where the check boxes can stay checked after refreshed but not in another device
http://forstoringdata.com/default.php
It looks like currently you are using cookies to save the state of the checkboxes. Cookies are stored on the clientside (i.e. the user's computer) and not the server side, which is why you are not seeing the checkbox state preserved across devices.
In order to save and retrieve the checkbox state in the database, you will need to add an additional column to your database table. Following your pattern above, this would probably be a boolean column named something lke 'dcChecked'.
Then when you are printing your inputs, you would want to do something like this:
<input type="checkbox" <?php if($row['dcChecked']) { print 'checked' } ?></input>
(This is simplified for clarity, you'll still want to include your other attributes for ID, name, etc)
<?php
include_once("dcConnect.php");
$dcData = "SELECT dcID, dcServerName, dcServerAge, dcServerGender, dcServerMarital, dcChecked FROM dcUsers";
$result = $link->query($dcData);
?>
<?php if($result->num_rows > 0): ?>
<table>
<tr>
<th></th><th>ID</th>
<th>Name</th>
<th>Age Group</th>
<th>Gender</th>
<th>Marital Status</th>
</tr>
<?php foreach($rows as $row): ?>
<tr>
<td><input type='checkbox' id="<?php print $row["dcID"]; ?> " name="<?php print $row["dcID"]?>" value='off' <?php if($row["dcChecked"]): ?>checked<?php endif;?>></input></td>
<td><?php print $row["dcID"]; ?></td>
<td><?php print $row["dcServerName"]; ?></td>
<td><?php print $row["dcServerAge"]; ?></td>
<td><?php print $row["dcServerGender"]; ?></td>
<td><?php print $row["dcServerMarital"]; ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php else: ?>
No results
<?php endif; ?>
Here's what the syntax would look like in context. I also refactored this a bit to make it a bit more readable.

Getting contenteditable div's current value and update database

I'm new to web development and I'm trying to create editable database interface. I have got checkboxes in every row and an edit button. I need to update table(in database) when button clicked(rows that are checked). However I can't get current values in cells. I tried contentedittable div to display attiributes.
<?php while ( $rows = mysql_fetch_array($result)): ?>
<td align="center" bgcolor="#FFFFFF"><input name="need_delete[<?php echo $rows['UniqueID']; ?>]" type="checkbox" id="checkbox[<?php echo $rows['UniqueID']; ?>]" value="<?php echo $rows['UniqueID']; ?>"></td>
<td bgcolor="#FFFFFF"><div contenteditable><?php echo $rows['Timestamp']; ?></div></td>
<td bgcolor="#FFFFFF"><div contenteditable><?php echo $rows['Name']; ?></div></td>
<td bgcolor="#FFFFFF"><div contenteditable><?php echo $rows['Email']; ?></div></td>
<?php endwhile; ?>
I also tried to give unique names to divs, but it didn't work. I want to get current values from there if possible.
<?php
if( ! empty($_POST['edit']) ){
$query = 'UPDATE `asd` SET `Timestamp` = '????' WHERE `UniqueID`='.(int)$id;
mysql_query($query);
}
?>
Checkboxes work fine when I delete rows from table. Any suggestions ?
Thanks.
There are several javascript libraries that help with this problem:
x-editable http://vitalets.github.io/x-editable/ (bootstrap)
datatables https://datatables.net/ (jquery)
I had a similar issue that I solved here:
http://www.abrandao.com/2019/12/saving-contenteditable-html-using-php/
basically, it involves reading the HTML and using PHP parser to exctract the tag and the update the data

Form Submit button doesnt work with PHP loop

I have this code
<tbody>
<form action="dsf.php" method="post">
<?PHP if(mysql_num_rows($leerdb) > 0) {while ($rs = mysql_fetch_row($leerdb)) {?>
<tr>
<td><input name="idecod[]" type="checkbox" value="<?php echo $rs[0]; ?>" /></td>
<td><?php echo $rs[0]; ?></td>
<td><?php echo $rs[1]; ?></td>
<td><?php echo $rs[2]; ?></td>
<td><?php echo $rs[3]; ?></td>
<td><?php echo $rs[4]; ?></td>
<td><?php echo $rs[5]; ?></td>
<td>BsF. <?php echo $rs[6]; ?></td>
</tr>
<?PHP }}?>
<input class="enviar" type="submit" name="enviar" id="enviar" value="Editar Asesor" />
</form>
</tbody>
I do not know why the submit button doesnt work. When I click on it, nothing happend.
It seems that something in the php loop is making the mess.. But as I know, PHP goes first than HTML, so, when FORM HTML comes, PHP code was already executed.
Where is my error.??
Thanks in advance.
Roberto
You are generating invalid HTML.
You can't have a form wrapped around table rows without wrapping it around the entire table.
You can't have a submit button placed between table rows.
The browser you are using is likely trying to recover from the error in such a way that the form is moved somewhere where it is allowed, but where it doesn't contain any of the controls.
NB: Different browsers recover from having forms in inappropriate parts of tables in different ways.
Use a validator, and write real HTML.
instead of opening the brackets for the while and if, use the php short tags. Example:
<?php if (condition): ?>
output your html here
<?php endif; ?>
Same thing goes for while. read about it here: www.php.net/manual/en/control-structures.while.php

Categories