PHP: Delete checked rows - php

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.

Related

A nested WHILE loop to fetch and display data from TWO tables

I'm in the process of building an entertainment website. It uses THREE MySQL tables; one called title, one called clips and one called dialogue.
I've been playing around all day with having my PHP fetch data from TWO of the tables (clips and dialogue) and output the content in a HTML table.
I've not had much luck and to cap it all, I was using a free host which has now reached its EP limit and although I've upgraded, I've got to wait 24 hours to try the code I've now come up with.
My question is, have I done it right? Will this collect basic information about the clip and then produce each line of the script in a new TR before going back to the start and collecting information for the next clip?
I really hope this makes sense.
I've tried researching this and have re-built my PHP from the ground up, ensuring that I annotate each section. Last time I checked, it still didn't work!
<table class='container'>";
##############################
# CLIPS QUERY & ECHOING HERE #
##############################
$clipsquery = "SELECT * FROM clips WHERE titleid=$mainurn ORDER BY clipid";
$result2 = mysqli_query($cxn, $clipsquery);
while ($row2 = mysqli_fetch_assoc($result2))
{extract ($row2);
echo "
<tr>
<td colspan='3' class='divider'></td>
</tr>
<tr>
<td class='description'>";
if ($epident == "")
{echo "";}
else
{echo "<span class='episode'>$epident</span>";}
echo "</td>
<td rowspan='2' style='text-align: right'><audio controls>
<source src='media/$clipid.mp3' type='audio/mpeg'>Your browser does not support the audio element.</audio></td>
<td rowspan='2' style='text-align: right'><a href='media/$clipid.mp3' download='$clipid.mp3'><img src='graphics/dl-icon.png' alt='Download Icon' title='Right-click here to download this clip to your computer.'></a></td>
</tr>
<tr>
<td class='description'>$clipsynopsis</td>
</tr>
<tr>
<td colspan='3'></td>
</tr>";
#################################
# DIALOGUE QUERY & ECHOING HERE #
#################################
$dialoguequery = "SELECT * FROM dialogue WHERE clipid=$clipid ORDER BY linenum";
$result3 = mysqli_query($cxn, $dialoguequery);
while ($row3 = mysqli_fetch_assoc($result3))
{extract ($row3);
echo "
<tr>
<td class='speaker'>$speaker:</td>
<td colspan='2' class='script'>$dialogue:</td>
</tr>";}}
echo "
</table>
I've got the site to work (sort of) but the formatting went wild and sometimes included clips from other sources not meant to be on the page!
There are some things I would change in your code. If you trust the variables going into your sql query then change your while loops:
while($row = $result->fetch_assoc()){
$fetchValue = $row['COLUMN_NAME'];
}
I would say you shouldn't be using extract here.
If the user is able to modify the variables going into your sql statement you should implement prepared statements. I would build a class/function and just call it when you need it.
From the HTML/CSS side its probably going to serve you better to use css div tables, especially if you are planning to make the site responsive down the line. This can convert yours
With regards to the queries, I'm not sure I understand the structure of your tables. If you want to keep playing around on your machine install a L/W/M/AMP stack depending on your operating system. See here for more information.
You only need one table where you store the data of clips.
First, you fetch the data into an array, then
you can loop through that array with foreach,
creating the table and filling it with data.
You can use an alternative syntax for foreach to make mixing PHP with HTML easier.
//Creating the array of clips
$clips = [];
$sql = "SELECT * FROM clips";
if($result = mysqli_query($db, $sql)) {
while($row = mysqli_fetch_assoc($result)) {
array_push($clips, $row);
}
}
?>
<!-- Looping through the array and creating the table -->
<table class="container">
<?php foreach ($clips as $clip): ?>
<tr>
<td colspan='3' class='divider'></td>
</tr>
<tr>
<td class='description'>
<span class='episode'><?php echo $clip["id"]; ?></span>
</td>
<td rowspan='2' style='text-align: right'>
<audio controls>
<source src='<?php echo "media/". $clip["id"]. ".mp3"; ?>' type='audio/mpeg'>
Your browser does not support the audio element.
</audio>
</td>
<td rowspan='2' style='text-align: right'>
<a href='<?php echo "media/". $clip["id"]. ".mp3"; ?>' download='<?php echo $clip["id"]. ".mp3"; ?>'>
<img src='graphics/dl-icon.png' alt='Download Icon' title='Right-click here to download this clip to your computer.'>
</a>
</td>
</tr>
<tr>
<td class='description'>
<?php echo $clip["sypnosis"]; ?>
</td>
</tr>
<tr>
<td class='speaker'>
<?php echo $clip["speaker"]; ?>
</td>
<td colspan='2' class='script'><?php echo $clip["dialogue"]; ?>
</td>
</tr>
<?php endforeach; ?>
</table>
You need 1 MySQL table (clips) with the 4 attributes.
You should consider using PDO over mysqli, because it's a better way of dealing with the database.
Also, template engines like Smarty can help you make the code more readable and modifiable, separating the application logic from the presentation logic.
you must use JOIN in your Sql query
SELECT
clips.clipid, clips.columnname,
dilogue.id, dialogue.columnname
FROM
clips JOIN dialogue ON
clips.clipid = dialogue.id
WHERE
clipid=$clipid
ORDER BY linenum
then you can use
while($row = mysqli_fetch_assoc($result)){
echo $row['column name in clips table'];
echo $row['column name in dialogue table'];
}
but you must use Prepared statements or
mysqli_real_escape_string()
to avoid Sql Injections
also open and close PHP tags before and after html)

Put text between autofilled PHP-Table

I'm currently working on a table that contains 'Name', 'Info', 'Price' and 'Duration'. However the PHP-Script is connected to a database.
I want to autofill the tablecells: 'Name', 'Price', 'Duration' via the Database by using PHP and SQL and that works perfectly fine for me. Though, I want to customize the content that's in the individual Info cells (e.g. Readmore jQuery and redirect to other pages).
I tried a little bit with using tags inside the Database and other weird stuff which, obviously, didn't work.
Is there a more elegant way of solving my problem than setting up a complete normal table without PHP/SQL, where I'd have to put in every bit of data about Name,Price and Duration manually?
<table class="table table-bordered table-hover tablesorter row sortable">
<thead>
<tr>
<th class="header">Name</th>
<th class="hidden-xs">Info</th>
<th>Price (in Euro)</th>
<th>Duration</th>
</tr>
</thead>
<tbody>
<?php
//Connect to Database
$db=mysql_connect ("xxxx", "xxxx", "xxxx") or die ('Oops! Da hat wohl' . mysqli_error(). 'Mist gebaut');
//Choose Database
$mydb=mysql_select_db("massageke_de");
//Query Database
$sql="SELECT * FROM Angebote";
//-run the query against the mysql query function
$result=mysql_query($sql);
//Show Results
while($row=mysql_fetch_array($result)){
//Start table ?>
<tr>
<td class="col-sm-2"><?php echo $Name =$row['Name'] ; ?></td>
<!--In this <td>-tag I want to put long textes with links-->
<td class="hidden-xs col-sm-5">echo $Name =$row['Info'];?<</td>
<td class="col-sm-2"><?php echo $Preis =$row['Preis']; ?></td>
<td ckass="col-sm-1"><?php echo $Dauer =$row['Dauer']; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Thanks in advance for helping.
Don't bother asking me additional questions.
P.S.: I hope you can help, without needing the CSS of Bootstrap, that I used.
P.P.S.:I know that my PHP-Script is not protected against PHP-Injection
(but I want to and will learn how to secure it)
Edit: As Jester asked for it. I made it quickly with photoshop because I think an image can express much better, what I want to achieve, than my poorly coding-skills.
Get to the image
Seems to me like the easiest way would be to just edit the info column in the database for each? If you want to do it in php i'd suggest making an array using the names (ids would be better but it seems you don't have access to those?) as keys:
$info['Aroma Teilkoerper'] = "Text about aroma teilkoerper";
$info['Aroma Ganzkoerper'] = "Text about aroma ganzkoerper";
and so on until you have all. Then in the loop:
//Show Results
while($row=mysql_fetch_array($result)){
//Start table ?>
<tr>
<td class="col-sm-2"><?php echo $Name =$row['Name'] ; ?></td>
<!--In this <td>-tag I want to put long textes with links-->
<td class="hidden-xs col-sm-5">echo $Name =$info[$row['Name']];?></td>
<td class="col-sm-2"><?php echo $Preis =$row['Preis']; ?></td>
<td ckass="col-sm-1"><?php echo $Dauer =$row['Dauer']; ?></td>
</tr>
<?php } ?>
Hoping that is a workable solution for you? (also you had a syntax error in your closing php tag.
echo $Name =$row['Info'];?< // <----- should be ?> of course

PHP PDO while doesn't achieve my desire end result

This is my first posting in SO, my apologize if I opened an existing question. As I couldn't find the result in Google. Sorry to said but I'm still fresh in PHP PDO and in learning stage.
Back to my question, currently I'm building a customer visit logs from my wife but I'm stuck with the result. I have two table which one stores the customer information and another table store the visit details. I uploaded the test table at here: SQL Fiddle
And below is my current coding and I'm using PHP PDO while
<?php
require_once 'dbconnect.php';
$p_id = $_GET['name'];
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$sql = "SELECT customer.fname, customer.lname, customer.gender, services.treatment, services.date
FROM customer LEFT JOIN services
ON customer.id = services.customer_id
WHERE customer.slug LIKE :id";
$q = $conn->prepare($sql);
$q->execute(array('id' => $p_id));
$q->setFetchMode(PDO::FETCH_ASSOC);
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="container">
<h1>Customer Record</h1>
Name: <br />
Gender: <br />
<table class="table table-bordered table-condensed">
<thead>
<tr>
<th>Customer Name</th>
<th>Customer Gender</th>
<th>Treatment</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<?php while ($r = $q->fetch()): ?>
<tr>
<td><?php echo htmlspecialchars($r['fname']), ' ', htmlspecialchars($r['lname'])?></td>
<td><?php echo htmlspecialchars($r['gender']); ?></td>
<td><?php echo htmlspecialchars($r['treatment']); ?></td>
<td><?php echo htmlspecialchars($r['date']); ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
Seach Again
</body>
</div>
</html>
And I achieve as what SQL Fiddle result, but what I wanted is, the name and gender is not keep repeating.
I attached together with the screenshot:
Screenshot
What I want is as per the screenshot image, Name: John Doe and Gender: Male, should be on top and not keep on repeating while the table below show all the visit details. I tried to modified the code but it seems it don't really work out.
Please advise me as I'm really out of idea how to achieve what I want.
Thank you so much.
Since you do a LEFT JOIN in your SQL query, you know ahead of time that all of the fname, lname and gender values returned by $q->fetch() are going to be for the same customer.slug, right? So you can count on that.
My suggestion would be to instead use the fetchAll() function to get an array of all records for customer.slug, and then render that in your view. For example (haven't tested this) you could add the following after $q->setFetchMode(PDO::FETCH_ASSOC); ...
$cs = $q->fetchAll(); // customer services join
Then, in your <html> view, you could do something like the following:
<h1>Customer Record</h1>
Name: <?php echo htmlspecialchars($cs[0]['fname'].' '.$cs[0]['lname']); ?> <br />
Gender: <?php echo htmlspecialchars($cs[0]['gender']); ?> <br />
<table>
<thead>
<tr>
<th>Treatment</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<?php foreach($cs as $r): ?>
<tr>
<td><?php echo htmlspecialchars($r['treatment']); ?></td>
<td><?php echo htmlspecialchars($r['date']); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
Of course, it might also be a good idea to check to see that any records were returned by your query and display a "not found" message if not. After all, $cs[0] might be empty, giving you a PHP error.

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

Sql query on clicked button

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

Categories