I am new to php and SQL and just toying around with a project for my own understanding of accessing, updating and deleting data from my Database.
I have managed to show the selected data, create a button to delete a specific Id but really needing some assistance with deleting the selected row or record instead of hard coding in the ID in my delete php script.
Here is an example of my script:
<?php
$sql = "SELECT id, firstname, lastname, joinDate FROM customers";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
"<div class='trow'>" .
$row["id"]. ": " .
$row["firstname"] . " " .
$row["lastname"]. " " .
$row["joinDate"]. " " .
"<span class='deleteMember'>
<form action='deleteMember.php' method='POST'>
<button type='submit'>Delete</button>
</form>
</span>" . " " .
"<span class='editMember'><a href='#'>Edit</a></span>" .
"<br></div>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Here is the delete.php
<?php
// sql to delete a record
$sql = "DELETE FROM customers WHERE id='6' ";
if ($conn->query($sql) === TRUE) {
header("Location: index.php");
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
what I would like it to do is, delete the row from which you hit the delete button from and not just delete the row I have specified in the delete.php script. I understand HOW it should work by posting the id but not sure how to do it.
Do like this
<?php
// sql to delete a record
$sql = "DELETE FROM customers WHERE id='".$_GET['id']."' ";
if ($conn->query($sql) === TRUE) {
header("Location: index.php");
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
<?php
$sql = "SELECT id, firstname, lastname, joinDate FROM customers";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
"<div class='trow'>" .
$row["id"]. ": " .
$row["firstname"] . " " .
$row["lastname"]. " " .
$row["joinDate"]. " " .
"<span><a href='deleteMember.php?id=".$row['id']."'>Delete</a></span>" .
"<span class='editMember'><a href='#'>Edit</a></span>" .
"<br></div>";
}
} else {
echo "0 results";
}
$conn->close();
?>
in place of your form use this
DELETE
and in your delete query must be like below
$sql = "DELETE FROM customers WHERE id='".$_GET['id']."' ";
or stay in your post form with:
while($row = $result->fetch_assoc()) {
echo
"<div class='trow'>" .
$row["id"]. ": " .
$row["firstname"] . " " .
$row["lastname"]. " " .
$row["joinDate"]. " " .
"<span class='deleteMember'>
<form action='deleteMember.php' method='POST'>
<input type='hidden' name='myid' value='".$row['id']."' />
<button type='submit'>Delete</button>
</form>
</span>" . " " .
"<span class='editMember'><a href='#'>Edit</a></span>" .
"<br></div>";
}
And in your delete.php :
<?php
$id=(int) $_POST['myid'];
// sql to delete a record
$sql = "DELETE FROM customers WHERE id=".$id;
if ($conn->query($sql) === TRUE) {
header("Location: index.php");
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
No need to add extra form element for Delete or Edit purpose. Try this way to pass the id of row for Eelete or Edit operation
while($row = $result->fetch_assoc())
{
$id=$row['id'];// capture your row id & pass to your delete & edit
echo
"<div class='trow'>" .
$row["id"]. ": " .
$row["firstname"] . " " .
$row["lastname"]. " " .
$row["joinDate"]. " " .
"<span class='deleteMember'>
<a href='deleteMember.php?id=<?=$id;?>'>Delete</a>
</span>" . " " .
"<span class='editMember'>
<a href='editMember.php?id=<?=$id;?>'>Edit</a>
</span>" .
"<br>
</div>";
}
EDIT:
Then catch the id on your relevant page for your operation.
//deleteMember.php
<?php
$id=$_GET['id'];
// sql to delete a record
$sql = "DELETE FROM customers WHERE id='".$id."'";
if ($conn->query($sql) === TRUE) {
header("Location: index.php");
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
Note: Please Use Prepared Statements of PDO or MYSQLi instead to avoid SQL Injection and manual escaping.
Related
I am making e-commerce site and add to basket script not doing anything
I expect it to insert data into shopping basket from products page that is working perfectly fine. Please have a look and help me figure it out.. it is not giving any syntax error or parse error it just dont do anything and when I click buy it just redirect me to homepage
<?php
error_reporting(E_ALL);
session_start();
require("db.php");
require("functions.php");
$validid = pf_validate_number($_GET['id'], "redirect", $config_basedir);
$prodsql = "SELECT * FROM products WHERE id = " . $_GET['id'] . ";";
$prodres = mysqli_query($prodsql);
$numrows = mysqli_num_rows($prodres);
$prodrow = mysqli_fetch_assoc($prodres);
if($numrows == 0)
{
header("Location: " . $config_basedir);
} else {
if($_POST['submit'])
{
if($_SESSION['SESS_ORDERNUM'])
{
$itemsql = "INSERT INTO orderitems(order_id, product_id, quantity) VALUES("
. $_SESSION['SESS_ORDERNUM'] . ", "
. $_GET['id'] . ", "
. $_POST['amountBox'] . ")";
mysqli_query($itemsql);
} else {
if($_SESSION['SESS_LOGGEDIN'])
{
$sql = "INSERT INTO orders(customer_id, registered, date) VALUES("
. $_SESSION['SESS_USERID'] . ", 1, NOW())";
mysqli_query($sql);
session_register("SESS_ORDERNUM");
$_SESSION['SESS_ORDERNUM'] = mysqli_insert_id();
$itemsql = "INSERT INTO orderitems(order_id, product_id, quantity) VALUES("
. $_SESSION['SESS_ORDERNUM']
. ", " . $_GET['id'] . ", "
. $_POST['amountBox'] . ")";
mysqli_query($itemsql);
} else {
$sql = "INSERT INTO orders(registered, date, session) VALUES("
. "0, NOW(), '" . session_id() . "')";
mysqli_query($sql);
session_register("SESS_ORDERNUM");
$_SESSION['SESS_ORDERNUM'] = mysqli_insert_id();
$itemsql = "INSERT INTO orderitems(order_id, product_id, quantity) VALUES("
. $_SESSION['SESS_ORDERNUM'] . ", " . $_GET['id'] . ", "
. $_POST['amountBox'] . ")";
mysqli_query($itemsql);
}
}
$totalprice = $prodrow['price'] * $_POST['amountBox'] ;
$updsql = "UPDATE orders SET total = total + "
. $totalprice . " WHERE id = "
. $_SESSION['SESS_ORDERNUM'] . ";";
mysqli_query($updres);
header("Location: " . $config_basedir . "showcart.php");
} else {
require("header.php");
echo "<form action='addtobasket.php?id="
. $_GET['id'] . "' method='POST'>";
echo "<table cellpadding='10'>";
echo "<tr>";
if(empty($prodrow['image']))
{
echo "<td><img src='./productimages/dummy.jpg' width='50' alt='"
. $prodrow['name'] . "'></td>";
} else {
echo "<td><img src='./productimages/" . $prodrow['image']
. "' width='50' alt='" . $prodrow['name']
. "'></td>";
}
echo "<td>" . $prodrow['name'] . "</td>";
echo "<td>Select Quantity <select name='amountBox'>";
for($i=1;$i<=100;$i++)
{
echo "<option>" . $i . "</option>";
}
echo "</select></td>";
echo "<td><strong>£"
. sprintf('%.2f', $prodrow['price'])
. "</strong></td>";
echo "<td><input type='submit' name='submit' value='Add to basket'></td>";
echo "</tr>";
echo "</table>";
echo "</form>";
}
}
require("footer.php");
error_reporting(E_ALL);
?>
there are two redirects that makes your user return to your home page
first:
$validid = pf_validate_number($_GET['id'], "redirect", $config_basedir);
make sure $_GET['id] has valid value
second:
$prodsql = "SELECT * FROM products WHERE id = " . $_GET['id'] . ";";
$numrows = mysqli_num_rows($prodres);
// ...
if($numrows == 0)
{
header("Location: " . $config_basedir);
}
check your query in this line:
$prodsql = "SELECT * FROM products WHERE id = " . $_GET['id'] . ";";
make sure it returns not an empty results ( $numrows == 0 )
Test it first on your DBMS front-end
This is the code I'm using for deleting row from my DB:
<?php
$eid = $_GET['eid'];
$con = mysqli_connect("localhost", "root", "","project") or die("Connection failed");
echo "connection is done";
$query = "delete from exam where eid='$eid'";
if ($con->query($query)==TRUE)
{
echo " record deleted";
}
else
{
echo "Error: " . $query . "<br>" . $con->error;
}
$con->close();
?>
The else statement is not getting executed. It displays "record deleted" for every value even if the value is not found in the database.
Why is this happening? how can I verify that my record has been deleted from my DB?
You can use mysqli.affected-rows.
Consider the following:
$query="delete from exam where eid='$eid'";
if ($con->query($query)==TRUE && $con->affected_rows > 0) {
echo " record deleted";
} else {
echo "Error: " . $query . "<br>" . $con->error;
}
I am having a problem displaying a JOIN statement. When I add
WHERE id = " . $team_id;
The information that is on the database will not display, but when I remove that line the information will correctly join and display on the "teaminfo.php " page, but it will display all of the data instead of the data that is unique to that id. Also when I remove the JOIN the the data that is unique to the id will display. Can anyone tell me whats wrong here. Any help will be great. Than you.
teaminfo.php
<html>
<head>
<title>Team Info page</title>
</head>
<body>
<?php
include 'connect.php';
$team_id = $_GET['id'];
// SQL query
$query = " SELECT *
FROM pitscouting
JOIN fieldscouting
ON pteam_number = fteam_number
WHERE id = " . $team_id;
if ($result = mysqli_query($mysqli, $query)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
// Write the data of the team
echo "<br />";
echo "Pit scouting";
echo "<dt>Team:</dt><dd>" . $row["pteam_number"] . " " . $row["pteam_name"] . "</dd>";
echo "<dt>Auto:</dt><dd>" . $row["pauto"] . "</dd>";
echo "<dt>Drive:</dt><dd>" . $row["pdrive"] . "</dd>";
echo "<dt>Objetcs With No Problem?</dt><dd>" . $row["pobjNoProblem"] . "</dd>";
echo "<dt>Objects They have a problem with?</dt><dd>" . $row["pobjWithProblem"] . "</dd>";
echo "<dt>Can they shoot? If yes from where and how acc</dt><dd>" . $row["pshoot"] . "</dd>";
echo "<dt>Extra Notes about their robot?</dt><dd>" . $row["pdrive"] . "</dd>";
echo"<br />";
echo "Field Scouting ";
echo "<dt>Team Number:</dt><dd>" . $row["fteam_number"] . "</dd>";
echo "<dt>Auto:</dt><dd>" . $row["fauto"] . "</dd>";
echo "<dt>Drive:</dt><dd>" . $row["fdrive"] . "</dd>";
echo "<dt>Objetcs With No Problem?</dt><dd>" . $row["fobjNoProblem"] . "</dd>";
echo "<dt>Objects They have a problem with?</dt><dd>" . $row["fobjWithProblem"] . "</dd>";
echo "<dt>Shots taken</dt><dd>" . $row["fshots_taken"] . "</dd>";
echo "<dt>Shorts made</dt><dd>" . $row["fshots_made"] . "</dd>";
echo "<dt>Extra Notes</dt><dd>" . $row["fnotes"] . "</dd>";
}
mysqli_free_result($result);
}
// Close the database connection
mysqli_close($mysqli);
?>
<p>Return to the list</p>
</body>
</html>
Palmetto.php
<?php
include 'connect.php';
// SQL query
$query = "SELECT * FROM pitscouting ORDER BY pteam_number";
if($result = mysqli_query($mysqli, $query)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
$name = $row['pteam_number'] . " " . $row['pteam_name'];
// Create a link to teaminfo.php with the id-value in the URL
$strLink = "<a href = 'teaminfo.php?id= " . $row['id'] . "'>" . $name . "</a>";
// List link
echo "<li>" . $strLink . "</li>";
}
echo "</table>";
// Close result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $query. " . mysqli_error($mysqli);
}
// Close connection
mysqli_close($mysqli);
?>
If your tables both have an ID field you will have to specify which table you want to get the data from.
WHERE pitscouting.id = " . $team_id;
or
WHERE fieldscouting.id = " . $team_id;
Please do mention the sql injection in you're code
$team_id = $_GET['id'];
// SQL query
$query = " SELECT *
FROM pitscouting
JOIN fieldscouting
ON pteam_number = fteam_number
WHERE id = " . $team_id;
please take a look at prepared statements, to prevent sql injections in youre code
Try putting an alias.
$team_id = $_GET['id'];
// SQL query
$query = " SELECT *
FROM pitscouting p
JOIN fieldscouting f
ON p.pteam_number = f.fteam_number
WHERE p1.id = " . $team_id;
How do you update only one row when you fetch for multiple rows? I am lost on how to do this. I can fetch for one row, update and it works. However, I'm stuck for multiple rows.
Down below is my code
FETCH PHP:
//loop through for results
while($row = mysqli_fetch_array($data)){
echo "<tr><td>"
. $row['title']."<input type='hidden' value='".$row['title']."' name='title'>"
. "</td><td>"
. $row['author']
. "</td><td>"
. $row['summary']
. "</td><td>"
. $row['isbn']
. "</td><td>"
. "<img src='books/".$row['image']."' width='100%'/>"
. "</td><td>"
. "$<input type='text' value='".$row['price']."' size='8' class='pricetoright' name='price'>"
. "</td><td>"
. "<button type='submit' class='btn btn-default btngreen' name='update'>Update</button>"
. "</td><td>"
. "<button type='submit' class='btn btn-default btnred' name='delete'>Delete</button>"
. "</td></tr>";
}
UPDATE PHP:
// Check Connection
if(!($db = mysqli_connect($server, $user, $password, $database))) {
die('SQL ERROR: Connection failed: '.mysqli_error($db));
}
$price = floatval($_POST["price"]);
$title = $_REQUEST["title"];
// SQL to update a record
$query = "UPDATE books SET price = '$price' WHERE title = '$title'";
if (mysqli_query($db, $query)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($db);
}
mysqli_close($db);
Use form tag for each row. Also its better to use unique id to update row instead of title. So take hidden input of id.
You'd want to add a foreach() statement into your code. While it's a little unclear on your code here's a possible example:
foreach($_POST as $k=>$v){
if($k === "title"){
$title = $_POST["title"];
}
if($k === "price"){
$price = floatval($_POST["price"]);
}
// SQL to update a record
$query = "UPDATE books SET price = '$price' WHERE title = '$title'";
if (mysqli_query($db, $query)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($db);
}
}
Okay so my code works pretty well so far, it all goes through, my only problem is that when I try and print the unordered list and it's contents I get nothing. When I view my source code I have <ul> </ul>. There's a space, so surely something is happening.
This is my code, I have commented it slightly but what's happening is obvious:
$uname = mysqli_real_escape_string($link, $_SESSION['Username']); //Get username ready
$sql = mysqli_query($link, "SELECT * FROM users WHERE Username = '" . $uname . "'"); //SQL Query result
if(!$sql)
{
echo "Error retrieving User ID. Please try again. MySQL Error: " . mysqli_error($link);
}
elseif($row = mysqli_fetch_assoc($sql))
{
$uid = $row['UserID']; //Obtain UserID
}
else
{
echo "Error: " . mysqli_error($link) . "<br />" . $uname . " / " . $sql . " / " . $uid;
}
mysqli_free_result($sql);
$sql = mysqli_query($link, "SELECT * FROM auditions"); //Get everything from the auditions table
if(!$sql)
{
echo "Error retrieving auditions. Please try again later. Error: " . mysqli_error($link);
}
elseif($row = mysqli_fetch_assoc($sql))
{
if(mysqli_num_rows($sql)==0)
{
echo "Sorry, there are currently no open auditions. Please try back at a later date.";
}
else
{
echo "<ul>";
while($row = mysqli_fetch_assoc($sql))
{
echo "<li><a href='auditions.php?id=" . $row['AudID'] . "'>" . $row['AudName'] . "</a></li>";
}
echo "</ul>";
}
}
else
{
echo "Error: " . mysqli_error($link);
}
Where am I going wrong? The only thing it doesn't do is actually pick up any results and I've put some data into the table so there are entries! Otherwise it would say there aren't any. I've reversed this so it shows the message if there aren't 0 entries and that works. What am I doing wrong guys?
Thanks in advance.
You are fetching the result twice. Instead, only fetch the result in the while loop:
<?php
$sql = mysqli_query($link, "SELECT * FROM auditions"); //Get everything from the auditions table
if(!$sql)
{
echo "Error retrieving auditions. Please try again later. Error: " . mysqli_error($link);
}
else{
if(mysqli_num_rows($sql)==0)
{
echo "Sorry, there are currently no open auditions. Please try back at a later date.";
}
else
{
echo "<ul>";
while($row = mysqli_fetch_assoc($sql))
{
echo "<li><a href='auditions.php?id=" . $row['AudID'] . "'>" . $row['AudName'] . "</a></li>";
}
echo "</ul>";
}
}
?>
See this link for more information regarding mysql_fetch_assoc