Sql query on clicked button - php

I would like to ask how can I call Sql query when HTML button is pressed. I watched a couple tutorials, but never got it to work correct, thats why I would like to ask here.
So..I have a list of items displayed, and the list is generated from database. Here is how the code looks like:
<table width="100%" border="1" cellspacing="1" cellpadding="5" style="background-color:#FFC" >
<td>Id</td>
<td>Text</td>
<td>Solved?</td>
<td></td>
<?php
while( $array = mysql_fetch_assoc($queryRun) ) {
?><tr>
<td><?php echo $id = $array['id'].'<br />';?></td>
<td><?php echo $text = $array['text'].'<br />';?></td>
<td><?php echo $reseno = $array['solved'].'<br />';?></td>
<td><input type="button" value="Solve it" /></td>
</tr><?php
}?>
</table>
Now each item that is generated inside this loops has a button "Solved" at the end of the table, and I want to make it so when user click on that button, do a Sql query which changes a value of solved from 0 (false) to 1 (true).

You need ajax. write button onclick and make ajax call.

I've not tested this, but it should work.
Basically I've applied a class to anything to easily select stuff in jQuery:
<?php while ($array = mysql_fetch_assoc($queryRun)) { ?>
<tr class="row">
<td class="cell_id">
<?php echo $array['id']; ?>
</td>
<td class="cell_text">
<?php echo $array['text']; ?>
</td>
<td class="cell_solved">
<?php echo $array['solved']; ?>
</td>
<td class="cell_solve_it">
<input class="button_solve_it" type="button" value="Solve it" />
</td>
</tr>
<?php } ?>
Then I've created this short jQuery script:
$('.row').each(function(){
$('.button_solve_it', this).click(function(e){
e.preventDefault();
$.post(
'solve_query.php',
{
id: $('.cell_id', this).html(),
text: $('.cell_text', this).html()
},
function (data) {
$('.cell_solved', this).html('1');
}
);
});
});
In short:
when you click a .button_solve_it button, you make an AJAX request to solve_query.php, where you perform your SQL query.
Then, it sets the content of the row in Solved? column to 1 (or to true or whatever you want).

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
}
})
});

symfony 1.4 and jquery. How to pass variable to jquery function?

I have the template indexSuccess.php with an AJAX function:
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#test<?php $mensajes->getIdmensajes() ?>').click(function(){
jQuery('#contenido<?php $mensajes->getIdmensajes() ?>').load(this.href);
return false;
});
});
</script>
<h2>Listado de mensajes emitidos</h2>
<h3>En orden cronológico inverso (más nuevo primero)</h3>
<table id="enviados" width="60%" border="1" cellpadding="8">
<thead>
<tr>
<th>Fecha Creación</th>
<th>Contenido del mensaje</th>
<th>Destinatarios</th>
</tr>
</thead>
<tbody>
<?php foreach ($mensajess as $mensajes): ?>
<tr>
<td width="10%" align="center"> <?php echo date('d/m/Y', strtotime($mensajes->getFechaalta())) ?></td>
<td bgcolor="<?php echo $mensajes->getColores()->getCodigo() ?>"><?php echo $mensajes->getCuerpo() ?></td>
<td width="20%" id="contenido<?php echo $mensajes->getIdmensajes() ?>">
<a id="test<?php echo $mensajes->getIdmensajes() ?>" href="<?php echo url_for('mensajes/receptores?idmensajes='.$mensajes->getIdmensajes()) ?>">Ver receptores</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
I want to pass the value $ message-> getIdmensajes () to the AJAX function. I will have a different ID for each row, but this does not work. But the function works well when I set the value. For example: jQuery ('# test24') and jQuery ('# contenido24') works well for the value Idmensajes=24 . How do I pass the value $ message-> getIdmensajes () to AJAX function?
Your question is not so clear but you wrote
jQuery ('#contenido24') works well for the value Idmensajes=24
Also, you have this
jQuery('#test<?php $mensajes->getIdmensajes() ?>').click(function(){
jQuery('#contenido<?php $mensajes->getIdmensajes() ?>').load(this.href);
return false;
});
So, I think you have elements with similar ids, such as contenido24, contenido25 and so on as data container and links with ids like #test24, #test25 an so. If this is the case then you can simply use
jQuery(document).ready(function(){
// Register click handler for all a tags whose id begins with 'test'
jQuery("a[id^='test']").click(function(e){
e.preventDefault(); // instead of return false
jQuery('#contenido'+this.id.match(/\d+/)[0]).load(this.href);
});
});
jQuery('contenido'+this.id.match(/\d+/)[0]) will select elements with id like #contenido24, contenido25 depending on the ID of a, if an a tag has id='test20' then it'll select #contenido20 and load content from ajax call into this element.

PHP: Delete checked rows

I will have to mention first that I have searched for a Google and stackoverflow and anywhere else, as well as tried to use scripts given in forums and write my own ones, but nothing worked for me. I am completely stuck.
So, all I try to do is to write a script that will delete checked rows from MySQL table. Here is my HTML written inside of a PHP file:
<tr class="noP">
<td class="check"><input class="checkbox" name="checkbox[]" type="checkbox" value="'.$row["PID"].'"/></td>
<td class="id">'.$row['PID'].'</th>
<td>'.$row["name"].'</th>
<td>'.$row["surname"].'</th>
<td>'.$row["pcode"].'</th>
<td class="address">'.$row["address"].'</th>
<td class="email">'.$row["email"].'</th>
<td>'.$row["phone"].'</th>
<td class="education">'.$row["education"].'</th>
<td class="remarks">'.$row["remarks"].'</th>
</tr>
for here $row = mysql_fetch_assoc($qParts);, so this array is just a collector of field values from MySQL DB.
Basically, all I try to do is just a table with all the participants listed with ability to delete selected ones.
I would highly appreciate any help provided. Thank you!
This should help you:
foreach($_REQUEST['checkbox'] as $val)
$delIds = intval($val);
$delSql = implode($delIds, ",");
mysql_query("DELETE FROM table WHERE PID IN ($delSql)");
So, that takes your input array from $_GET/$_POST, sanitises it (a little), then implodes it to get a list of IDs (e.g. 5, 7, 9, 13). It then feeds that into an SQL statement, matching on those IDs using the IN operator.
Note that you should do this using prepared statements or similar. It's been a while though, so I can't write them off-hand, but this should give you the gist of it.
To do this using PDO, have a look here. It's a bit more complex, since you need to dynamically create the placeholders, but it should then work the same.
Reference - frequently asked questions about PDO
I think I can help you out. I had the same issue during my semester project. The problem can be solved using HTML and PHP alone.
I am assuming that PID is the primary key in your table. The trick here is to put the entire table in a form so that it looks like this:
<form action="/*NAME OF THIS PAGE HERE*/.php" method="POST">
<?php
if(isset($_POST['delete'])) //THE NAME OF THE BUTTON IS delete.
{
foreach ($_POST["checkbox"] as $id){
$de1 = "DELETE FROM //table-name WHERE PID='$id'";
if(mysqli_query($conn, $de1))
echo "<b>Deletion Successful. </b>";
else
echo "ERROR: Could not execute";
}
}
if(isset($_POST['delete'])){
echo"<b>Please make a selection to complete this operation.</b>";
}
?>
</br>
<!-- below you will see that I had placed an image as the delete button and stated its styles -->
<button type="submit" name="delete" value="delete" style="float:right;border:none; background:none;">
<img style="width:55px; height:55px;margin-left:10px; margin-bottom:6px; float:left;" src="images/del.png">
</button>
<table>
<thead>
<tr>
<th>#</th>
<th>PID</th>
<th>NAME</th>
<th>SURNAME</th>
<!--REST OF THE TABLE HEADINGS HERE -->
</tr>
<?php $fqn="SELECT * FROM //table-name here;
$fqn_run=mysqli_query($conn,$fqn);
while($row=mysqli_fetch_array($fqn_run)):?>
</thead>
<tbody>
<tr class="noP">
<td class="check"><input class="checkbox" name="checkbox[]" type="checkbox" value="<?php echo $row["PID"];?>"></td>
<td><?php echo $row['PID'];?></td>
<td><?php echo $row["name"];?></td>
<td><?php echo $row["surname"];?></td>
<!-- REST OF THE ROWS HERE -->
</tr><?php endwhile;?>
</tbody>
</table>
</div>
</div>
</form>
Hope this helps you.

delete items that are checked without $_POST php

I've stuck with the following issue:
I have a table with texts and each one has a checkbox next to it. I also have a button-like link "Delete selected". What I want is to give the ability to the user to select many texts through checkboxes and delete the selected all together. The problem is tha I don't want to use a form so I can't use $_POST so I suppose I have to use $_SESSION. I have used sessions before but I don't know how to combine them with checkboxes..
if you could give me some tips or examples I would be very gratefull..
parts of my code to give you a clue..
view_texts.php
<?php
$sql="SELECT * FROM texts";
$res=mysql_query($sql) or die(mysql_error());
$i=1;
while($row=mysql_fetch_array($res))
{
?>
<tr>
<td><input type="checkbox" name="check[]" value="<?php echo $row['id']?>"/></td>
<td><?php echo $i; ?></td>
<td><?php echo $row['title']; ?></td>
<td><?php echo substr($row['description'],0,20); ?></td>
<td><?php echo $row['page_id']; ?></td>
<td><img src="images/user_edit.png" alt="" title="" border="0" /> </td>
<td><a href="delete_text.php?id=<?php echo $row['id'];?>" class="ask"><img src="images/trash.png" alt=""
title="" border="0" /></a></td>
</tr>
<?php
$i++;
}
?>
<span class="bt_red_lft"></span><strong>Διαγραφή επιλεγμένων</strong><span class="bt_red_r"></span>
delete_selected_texts.php
<?php
if (isset($_POST['check']))
{
foreach ($_POST['check'] as $value)
{
$sql = "DELETE FROM texts WHERE id =".$value;
mysql_query ($sql);
}
}
?>
this is the code that i use for textboxes inside a form tag.
If you're stuck on not using a form, for whatever reason, you're looking at using javascript and sending an AJAX request on the POST instead. I'd recommend using jQuery, as that greatly simplifies the process of selecting the elements you want to target.
It would look something like this...
$(document).function(){
$(":checkbox").click(function(e){
var deleteItem = $("input:id").val();
$.ajax({
type: "POST";
data: deleteItem;
url: "path/to/a/file.php";
success: function(data){
if (data="success"){
$(this).css("backgroundcolor", "blue");
} else {
alert("failed to find item");
}
}
});
}
You would need then to have a file that the Ajax request sends the data to that will build a list of items to delete/take items off that list, which will be stored and called up when the delete_selected_texts.php is called up to be deleted.
NB.: The jQuery above hasn't been checked. There's an excellent chance of there being several errors in there.

PHP Repeating Region and Checkboxes

--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)

Categories