DELETE link does nothing in PHP when removing data from PHPMyAdmin - php

I have created a table in PHPMyAdmin, and I have connected to it via a localhost. My PHP code displays the data in a table.
I want to be able to delete a certain row, so I created a html/php link to delete the row within a table.
My problem is that whenever I press delete, the page just refreshes without an error but the record is still there.
Is there something missing within my code?
<?php
// Connect to the database
$username="root";$password="test";$database="products";
// Connect to the MySQL server and select the required database
$connection = new mysqli("localhost",$username,$password, $database);
$sql = "";
$sql = "SELECT * FROM products";
$ID = isset($row['ID']) ? $row['ID'] : '';{
$query = mysqli_query($connection, "DELETE FROM products WHERE ID=$ID");
}
$result = $connection->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<tr>\n";
echo "<td>" . $row['Name'] . "</td>\n";
echo "<td>" . $row['Description'] . "</td>\n";
echo "<td>" . $row['Price'] . "</td>\n";
echo "<td>" . $row['Cost_Price'] . "</td>\n";
echo "<td>" . $row['Stock'] . "</td>\n";
echo "<td>" . $row['EAN'] . "</td>\n";
?>
<td><a href="?mode=delete&ID=<?php echo $row["ID"]; ?>"
title="Delete <?php echo $row["ID"]; ?>">Delete</a></td>
<?php
echo "</tr>\n";
}
}
$stmt = $connection->prepare('SELECT * FROM products WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
$connection->close();
?>

Change
$ID = isset($row['ID']) ? $row['ID'] : '';{
$query = mysqli_query($connection, "DELETE FROM products WHERE ID=$ID");
}
To
if(isset($_GET['ID']) && ($_GET['mode'] == 'delete')) {
$ID = $_GET['ID'];
$query = mysqli_query($connection, "DELETE FROM products WHERE ID=$ID");
}
Explanations
When after clicking delete link, it comes to this line
$ID = isset($row['ID']) ? $row['ID'] : '';{.
Here, $row['ID'] is not set. So, $ID set to "" as you declared in your code. So, DELETE statement is not able to find that product which you wanted to delete.
Actually, in delete link. You are passing 2 variables. One is mode and other is ID of product. Catch those 2 variables through $_GET as I mentioned in my answer.
Quick Links
How to set $_GET variable
$_GET : PHP Manual

Related

Data from mysql is not getting retrieved on every page refresh

Iam trying to fetch the random data from mysql database, but it only fetches the same row on page refresh
I tried to run the query to get the random single row data from mysql and display on the webpage using php, but it only retrieving only the same row every time
$sql = "SELECT * FROM identity_explorer_demographics ORDER BY RAND() LIMIT 1
<?php
$link = mysqli_connect("host", "username", "password", "db_name");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM identity_explorer_demographics ORDER BY RAND() LIMIT 1";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>email_md5</th>";
echo "<th>age_group </th>";
echo "<th>age</th>";
echo "<th>income</th>";
echo "<th>Income_group </th>";
echo "<th>gender</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['email_md5'] . "</td>";
echo "<td>" . $row['age_group'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['income'] . "</td>";
echo "<td>" . $row['Income_group'] . "</td>";
echo "<td>" . $row['gender'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
I need the random row data to be displayed everytime the page is refreshed. Will really be helpful if anyone can suggest be the best solution.
$sql = "SELECT * FROM identity_explorer_demographics ORDER BY RAND()
LIMIT 1";
Change the line to
$randomv=rand(min,max);
$sql = "SELECT * FROM identity_explorer_demographics ORDER BY $randomv
LIMIT 1";
Here is my implementation in another case where I have to choose from a random id available - Yii 2 Framework
$prodcutids= \app\models\TblProduct::find()->all();
$targetproduct= ArrayHelper::map($prodcutids, 'id','id');
$productdetails= \app\models\TblProduct::findOne(['id'=>array_rand($targetproduct)]);
$productseriesname= \app\models\TblSeries::findOne(['id'=>$productdetails['Serie']]);
Or if you have an id column
$sql = "SELECT * FROM identity_explorer_demographics WHERE id=$randomv
LIMIT 1";
rand(min,max)
min specifies the lowest value that will be returned.
max specifies the highest value to be returned.
You mix it with PHP
$sql = 'SELECT * FROM `identity_explorer_demographics`';
//Perform query and parse result, E.G $sql = db::query($sql);
function getRandomRow($sql) {
$random_row = count(0, count($sql));
foreach($sql as $row => $result) {
if ($row == $random_row) {
return $row;
}
}
}

How to use MySQL query results as options in HTML forms

<?php
$con = new mysqli('localhost', 'root' ,'', 'world');
$query = 'SELECT * FROM city ORDER BY Name';
if ($result = mysqli_query($con, $query)) {
echo "<table>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>"
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['CountryCode'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_free_result($result);
}
mysqli_close($con);
?>
This simple code will display every entries in this database. Now I would like to add a selective display option by choosing the CountryCode.
$query2 = 'SELECT DISTINCT CountryCode FROM city ORDER BY CountryCode';
How do I use the result I got from the query above and make it become radio buttons to choose what to display?
Similar to what you are doing already: Something like
while ($row = mysqli_fetch_assoc($result)) {
echo "<input type='radio' name='whatever' value='".$row['Name']."'>". $row['Name'];
}
Ofcourse the field names can be whatever you like them to be, as long as you select them in the query

Php Does not loop, provides only one item in the other page, edit

Edited: My first problem was solved, but another problem came up, only one user id is provided. So here is the screenshot of the revised code.
Going back to the table, The user will press edit button, so he can edit the problem and give appropriate action..
My code for the table above is this:
<form action="edit.php" method="get">
<?php
$result = mysqli_query($con,"SELECT * FROM complaints");
echo "<table border='1'>
<tr>
<th>Id Number</th>
<th>Category</th>
<th>Problem</th>
<th>Date Reported</th>
<th>Action</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td name=id_number>" . $row['id_number'] . "</td>";
echo "<td name=remarks>" . $row['remarks'] . "</td>";
echo "<td name=status>" . $row['status'] . "</td>";
echo "<td name=date>" . $row['date_reported'] . "</td>";
echo "<td>" . "<INPUT TYPE = Submit Name = Submit1 VALUE =Edit>" . "</td>";
echo "</tr>";
}
echo "</table>"; ?> </form>
My code for the edit.php is this: [for the user id part]:
User ID: <input type='text' disabled='disables' name='userid'placeholder='<?php
$userid = $_GET["userid"];
$result2 = mysql_query("SELECT * FROM complaints WHERE id_number = '$userid'", $link);
while($row = mysql_fetch_array($result2))
{
echo $row['id_number'];
}
?>'></br>
Now, I am having difficulty, on the user id part, because only one user id show which is the 201010005 id, and the user id to be shown is the one in line with the edit that has been pressed by the user.
Any help would be appreciated.
You need to pass the id of the user that you are going to edit, so in the form add another input, but hidden with the id value, like this:
echo "<td>" . "<INPUT TYPE = hidden Name = userid VALUE = " . $row['id_number'] . ">" . "</td>";
Then in the edit page you´ll grab the user and set the query with the WHERE conditional like this:
$userid = $_GET['userid'];
$result = mysqli_query($con,"SELECT * FROM complaints WHERE id_number = '$userid'");
$result = mysqli_query($con,"SELECT * FROM complaints WHERE id = XXX");
$row = mysqli_fetch_assoc($result);
print_r($row);

Sort and Pagination combined, PHP with SQL

I've got a CV database, you can see the fields below and they are pretty standard. Retrieval is done by a simple form sending the information into an SQL database.
I was happy with my simple system till I was flooded with over 500 applicants in my inbox. My previous system allowed me to view the applicants only one by one which would have taken forever...
What I'm trying to achieve is a simple backend page similar to the phpmyadmin of the table view. (no i don't want to just use phpmyadmin as i'd like to give the CV sifting task to other employees)
Basically the concept is to display the table like an excel, allow sorting by clicking on headers, pagination [20 rows per page] and a check box to delete row.
I'm ok with asking for some help as I have put alot of effort into trying to figure this out ;)
So far what i've got is:
The sorting works no problem, clicking on one of the headers spits out localhost/mena/new3.php?sort=fname to the address bar and parses the correct Sql query and sorts the page.
The pagination so far does not work. The page displays all 815 candidates. It is providing the numbered links 1-42 that when clicked on result in the address bar changing to localhost/new3.php?page=2 but 0 change.
Also for the life of me i can't see how to include the php delete into this..
9 yo pseudo code idea of it is :
//Input the rows from SQL
While($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td> $checkbox1
if checkbox1=true then mysqli_query($con,"DELETE FROM cv WHERE .$row[].");
echo "<td>" . $row['title'] .
My code so far:
<?php
$con=mysqli_connect("localhost","root","","test_db-jil");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Pagination
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * 20;
// Sort, from headers.
if(isset($_REQUEST['sort'])){
if($_GET['sort'] == "title"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY title");
}
elseif($_GET['sort'] == "fname"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY fname");
}
elseif($_GET['sort'] == "lname"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY lname");
}
elseif($_GET['sort'] == "gender"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY gender");
}
elseif($_GET['sort'] == "dob"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY dob");
}
elseif($_GET['sort'] == "nationality"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY nationality");
}
elseif($_GET['sort'] == "language"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY language");
}
elseif($_GET['sort'] == "phone"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY phone");
}
elseif($_GET['sort'] == "email"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY email");
}
elseif($_GET['sort'] == "uni"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY uni");
}
elseif($_GET['sort'] == "prog"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY prog");
}
elseif($_GET['sort'] == "graddate"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY graddate");
}
elseif($_GET['sort'] == "startdate"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY startdate");
}
elseif($_GET['sort'] == "grad"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY grad");
}
else{
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY fname");
}
}
else{ // Default if no parameters passed
$result = mysqli_query($con,"SELECT * FROM cv");
}
//Table of Content
echo "<table border='1'>
<tr>
<th><a href=new3.php?sort=title>Title</a></th>
<th><a href=new3.php?sort=fname>First Name</a></th>
<th><a href=new3.php?sort=lname>Last Name</a></th>
<th><a href=new3.php?sort=gender>Gender</a></th>
<th><a href=new3.php?sort=dob>Date Of Birth</a></th>
<th><a href=new3.php?sort=nationality>Nationality</a></th>
<th><a href=new3.php?sort=language>Language</a></th>
<th><a href=new3.php?sort=phone>Phone No</a></th>
<th><a href=new3.php?sort=email>Email</a></th>
<th><a href=new3.php?sort=uni>University</a></th>
<th><a href=new3.php?sort=prog>Program</a></th>
<th><a href=new3.php?sort=graddate>Graduated</a></th>
<th><a href=new3.php?sort=startdate>Start Date</a></th>
<th><a href=new3.php?sort=grad>Applying for</a></th>
<th>CV File</th>
</tr>";
//Input the rows from SQL
While($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['fname'] . "</td>";
echo "<td>" . $row['lname'] . "</td>";
echo "<td>" . $row['gender'] . "</td>";
echo "<td>" . $row['dob'] . "</td>";
echo "<td>" . $row['nationality'] . "</td>";
echo "<td>" . $row['language'] . "</td>";
echo "<td>" . $row['phone'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['uni'] . "</td>";
echo "<td>" . $row['prog'] . "</td>";
echo "<td>" . $row['graddate'] . "</td>";
echo "<td>" . $row['startdate'] . "</td>";
echo "<td>" . $row['grad'] . "</td>";
echo "<td>" . $row['cvfilename'] ."</td>";
echo "</tr>";
}
echo "</table>";
//Get total count of rows then ceil divide by 20 as pages
$sql = "SELECT COUNT(*) as 'num' FROM cv";
$total_pages = $con->query($sql) or die(mysqli_error($connection));
$row = $total_pages->fetch_assoc();
$total_pages = ceil($row['num'] / 20);
for ($i=1; $i<=$total_pages; $i++) {
//Can I ?page= and ?sort= ??????
echo "<a href='new3.php?page=".$i."'>".$i."</a> ";
};
mysqli_close($con);
?>
Recap, please help me fix pagination, have it work with sort and finally add a delete check box to each row. :)
You know you can optimize that entire block of "else if" statements by just assigning the
$_GET to a variable:
$type = $_GET;
Then use that in your mysqli:
$result = mysqli_query($con, "SELECT * FROM cv ORDER BY $type");
To limit your results use LIMIT:
$result = mysqli_query($con, "SELECT * FROM cv ORDER BY $type LIMIT 20, $page");
20 = how many to return
$page = where you want the results to start from

How To Edit/Delete Stored Data From Database In PHP

EDIT
I have a mysql table with fields as follows:
Products - serial, name, description, price, picture.
the viewproducts.php page is as follows:
<?php
$result = mysql_query("SELECT * FROM products ")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Products';
} else {
echo "<table border='0'><table border='1' width=100%><tr><th>Product Name</th><th>Description</th><th>Price</th><th>Image</th><th>Edit</th><th>Delete</th>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name']. "</td>";
echo "<td>" . $info['description']. "</td>";
echo "<td>£" . $info['price']." </td>";
echo "<td>" . "<img src='../getImage.php?id=" . $info['serial'] ."'/></td>";
echo '<td> Edit</td>';
}
}
echo "</tr>";
echo "</table>";
?>
my edit.php page looks like this:
<?php
$product_id = $_GET['serial'];
$result = mysql_query("SELECT * FROM products WHERE serial = '$product_id'")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Products';
} else {
echo "<table border='0'><table border='1' width=100%><tr><th>Product Name</th><th>Description</th><th>Price</th><th>Image</th><th>Edit</th><th>Delete</th>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name']. "</td>";
echo "<td>" . $info['description']. "</td>";
echo "<td>£" . $info['price']." </td>";
echo "<td>" . "<img src='../getImage.php?id=" . $info['serial'] ."'/></td>";
}
}
echo "</tr>";
echo "</table>";
?>
when i click on edit from thr viewproducts.php page, it goes to edit.php page where nothing is showing up. the serial id on the address bar is coming up as follows:
http://www.********.com/****/admin/edit.php?product_id=
I want to be able to edit any product clicked on from the viewproduct.php page and transfered to edit.php page. I dont think my edit.php page is set up corretly.
Please help,
Thanks
You can pass via $_GET the id of the product and then, in the edit/delete page, retrieve that parameter. Obviously you have to sanitize the input properly before using it. For example, the link of the each product should look like this:
echo '<td>Edit</td>';
In the edit page you should have something like:
$id = $_GET['id'];
// For example, if the product id is an integer
// you can sanitize it doing this
$id = (int) $id
You could pass it as an argument to your php file in wich you want to edit/delete the product:
Edit Product
Then in your edit.php you will pick up the id of the product and load it's data from the database.
[edit.php]
$product_id = isset($_GET['product_id']) ? intval($_GET['product_id']) : null;
if(!$product_id) {
exit();
}
// query your database for the product
$row = mysqli_query("SELECT * FROM <table> WHERE product_id = $product_id");
// then you output your html with fields populated from the result from the database

Categories