How to delete table rows in MySQL and PHP? - php

i want to delete a table row from my database with MySQL and PHP. I have searched on the internet and I can't figure out what I'm doing wrong. I have the feeling I'm close.
If I go over the delete link there is a link showing with the ID number of the row to delete. But if I click it, it isn't working.
This is my code for admin.php
<?php
if(!isset($_COOKIE['E2ingelogd'])) {
header("location:../../index.php");
}
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Kan niet inloggen");
$selected = mysql_select_db("login", $dbhandle);
if(isset($_POST['team'])){
$team = $_POST['team'];
$ID = $_POST['id'];
$query = mysql_query("SELECT * FROM e2teams WHERE Team='$team' and ID='$ID'");
if(mysql_num_rows($query) > 0 ) { //check if there is already an entry for that username
echo "$team bestaat al!";
}
else{
mysql_query("INSERT INTO e2teams (Team) VALUES ('$team')");
header("location:e2admin.php");
}
}
mysql_close();
?>
<html><head>
<link href='http://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'>
<link href="../css/layout.css" rel="stylesheet" type="text/css"></head>
<body>
<div class="wrapper">
<div class="header">
<div class="logo"><img height="140" src="../images/boyslogo.png"> </div>
<div class="titelpagina">Vroomshoopse Boys E2 admin panel</div>
<div class="uitloggen">Uitloggen</div>
</div>
<div class="content">
<div class="teamstoevoegenvak">
<div class="titelbalk">
<h1>Voeg teams toe</h1>
<form style="border:0px; margin:0px; padding:0px"; action="e2admin.php" method="POST">
<input width="400" maxlength="400" type="text" name="team" placeholder="Team naam" /><br>
<input type="submit" value="Toevoegen" />
</form></div>
</div>
<div clas="toegevoegdeteamsvak">
<div class="titelbalktoege">
<h1>Toegevoegde teams</h1>
</div>
<div class="deteams">
<?php
$table = "e2teams";
$sql = "SELECT * FROM e2teams";
$result = mysql_query($sql, $dbhandle);
if(mysql_num_rows($result) > 0){
$team = array();
while($row = mysql_fetch_array($result)) {
echo "<table><tr><td class='styled-td'>";
echo $row['Team']. '</td><td></td><td>Bewerk</td><td><a href="delete.php?del='.$row['ID'].'">Delete<br>';
echo "</td></tr></table>";
$team = $row['Team'];
}
}
mysql_data_seek($result, 0);
?>
</div>
</div>
</div>
<div id="volgendewedstrijd"> <form action="" method="post">
<select name="dropdown">
<?php
mysql_data_seek($result, 0);
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)) {
echo '<option value="">' . $row['Team'] . '</option>';
}
}
?>
</select>
</form></div>
</div>
</body>
</html>
The piece of code where the delete is, is this:
if(mysql_num_rows($result) > 0){
$team = array();
while($row = mysql_fetch_array($result)) {
echo "<table><tr><td class='styled-td'>";
echo $row['Team']. '</td><td></td><td>Bewerk</td><td><a href="delete.php?del='.$row['ID'].'">Delete<br>';
echo "</td></tr></table>";
$team = $row['Team'];
}
}
mysql_data_seek($result, 0);
?>
And this is my delete.php:
<?php
if(!isset($_COOKIE['E2ingelogd'])) {
header("location:../../index.php");
}
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
mysql_query("DELETE FROM e2teams WHERE ID = $_GET[id]");
echo "Team is deleted";
header('location: e2admin.php');
?>
What am I doing wrong?

You are using del as a param in the link
<a href="delete.php?del='.$row['ID'].'">Delete<br>
This needs to be closed as
Delete<br>
And in the delete script you need to get it as
$id = (int)$_GET["del"];
and use in the query as
mysql_query("DELETE FROM e2teams WHERE ID = $id");

This:
mysql_query("DELETE FROM e2teams WHERE ID = $_GET[id]");
Should be:
mysql_query("DELETE FROM e2teams WHERE ID = ".$_GET['del']."");
Because of:
<a href="del.php?del='.$row['ID'].'"> //the get var name is: del

You can access a variable inside a array between quotes:
Change the following line
mysql_query("DELETE FROM e2teams WHERE ID = $_GET[id]");
to
mysql_query("DELETE FROM e2teams WHERE ID = " . $_GET['id']);
This is a security risk and you are acceptable to SQL injections. Please google: "php sql injections".

Related

How to show comments on specific posts

I have an application that where users can post announcements and comment on posts. My problem is that whenever a comment is posted, It shows up on every announcement post. How can I post comments so that they show up on that specific post?
I have 2 database tables: "announcement: id, name, announcementTitle, announcement, image" and "comment: id, post_id, name, comment" with foreign key attached to comment.
Here is my home.php where the announcements and comments are echoed
<div class="container">
<div class="mx-auto">
<?php
if (isset($_SESSION['username'])) {
echo'
<h1 style="text-decoration:underline">Post an announcement</h1>
<form method="post" action="announcement.php" enctype="multipart/form-data">
<input type="text" name="announcementTitle" placeholder="Enter Subject"><br>
<textarea name="announcementBox" rows="5" cols="40" placeholder="Enter Announcement"></textarea><br>
<input type="file" name="image" accept="image/jpeg">
<button name="announcement">Submit</button>
</form>';
}
$query = "SELECT * FROM announcement ORDER BY id DESC";
$result = mysqli_query($con,$query);
while ($row = mysqli_fetch_array($result)) {
echo '<div class="row" style="color:black;background-color:white;border-radius:5px;padding:10px;margin-top:10px;margin-bottom:70px">';
echo '<div class="column" style="width:100%;border:5px">';
if (isset($_SESSION['username'])) {
echo '<form method="post" action="announcement.php">';
echo "Posted by " .$row["name"]. " click X to delete:";
echo '<input type="hidden" name="postID" value="'.$row['id'].'">';
echo '<button name="delete" style="float:right">X</button>';
echo '</form>';
}
echo $row['announcementTitle'].'<br>';
echo $row['announcement'].'<br>';
echo '<img width="20%" src="data:image;base64,'.$row['image'].'"alt="Image" style="padding-top:10px">';
echo'
<form method="post" action="comment.php">
<textarea name="commentbox" rows="2" cols="50" placeholder="Leave a Comment"></textarea><br>
<button name="comment">Submit</button>
</form>';
echo "Comments:<p><p>";
echo " <p>";
$find_comment = "SELECT * FROM comment ORDER BY id DESC";
$res = mysqli_query($con,$find_comment);
while ($row = mysqli_fetch_array($res)) {
echo '<input type="hidden" name="postID" value="'.$row['post_id'].'">';
$comment_name = $row['name'];
$comment = $row['comment'];
echo "$comment_name: $comment<p>";
}
if(isset($_GET['error'])) {
echo "<p>100 Character Limit";
}
echo '</div></div>';
}
?>
</div>
</div>
Here is comment.php where comments are put in the database
<?php
session_start();
$con = mysqli_connect('localhost', 'root', 'Arv5n321');
mysqli_select_db($con, 'userregistration');
$namee = '';
$comment = '';
$comment_length = strlen($comment);
if($comment_length > 100) {
header("location: home.php?error=1");
}else {
$que = "SELECT * FROM announcement";
$res = mysqli_query($con,$que);
while ($row = mysqli_fetch_array($res)) {
$post_id = $row['id'];
}
$namee = $_SESSION['username'];
$comment = $_POST['commentbox'];
$query = "INSERT INTO comment(post_id,name,comment) VALUES('$post_id','$namee','$comment')";
$result = mysqli_query($con, $query);
if ($result) {
header("location:home.php?success=submitted");
} else {
header("location:home.php?error=couldnotsubmit");
}
}
?>
Here is announcement.php where announcements are put in the database
<?php
session_start();
//$con = mysqli_connect('freedb.tech', 'freedbtech_arvindra', 'Arv5n321', 'freedbtech_remote') or die(mysqli_error($con));
$con = mysqli_connect('localhost', 'root', 'Arv5n321', 'userregistration') or die(mysqli_error($con));
if (isset($_POST['announcement'])) {
$image = $_FILES['image']['tmp_name'];
$name = $_FILES['image']['name'];
$image = base64_encode(file_get_contents(addslashes($image)));
date_default_timezone_set("America/New_York");
$title = $_POST['announcementTitle']." (<b>".date("m/d/Y")." ".date("h:i:sa")."</b>)";
$paragraph = $_POST['announcementBox'];
if (empty($paragraph)||empty($title)) {
header('location:home.php?error=fillintheblanks');
}else{
$nam = $_SESSION['username'];
$query = "insert into announcement(name,announcementTitle,announcement,image) values('$nam','$title','$paragraph','$image')";
$result = mysqli_query($con, $query);
if ($result) {
header("location:home.php?success=submitted");
} else {
header("location:home.php?error=couldnotsubmit");
}
}
}else if (isset($_POST['delete'])){
$query = "delete from announcement where id='".$_POST['postID']."';";
$result = mysqli_query($con,$query);
if ($result) {
header('location:home.php?success=deleted');
} else {
header('location:home.php?error=couldnotdelete');
}
}
else {
header('location:home.php');
}
I am a little new to PHP so any help is good.

The edit form in the same page won't show up when I click the EDIT link

I am trying to update or edit the data from the database but I don't want the edit page to be in another page, I just want it to be in the same page where I can view the different news that the user has added. But the form won't show up when I click the edit link .
Help me find what's wrong or missing?
here's my edit_news.php
<?php
date_default_timezone_set('Asia/Manila');
include_once('db.php');
if($isset($_GET['id']))
{
$id=$_GET['id'];
if(isset($_POST['edit'])) {
$title = $_POST['title'];
$body = $_POST['body'];
$date = date('Y-m-d H:i:s');
$title = mysql_real_escape_string($title);
$body = mysql_real_escape_string($body);
$servername = "localhost";
$username="root";
$password = "";
$database = "zchs_alumni";
$connection = new mysqli($servername, $username, $password, $database);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
$sql = ("UPDATE news SET title = '$title', body = '$body', name = '$name', date = '$date' WHERE id='$id'")or die();
mysql_query($sql);
echo "<script type='text/javascript'>alert('Changes saved!'); window.location.assign('/zchs-alumni/news.php');</script>";
}
}?>
<?php
if($isset($_GET['id']))
{
$id=$_GET['id'];
$query=mysql_query("SELECT * FROM news WHERE id='$id'");
while($row = mysql_fetch_array($query)) {
$title=$row['title'];
$body=$row['body'];
?>
<form action="" method="post">
<p>
<label for="title" id="title">Title</label>
<input type="text" name="title" value="<?php echo $row['title']; ?>"/>
</p><br/>
<p>
<label for="body" id="body">Body</label>
<input type="text" name="body" value="<?php echo $row['body']; ?>"/>
</p><br/>
<p>
<input type="submit" name="update" value="Save Changes" style="float: right"/>
</p>
</form>
<?php
} }?>
And this is my news.php where the news show up and where I want the editing of the data to take place.
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("zchs_alumni") or die(mysql_error());
$query = mysql_query("SELECT * FROM news ORDER BY date DESC LIMIT $start, $limit");
while($row = mysql_fetch_array($query)) {
?>
<p> <span><h3><?php echo $row['title']; ?></h3></span></p>
<p> <span><?php
$img = $row['photo'];
if($img != ""){
$image = 'news/'.$img;
echo '<center><img src="'.$image.'" width="750" height="350" alt=""></center>';
}
?></span></p>
<br/>
<p> <span><?php echo $row['body']; ?></span></p>
<br/>
<p> <span><h6>Posted at
<?php
$row_date = strtotime($row['date']);
echo date("F j, Y, g:i a", $row_date);
?></h6></span></p>
<br/>
<p><span><span class="edit" title="Edit">EDIT</span></p>
<?php
}
?>
I have seen these guys do that. Simple check if the post variable is defined if(isset($_POST)) and if so then it is an update submission, if not then display the form!

A multiple choice is pulled randomly from mysql database. Use the correct answer on the grade page

I have generated a multiple choice question page, where it takes a random question from my qbanktable in my database. The CorrectAnswer to this question is also in the qbanktable. Here is the code for the question.php page
<form action="grades.php" method="post" id="quiz">
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "qbank";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Question, AnswerA, AnswerB, AnswerC, AnswerD, AnswerE, CorrectAnswer FROM qbanktable ORDER BY RAND() LIMIT 1";
$result = $conn->query($sql);
?>
<h3>
<?php
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["Question"];
}
}
?>
</h3>
<p> </p>
<div>
<input type="radio" name="question-1-answers" id="question-1-answers-A" value="A" />
<label for="question-1-answers-A">A)
<?php
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["AnswerA"];
}
}
?>
</label>
</div>
<div>
<input type="radio" name="question-1-answers" id="question-1-answers-B" value="B" />
<label for="question-1-answers-B3">B)
<?php
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["AnswerB"];
}
}
?>
</label>
</div>
<div>
<input type="radio" name="question-1-answers" id="question-1-answers-C" value="C" />
<label for="question-1-answers-C3">C)
<?php
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["AnswerC"];
}
}
?>
</label>
</div>
<div>
<input type="radio" name="question-1-answers" id="question-1-answers-D" value="D" />
<label for="question-1-answers-D3">D)
<?php
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["AnswerD"];
}
}
?>
</label>
</div>
<div>
<input type="radio" name="question-1-answers" id="question-1-answers-D" value="E" />
<label for="question-1-answers-D3">E)
<?php
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["AnswerE"];
}
}
?>
</label>
</div>
<div>
<input type="hidden" name="question-1-correct_answer" id="question-1-correct-answer" value="$row["CorrectAnswer"]" >
</div>
</ol>
<input type="submit" class="hvr-grow" value="SUBMIT" />
</form>
Now after I press the submit button, it will direct me to grades.php where it will analyze the CorrectAnswer:
<?php
$correctAnswer = $_POST['question-1-correct_answer'];
$answer1 = $_POST['question-1-answer'];
if ($answer1 == $correctAnswer) {
echo "<img src=correct.svg";
}
else {
echo "<img src=wrong.svg";
}
?>
I believe now in the grades.php (code above) I am messing something simple. I was wondering what is the correct code to match the CorrectAnswer with the user answer? Thank you
Multiple ways:
Send the question id in a hidden input and requery the database to get the Correct answer, this requires you to edit the query to also get the question ID
<input type="hidden" name="question-id" id="question-id" value="$row["id"]" >
In the grades.php you can then use to requery the db to get all the answers (especially the correct one)
$questionID= $_POST['question-id'];
The second one is easier but less secure, so try the first option first
You could send it using an hidden input type, but as already commented by #khuderm, this is a bad idea, because someone with little skills could see the answer in the source. I don't think anyone would actually try it, but better safe then sorry.
<input type="hidden" name="question-1-correct_answer" id="question-1-correct-answer" value="$row["CorrectAnswer"]" >
In the grades.php you will need something like this:
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "qbank";
$questionID= $_POST['question-id'];
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT CorrectAnswer FROM qbanktable where id = $questionID";
$result = $conn->query($sql);
So after a few modifications, now it works.
1) I had to include the label for the hidden input in php as follows:
<input type="hidden" name="question-id" id="question-id" value= <?php
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["id"];
}
}
?> >
Now it gets the id row from my table and send it to the grades.php
2) In grades.php the code to finally check the user input with the correct answer from question id provided from the last page:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "qbank";
$questionID= $_POST['question-id'];
$answer1 = $_POST['question-1-answers'];
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT CorrectAnswer FROM qbanktable WHERE id = $questionID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$correct = $row["CorrectAnswer"];
}
}
if ($answer1 == $correct) {
echo "<img src=correct.svg";
}
else {
echo "<img src=wrong.svg";
}
?>
Now it works fine.
Special thanks to #davejal

Removing selected data from drop down list(php)

I need to create a function which retrieves my data from my database into a drop down list, then choose and remove the selected data. I have my drop down list done & working but I'm experiencing some error with my 'Remove' function.
<body>
<?php
//connecting to database
$server = 'localhost';
$username = 'root';
$password = 'infosys';
$database = 'project';
mysql_connect($server,$username,$password) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
//dropdown list to retrieve sentence
$sql = "SELECT words FROM sentence";
$result = mysql_query($sql);
echo "<select name
='dropdownlist'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['words'] ."'>" . $row['words'] ."</option>";
}
echo "</select>";
?>
<form method="post" action="remove.php">
<input type="submit" value="Remove" />
</form>
<a href="index.php" >View list</a>
</body>
Followed by another php file
<?php
$server = 'localhost';
$username = 'root';
$password = 'infosys';
$database = 'project';
mysql_connect($server,$username,$password) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
$dropdownlist1 = $_POST['dropdownlist'];
$dropdownlist2 = $dropdownlist1.value;
if(isset($_GET['id'])) {
$mysql_query("DELETE FROM 'words' WHERE id = $dropdownlist2");
header("location: index.php");
exit();
}
?>
Move your Select box or dropdown inside the form tag,
<form method="post" action="remove.php">
<select name ='dropdownlist'>
<?php while ($row = mysql_fetch_array($result)) { ?>
<option value='<?php echo $row['words'];?>'><?php echo $row['words'];?></option>
<?php } ?>
</select>
<input type="submit" value="Remove" />
</form>
in php,
if(isset($_POST['dropdownlist'])) {
$dropdownlist1 = $_POST['dropdownlist'];
mysql_query("DELETE FROM `sentence` WHERE `words` = '$dropdownlist1' ");
header("location: index.php");
exit();
}
Note: Use mysqli_* or PDO functions instead of using mysql_* functions(deprecated)

Deleting Multiple Records using Checkboxes in PHP

I am having an issue where I need to be able to delete multiple records using checkboxes.
Here is the code that I currently have.
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#############################################################################################
?>
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<table width=50%>
<form method="post" action="insert_ticket.php">
<table width border='0'>
<tr><td> Date:<input type="text" name="date"/></td>
<td>Ticket #:<input type="text" name="ticket"/></td></tr>
<table>
<tr><td>Description:<TEXTAREA COLS=50 name="description"></TEXTAREA></td></tr>
<tr><td> Result :<TEXTAREA COLS=50 name="result"></TEXTAREA></td></tr>
<tr><td><input type="submit" name="submit" value="Add"/></td></tr>
</table>
</table>
</form>
<form method="post" action="delete_ticket.php">
<input type="submit" name="delete" value="Delete"/>
</form>
</table>
<?php
print "<table width=80% border=1>\n";
$cols = 0;
while ($get_info = mysql_fetch_assoc($result)){
$id = $get_info->id;
if($cols == 0)
{
$cols = 1;
print "<tr>";
print "<th>Select</th>";
foreach($get_info as $col => $value)
{
print "<th>$col</th>";
}
print "<tr>\n";
}
print "<tr>\n";
print "<td><input type='checkbox' name='selected[]' id='checkbox[]' value=$id></td>";
foreach ($get_info as $field)
print "\t<td align='center'><font face=arial size=1/>$field</font></td>\n";
print "</tr>\n";
}
print "</table>\n";
mysql_close();
?>
<!------------------------------------------------------------!>
</BODY>
</HTML>
Delete.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#####################################
if($_POST['delete']) {
$checkbox = $_POST['selected'];
$countCheck = count($_POST['selected']);
for($i=0;$i<$countCheck;$i++) {
$del_id = $checkbox[$i];
$sql = "DELETE FROM ticket_history WHERE Auto = $del_id";
$result = mysql_query($sql);
}
}
?>
I just want to be able to delete rows checked. How would I go about doing this effectively and efficiently?
Thank you in advance.
The simple answer to your question would be to use:
$sql = sprintf('DELETE FROM ticket_history WHERE Auto IN ()',
implode(',', $checkbox));
However as people will jump in and tell you, you are vulnerable to SQL injection. You should never trust user input. You are deleting using an ID, which I'm assuming must be an integer.
Using something like this will validate that:
$ids = array();
foreach($_POST['selected'] as $selected) {
if (ctype_digit($selected)) {
$ids[] = $selected;
}
else {
// If one is invalid, I would assume nothing can be trusted
// Depends how you want to handle the error.
die('Invalid input');
}
}
$sql = sprintf('DELETE FROM ticket_history WHERE Auto IN (%s)',
implode(',', $ids));
Other issues:
You seem to be using id's, but have not selected that field in your initial query.
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
Then you reference:
$id = $get_info->id;
Check the HTML output is actually what you expect.
In your delete query, you are referencing the field Auto. Is that your ID field?
And lastly, there no checking if the user has permission to do so. If this is a public site anyone can delete from that table.
Example of using two submit buttons within one form:
<?php
if (isset($_POST['create'])) {
echo "Create!";
}
elseif (isset($_POST['delete'])) {
echo "Delete!";
}
?>
<html>
<form method="post">
<input type="submit" name="create" value="Create"/>
<input type="submit" name="delete" value="Delete"/>
</form>
</html>

Categories