Delete record with php then reload page - php

I am building a simple webpage that will allow the user to delete a record from a database and then the page will reload with the record deleted. Having trouble figuring out the code to use to accomplish this. Here is my main page:
<html>
<head>
<title>Change Record form</title>
<style type="text/css">
td {font-family: tahoma, arial, verdana; font-size: .875em }
</style>
</head>
<body>
Add new record
<br>
<br>
<?php
$con=mysqli_connect("localhost", "root", "", "customers");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$strSQL = "SELECT * FROM music";
$rs = mysqli_query($con, $strSQL);
while($row = mysqli_fetch_array($rs, MYSQLI_BOTH)) {
// Write the value of the column FirstName (which is now in the array $row)
echo "<br>";
echo "<br>";
echo $row['artist'] . "<br />";
echo $row['title'] . "<br />";
echo $row['format'] . "<br />";
echo $row['notes'] . "<br />";
echo '<FORM METHOD="LINK" ACTION="update_form.php">
<INPUT TYPE="submit" VALUE="Update">
</FORM>';
echo '<FORM METHOD="LINK" ACTION="delete_process.php">
<INPUT TYPE="submit" VALUE="Delete">
</FORM>';
}
?>
And then this is the delete_process page:
<?php
$id = $_GET['id'];
$artist = $_GET['artist'];
$title = $_GET['title'];
$format = $_GET['format'];
$notes = $_GET['notes'];
//create connection to DB
$con=mysqli_connect("localhost", "root", "", "customers");
//check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "DELETE from 'MUSIC' WHERE 'id' = $id";
mysql_query($sql);
?>
Basically when the user clicks the delete button, that particular record will be deleted and the main page will reload with the record deleted. Don't really know the code, thanks!

add a header at the end of your delete_process.php
<?php
//redirect to index page
header('Location:index.php'); //replace index.php with the page you want to redirect to
?>
should work

You need to add
'<input type="hidden" name="id" value="' . $row['id'] . '" />'
to the form that posts to delete_process.php.
However, you should know that the code as you've posted it is horribly insecure, and it would be trivial to attack via SQL injection and delete your entire database.

Related

UPDATE single column in database: PHP&MYSQL

So, I am trying to figure out how do this this and it boggling me. THIS WILL NOT BE USED ONLINE LIVE SO SQL INJECTION I DONT' CARE ABOUT. What am I doing wrong/right?
<?php
$db = mysql_connect("localhost", "root", "root");
if (!$db) {
die("Database connect failed: " . mysql_error());
}
$db_select = mysql_select_db("UNii", $db);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$comment = $_GET['comment'];
$id = $_GET['id'];
$sql = "UPDATE Dbsaved SET comment = '{$comment}' WHERE id = $id";
$comment1 = mysql_query($sql);
if (!$comment1) {
die("did not save comment: " . mysql_error());
}
echo $sql;
The main problem is with the statement itself, the connection is fine. I am trying to read $comment, and then update that into a MYSQL table and then have it read back in a different file.
EDIT: Mark up for the form I'm taking $comment from.
<!DOCTYPE html>
<html lang="en">
<LINK href="stylesheet.css" rel="stylesheet" type="text/css">
<script src ="js/validateform.js"></script>
<head>
<meta charset="UTF-8">
<title>UniHelp Home</title>
</head>
<body>
<div id="headeruni">
<h1>Welcome <?php echo $_GET["name"]; ?> to UniHelp!</h1>
</div>
<div id ="infouni">
<h3>Welcome to UniHelp. The social Network getting you connected to other people all over the University for any help you require!</h3>
</div>
<div id ="nameandemail">
<form action="formsend.php" method="post">
First name: <br> <input type="text" name="name"><br>
Email: <br> <input type="text" name="email"><br>
Comment: <br> <input type="text" name="message"><br>
<input type="submit" name="submit">
</form>`enter code here`
</div>
<div id="grabphpdiv">
<?php
$db = mysql_connect("localhost", "root", "root");
if (!$db) {
die("Database connect failed: " . mysql_error());
}
$db_select = mysql_select_db("UNii", $db);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$result = mysql_query("SELECT * FROM Dbsaved", $db);
if (!$result) {
die ("Database query failed: " . mysql_error());
}
$comment = $_POST['$comment'];
while ($row = mysql_fetch_array($result)) {
echo "<div id='posts'>";;
echo "<h2>";
echo $row[1] . "";
echo "</h2>";
echo "<p>";
//echo $timestamp = date('d-m-y G:i:s ');
echo "<br>";
echo "<br>";
echo $row[2] . "";
echo "</p>";
echo "<p>";
echo $row[3] . "";
echo "</p>";
echo 'Delete';
echo "<br>";
echo "<br>";
echo 'Comment: <br>
<input type=text name=comment><br>
<a href=addcomment.php?id=' . $row[0]. '&comment='. $row['$comment'].'>Comment</a>';
echo "<p>";
echo $row['comment'] . "";
echo "</p>";
echo "</div>";
echo "<br>";
}
?>
</div>
</body>
<div id="footer">Copyright &copy James Taylor 2016</div>
</html>
I just ran this code:
$comment = "Hello World!";
$id = 1;
$sql = "UPDATE Dbsaved SET comment = '{$comment}' WHERE id = {$id}";
echo $sql;
and saw:
UPDATE Dbsaved SET comment = 'Hello World!' WHERE id = 1
which is a correct SQL statement, so if it is not working, you might want to play with SQL directly to get something working. Hope that helps!
SOLUTION:
$comment = $_GET['$comment'];
$id = $_GET['$id'];
while ($row = mysql_fetch_array($result)) {
echo "<div id='posts'>";;
echo "<h2>";
echo $row[1] . "";
echo "</h2>";
echo "<p>";
//echo $timestamp = date('d-m-y G:i:s ');
echo "<br>";
echo "<br>";
echo $row[2] . "";
echo "</p>";
echo "<p>";
echo $row[3] . "";
echo "</p>";
echo 'Delete';
echo "<br>";
echo "<br>";
echo $row[4] . "";
echo "<br>";
echo 'Comment: <br>
<form action="addcomment.php?id=' . $row[0]. '" method="post">
<input type=text name=comment><br>
<input type=submit name="submit">
</form>';
echo "<p>";
echo $row['comment'] . "";
echo "</p>";
echo "</div>";
echo "<br>";
}
?>
and:
<?php
$db = mysql_connect("localhost", "root", "root");
if (!$db) {
die("Database connect failed: " . mysql_error());
}
$db_select = mysql_select_db("UNii", $db);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$comment = $_POST['comment'];
$id = $_GET['id'];
$sql = "UPDATE Dbsaved SET comment = '$comment' WHERE id = $id ";
$comment1 = mysql_query($sql);
echo $sql;
if (!$comment1) {
die("did not save comment: " . mysql_error());
}
else {
header("location: UniHelpindex.php");
}
It was to do with mainly needing to get the id which was used in $row[0]' in the form created in the while loop. And actually using the correct syntax for the update Dbsaved... bit.

Why will it not update to the database?

This is my code :
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="blah"; // Mysql password
$db_name="test"; // Database name
$tbl_name="SubCategories"; // Table name
$con=mysqli_connect("$host", "$username", "$password", "$db_name");
if (mysqli_connect_errno()) // Check connection
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="untitled.php" method="post"><!-- untitled.php -->
<?php
//print_r($_POST); //print all checked elements
//echo "<br>".$email, $_POST["update"][$i];
//mysql_real_escape_string ($route )
if(isset($_POST['submit'])) {
foreach ($_POST["holder"] as $i=>$email) {
$y=$email;
$h=$_POST["update"][$i];
$res2=mysqli_query("UPDATE ".$tbl_name." SET subCat2 = '" . $y . "' WHERE id =". $h,$con);
if ($res2){
}
else{
echo "<h1>NOT WORKING!</h1>";
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
}
$result = mysqli_query($con,"SELECT * FROM $tbl_name");
echo "<br>";
while($row = mysqli_fetch_array($result))
{
echo '<input type="text" name="holder[]" id="checkbox-1" class="custom" value=" ' . $row['subCat2'] . '"/>';
echo '<input type="hidden" name="update[]" id="checkbox-1" class="custom" value=" ' . $row['subCatNum'] . '"/>';
echo "<br>";
}
?>
</br>
<input type="submit" name="submit">
</form>
</body>
</html>
I can't update the table in my database. I am able to extract the variables properly and echo them, however it does not work.
I have gotten the following error in the past 'no database selected'.
I think that you forgot to select the database. Try to put this after your connection:
if (!mysqli_select_db($con, $db_name)) {
die("Uh oh, couldn't select database $db_name");
}
If this happens, double check the name, permissions, etc.
Try it again, but without the quotes surrounding the DB connection variables. I mean, they are variables & not strings, right?
Original with quotes:
$con=mysqli_connect("$host","$username","$password","$db_name");
Cleaned without quotes:
$con=mysqli_connect($host,$username,$password,$db_name);
You should change your code adding the snippet below. This way you can debug your code better:
if (!$result = $mysqli->query("YOUR-SQL", MYSQLI_USE_RESULT)) {
printf("Error: %s\n", $mysqli->error);
}
...do something here..
$result->close();
Someone in my class helped me figure it out, thanks though! Here is the code, just wonderful :)
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="blah"; // Mysql password
$db_name="test"; // Database name
$tbl_name="test_mysql"; // Table name
$con=mysqli_connect($host,$username,$password,$db_name);
if (mysqli_connect_errno()) // Check connection
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="untitled.php" method="post"><!-- untitled.php -->
<?php
if(isset($_POST['submit'])) {
foreach ($_POST["holder"] as $i=>$email) {
$y=$email;
$h=$_POST["update"][$i];
$sql2="UPDATE ".$tbl_name." SET name = '" . $y . "' WHERE id =". $h;
//$res2=mysqli_query("UPDATE ".$tbl_name." SET name = '" . $y . "' WHERE id =". $h,$con);
$res2=mysqli_query($con,$sql2);
if ($res2){
}
else{
echo "<h1>NOPE!</h1>";
print "Failed to connect to MySQL: " . mysqli_error();
}
}
}
$result = mysqli_query($con,"SELECT * FROM ".$tbl_name);
echo "<br>";
while($row = mysqli_fetch_array($result))
{
echo '<input type="text" name="holder[]" id="checkbox-1" class="custom" value=" ' . $row['name'] . '"/>';
echo '<input type="hidden" name="update[]" id="checkbox-1" class="custom" value=" ' . $row['id'] . '"/>';
//echo '<input type="text" class="a" name="holder2[]" id="checkbox-1" class="custom" value="' . $row['price'] . '" />';
echo "<br>";
}
?>
</br>
<input type="submit" name="submit">
</form>
</body>
</html>

PHP deleting from database not working

I'm trying to let the user check off which item to be deleted. When the user check off one or many items and click the Delete button, those data will be erased from the database. I've also added a search box to search for the dvd. The search box works, but the deleting doesn't. This is what it looks like in the browser.
My PHP looks like this (I took out the searching code):
<form action="" method="post">
<p><input type="text" name="search"> <input type="submit" value="Search"></p>
<p><input type="submit" name="deleting" value="Delete"></p>
</form>
<?php
$link = mysqli_connect( $host, $user, $password, $dbname);
if (!$link) {
die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';
//searching code goes here
if (isset ($_POST['deleting']) && isset ($_POST['deleteThese']) )
{
$deleteThese = implode(",", $_POST['deleteThese']);
$queryTwo = "DELETE FROM `$dbname`.`dvds` WHERE `dvds`.`DvdID` IN ($deleteThese)";
$resultTwo = mysqli_query($link, $queryTwo);
}
echo "<table border=\"1\"><tr><th>DvdTitle</th><th>RunningTime</th><th>Delete</th></tr>";
if (mysqli_num_rows($result) == 0)
echo "<tr><td colspan='2'>No records found.</td></tr>";
else {
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>" . $row['DvdTitle'] . "</td>";
echo "<td>" . $row['RunningTime'] . "</td>";
echo "<td>" . "<form>" . "<input type='checkbox' name='deleteThese[]' value='" . $row['DvdID'] . "' >" . "</form>" . "</td></tr>\n";
}
}
echo "</table>";
mysqli_free_result($result);
mysqli_close($link);
?>
Each DvdTitle has an unique Dvd ID, hence the value of each row is the dvd's ID $row['DvdID'].
Adding the parentheses will allow for those ID's to be selected for deletion.
IN($deleteThese)
EDIT
Do not close the form after the submit button. Put that at the end of the code. This will allow the form to include the checkbox values.
<form action="" method="post">
<p><input type="text" name="search"> <input type="submit" value="Search"></p>
<!-- YOUR PHP CODE -->
<p><input type="submit" name="deleting" value="Delete"></p>
</form>
2nd Edit [requested to improve code]
Move the isset on top of the form.
<?php
if (isset ($_POST['deleting']) && isset ($_POST['deleteThese']) )
{
$deleteThese = implode(",", $_POST['deleteThese']);
$queryTwo = "DELETE FROM `$dbname`.`dvds` WHERE `dvds`.`DvdID` IN ($deleteThese)";
$resultTwo = mysqli_query($link, $queryTwo);
}
?>
<form>....
$deletethese might need to have quotes around it.

Updating mysql database using While loop php

This has been bugging me for 3 days now.. I'm new to this and trying to get my head round something. I have a form which involves 3 fields. Firstname, Surname, Marks. I have used a while loop to generate the table from a mysql table. I have used a text box and used the loop to call the text box after the 'ID' so each text box is named uniquely. I am then using a post method to send values to a second page which will update the 'marks' column with the value the user has just put in.. this is where I am finding my problem!
This is the initial page.
<html>
<head><title>Please Enter Your Surname</title></head>
<body>
<center>
<h2><font color=blue>Please Enter Your Surname</font></h2><p>
<form action="insert.php" method="POST">
<?php
$db = mysql_connect("localhost","root","");
if (!$db)
{
do_error("Could not connect to the server");
}
mysql_select_db("session6",$db)or do_error("Could not connect to the database");
$result = mysql_query("SELECT * FROM members ORDER BY id",$db);
$rows=mysql_num_rows($result);
if(!$rows)
{
do_error("No results found");
}
else
{
echo "<table border=3 cellspacing=1 cellpadding=1
align=center bgcolor=lightblue>\n";
echo "<caption><h2><font color=blue> Members Details
</font></h2></caption>\n";
echo "<tr><th>Member Id</th><th>Firstname</th><th>Mark</th></tr>\n";
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td strong>" . $row['Id'] . "</td>";
echo "<td strong>" . $row['Firstname'] . "</td>";?>
<td strong><input type="text" name="<?php echo $row['Id']; ?>" size="20"></td>
<tr>
<?php
}
?><input type="hidden" name="no_of_rows" value="<?php echo $rows; ?>">
<?php
echo "</table>\n";
}
mysql_close($db) or do_error("Could not close connection");
function do_error($error)
{
echo $error;
die();
}
?>
<input type="submit" value="Search">
<input type="reset" value="Reset">
</form>
</body></html>
`
Then the update is done here which is where I seem to be having a problem:
<html>
<body>
<?php
$db = mysql_connect("localhost","root","");
if (!$db)
{
do_error("Could not connect to the server");
}
mysql_select_db("marks",$db)or do_error("Could not connect to the database");
$i=1;
while ($i <= $_POST["no_of_rows"])// or $_POST["No_of_Rows"] from form
{
$insertsql = "UPDATE members SET mark = " . $_POST[$i] . " WHERE Id = " . $row['Id'] . ";";
echo $_POST['$i'];
$i++;
}
?>
</body></html>
When I echo $_POST[$i'] it shows the correct values but does not update the DB, and I'm not about ready to throw my laptop in the bin! ha! I know it is prob going to be something stupid I just can't see what, so any help would be appreciated.
You're missing the single quotes in your update query. This would help:
$insertsql = "UPDATE `members` SET `mark` = '" . $_POST[$i] . "' WHERE `Id` = '" . $row['Id'] . "' ;";
you are also not running the mysql_query query command for the update
lastly you are using the mysql php commands which are deprecated. Use mysqli or pdo instead. and don't forget to escape data in your queries to prevent sql injections
Problem is the single quotes here, forcing to literal '$i' which probably isnt a key in $_POST
echo $_POST["$i"];
No need to use quotes when variable is used:
$_POST[$id];

Session array keeps overwriting rather than adding to itself

Ran into an issue today that I have not been able to resolve. I am trying to set up a very basic shopping cart for a project. I have a searchable form on the page searchFilm.php that will retrieve a list of 10 films based on your search criteria. This works without issue. I also have an "Add" button beside each film in the list, that also works well.
When I click "Add" it redirects to another page, as intended, called addToCart.php. This page will then display the information for the film added, which is Title and Rental Rate.
This also has worked without issue. Both pages use a central page call dbConnect.php to connect to and select from the database.
The issue I have run into is trying to create a session array that will hold the film_id of each film that I add, and add them to a table. It keeps overwriting the last value that was held in the array. I have commented out almost everything on the addToCart page to try and simplify my debugging. At this point it seems like I am perhaps starting a new session every time I click add.
I will provide the code for each page. I have been trying to figure this out for 4-5 hours without success. Hoping that another pair of eyes might see something I am missing.
Thanks.
dbConnect.php:
<?php
function connect($db)
{
if(!$db)
{
die('Could not connect to the Sakila Database: ' . mysqli_error($db));
}
return $db;
}
function select($db, $table, $id)
{
$result = mysqli_query($db, "SELECT * from " . $table . " where film_id = '" . $id . "'");
if(!$result)
{
die('Could not retrieve records from the Sakila Database: ' . mysqli_error($db));
}
return $result;
}
function searchResult($db, $table, $term)
{
$result = mysqli_query($db, "SELECT * from " . $table . " where description LIKE ('%" . $term . "%') LIMIT 0,10");
if(!$result)
{
die('Could not retrieve records from the Sakila Database: ' . mysqli_error($db));
}
return $result;
}
?>
searchFilm.php:
<html>
<head>
<title>TITLE!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<?php
include'dbConnect.php';
session_start();
if(isset($_POST['search']))
{
$term = $_POST['search'];
//connect to the database
$db = connect(mysqli_connect("localhost","root","","sakila"));
//retrieve results from the database
$result = searchResult(mysqli_connect("localhost","root","","sakila"),'film', $term);
//echo the title and description of each row
echo "<table border=1 bordercolor=red>";
echo "<tr>";
echo "<th>Title</th>";
echo "<th>Description</th>";
echo "<th>Add To Cart</th>";
echo "</tr>";
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['title'] . "</td> <td>" . $row['description'] . "</td>";
?>
<td>
<form name="addToCart" action="addToCart.php" method="POST">
<input type="hidden" name="filmID" value="<?php echo $row['film_id']; ?>" />
<input type="submit" name="addToCart" value="Add" />
</form>
</td>
<?php
echo "</tr>";
}
echo "</table>";
mysqli_close($db);
}
?>
<form method="post" action="searchFilm.php" name="">
<p>Search:
<input name="search" type="text" value="" />
</p>
<p>
<input name="" type="submit">
</p>
</form>
</body>
</html>
addToCart.php:
<?php
include('dbConnect.php');
if(isset($_POST['filmID']))
{
$id = $_POST['filmID']; //the item selected
$_session['cart'][] = $id;
foreach ($_session['cart'] as $item)
{ //display contents of array
echo "$item<br />";
}
/*$filmid = $_POST['filmID'];
$_SESSION['cart'][$filmid];
$db = connect(mysqli_connect("localhost","root","","sakila"));
$select = select(mysqli_connect("localhost","root","","sakila"),'film', $filmid);
echo "<table border=1 bordercolor=red>";
echo "<tr>";
echo "<th>Film</th>";
echo "<th>Rental Rate</th>";
echo "</tr>";
while($row = mysqli_fetch_assoc($select))
{
echo "<tr>";
echo "<td>" . $row['title'] . "</td> <td>" . $row['rental_rate'] . "</td>";
echo "</tr>";
}
echo "</table>";*/
}
?>
<html>
<head>
<title>TITLE!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
click to go back
</body>
</html>
Sorry for the length. Just wanted to make sure that all information was there.
Any insight would be appreciated.
Thanks!
PS. I know my database is very insecure. It's just full of dummy data and run every once in a while on a VM, so I don't really care. :P
1) Try starting the session in addToCart.php
2) As far as I know, $_session won't work, it should be $_SESSION
addToCart.php should call session_start(); and it doesn't as far as I can see.
I believe the issue is that there doesn't appear to be a call to session_start() in the addToCart.php file.
Since you aren't starting a session, none of the previous data is available. Essentially you are creating an array called $_SESSION and adding your cart array to it.
This results in using an array with the same name as PHP's session array, but it is not based off of an existing session.

Categories