PHP delete functionality probably logical error - php

In the top of my admin PHP (admin.php), I have loaded data from "Sport" table in "DogSport" MySQL database. After clicking "Edit" link of a particular record, I can
edit, delete that record on "editform2.php". Even on that page, I can also insert a new record.
Problem: Deleting first and second records do not work! Deleting all following records work fine. This problem only with deleting functionality.
Code segment - admin.php
<?php
include("dbconnect.inc.php");
//Retrieving Data
$query1="SELECT * FROM Sport ORDER BY SportId ASC";
$result2=mysqli_query($con, $query1);
$rows=mysqli_num_rows($result2);
$i=0;
if($rows==0)
echo "<br/>There are no records";
else{
echo "<table id='sport'>";
echo "<tr><th>Sport Id</th><th>Sport Name</th><th>Description</th></tr>";
while ($row = mysqli_fetch_array($result2))
{
echo "<tr><td>" . $row["SportId"] . "</td><td>" . $row["SportName"] . "</td><td>" . $row["Description"] .
"</td><td> <a href='editform2.php?id=" . $row["SportId"] . "' target='_blank'>Edit</a></td></tr>";
$i++;
}
echo "</table>";
}
?>
Code segment - editform2.php
if(isset($_POST["delete"])){
include("dbconnect.inc.php");
$query3="DELETE FROM Sport WHERE SportId=$id";
mysqli_query($con, $query3);
echo "<h1>Deleted Successfully</h1>";
mysqli_close($con);
}
I have uploaded necessary files, you can also use to check it including database .sql script. Your help is appreciated.
https://www.dropbox.com/s/wn40u93oa1sxcph/SO.rar?dl=0

$query3="DELETE FROM Sport WHERE SportId=$id";
Where did you set value of $id? It should be $_POST["id"] right?
As a side note - SQL injection risk ...

Related

How to get user information from a MYSQL local database

Hey i need to get information from a database and display it on my index.php.
<html>
<body>
<?php
$connection = mysql_connect('localhost', 'root', ''); //The Blank string is the password
mysql_select_db('users');
$query = "SELECT * FROM employee"; //You don't need a ; like you do in SQL
$result = mysql_query($query);
echo "<table>"; // start a table tag in the HTML
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['age'] . "</td></tr>"; //$row['index'] the index here is a field name
}
echo "</table>"; //Close the table in HTML
mysql_close(); //Make sure to close out the database connection
?>
</body>
</html>
however this will show the information for all of the users in the database.
I have a primary key in the database, which is the account number, could we use this to only display information about that account on the page only?
I will also need to save the details into variables on the php page so some guidance doing that would be greatfull.
Thanks Oliver
In order to retrieve data according to a specific user you must explicitly tell mysql. So, add WHERE id={the I'd u want the info for}.
For your second question. "How do u get the id when the user logs in".
The answer to this is you can (a) how a session initialized at login or (b) how another file or even a loop in the script you need the Id for to run a query for the users name and then you get the Id.
The draw backs of option b is that you are slowing this done and are doing alot of call which can crash your overall site.
The choice is your this is how you can get a particular I'd for a user.
<?php
include('session.php');
?>
<html>
<body>
<?php
$connection = mysql_connect('localhost', 'root', 'Oliver'); //The Blank string is the password
mysql_select_db('users');
$query = "SELECT * FROM username WHERE username='$login_session'"; //You don't need a ; like you do in SQL
$result = mysql_query($query);
echo "<table>"; // start a table tag in the HTML
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['username'] . "</td></tr>"; //$row['index'] the index here is a field name
echo "<tr><td>" . $row['sex'] . "</td><td>" . $row['phone'] . "</td></tr>"; //$row['index'] the index here is a field name
echo "<tr><td>" . $row['email'] . "</td><td>" . $row['password'] . "</td></tr>"; //$row['index'] the index here is a field name
}
echo "</table>"; //Close the table in HTML
mysql_close(); //Make sure to close out the database connection
?>
</body>
</html>
I got the WHERE username="$login_session"
and the login_session value is a unique value for each of the users in the database so it can never be the same, so i can use this to pull up information for that user only
You can use session variables to store the information in the case you are working with sessions, if not, you can use a regular variable to store the information or maybe use post or get variables

Deleting an item from a mysql cart with php

I'm creating a cart system and trying to find a way to have a simple button that once pressed deletes the corresponding row. However, I cannot seem to find a way to dynamically do this with while loop I currently have.
<?php
//connect to DB.
$con = mysqli_connect("localhost", "root", "", "books");
if(mysqli_connect_errno())
{
echo "Failed to connect to MySql: ". mysqli_connect_error();
}
$query = "SELECT * FROM cart WHERE customerID = '$_SESSION['id']'";
$result = mysqli_query($con, $query);
//creates a table for dumping the DB to, loops through the DB and posts the contents elegantly.
echo "<table>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>" . $row['bookAuthor'] . "</td><td>" . $row['bookTitle'] . "</td><td>" . $row['bookPrice'] . "</td></tr>";
$totalprice += $row['bookPrice'];
}
echo "</table>";
echo "The total present price is: $".$totalprice;
//closes the conncection to the DB
mysqli_close($con);
?>
I've considered trying to put an echo query statement into the database and adding "$row['deletebutton']" to the while loop but I'm not sure that would necessarily work.
The easy way is to create a new page and send the message to this page to delete the item.
So, in the table you add a new column with a link
delete
And in the page you treat this value.
To expand on the comment posted to the question, you could add this to your row:
echo "<tr><td>" . $row['bookAuthor'] . "</td><td>" . $row['bookTitle'] . "</td><td>" . $row['bookPrice'] . "</td><td><input type='checkbox' name='remove[]' value='" . $row['ROW_ID'] . "' /></td></tr>";
And then with the data submitted in the form you could do something like this:
$query = "DELETE FROM cart WHERE ROW_ID IN (" . implode(',',$_POST['remove']) . ")";
Keep in mind to check the value of remove before using it in queries.

Deleting a row from the database via PHP

Okay, so what I've got here is a PHP generated table in which the values are pulled from a database. Now, if the administrator is logged in, I'd like to add an option to delete a row from the database.
I've got the structure all set up, but I have no idea what to put in the path of the link that is supposed to delete the row. How can I do this?
<?php
$rb = 1;
include 'konekcija.php';
$query = "SELECT * FROM oglasi";
$rezultat = mysql_query($query);
while($niz = mysql_fetch_array($rezultat)){
echo "<tr><td>" . $rb . "</td><td>" . $niz['model'] . "</td><td>" . $niz['cena'] . "</td><td><img src='" . $niz['slika_path'] . "'</img></td>";
if($_SESSION['uloga'] == "admin"){
echo "<td><a href='#'>Obrisi</a></td>";
}
echo "</tr>";
$rb++;
}
?>
You could try something like
echo "<td><a href='delete.php?row=" .$niz['id']. "'>Obrisi</a></td>";
Where delete.php is a php page that checks if the user is an administrator, parses the id value via GET (always remember to do proper escaping to avoid injections, or use other query systems, like prepared statements or stored procedures), and deletes the row with the specified id. Of course every record must have a unique id. Eventually the page redirects to the table view page.
Important sidenote: mysql_* functions are deprecated, use mysqli_* ones instead!
Well first of the link that you should use to delete the row is going to be whatever link you create.
Therefore you will have to create a new php page, or modify an existing one. To handle the requests to delete the rows.
Here is a quick example:
handler.php
<?php
//execute database connection here
switch($_GET['action'])
{
case 'delete':
mysql_query('DELETE FROM `TABLE_NAME` WHERE '.$_GET['where']);
break;
case 'add':
//parse info and submit request to db
break;
case 'edit':
//parse info and submit request to db
break;
}
//close db connection
?>
Disclaimer! This example is by no means secure, do not use it in production.
Then the absolute link you would use would be something like: (unescaped version)
http://host.com/pathtofile/handler.php?action=delete&where=(row_name='rowid')
guo
$rb = 1;
include 'konekcija.php';
$query = "SELECT * FROM oglasi";
$rezultat = mysql_query($query);
while($niz = mysql_fetch_array($rezultat)){
echo "<tr><td>" . $rb . "</td><td>" . $niz['model'] . "</td><td>" . $niz['cena'] . "</td><td><img src='" . $niz['slika_path'] . "'</img></td>";
if($_SESSION['uloga'] == "admin"){
echo "<td><a href='#'>Obrisi</a></td>";
}
echo "</tr>";
$rb++;
}
?>

php - using a hyper link to send variable used in data base to use get command to echoe results

I have a table with arrays pulling information from a database, I have linked the fix to be a hyperlink "click me for fix" I have entered the link to send the variable to a php that will use $GET to echoe the information.
code below , i am new to php and been racking brains . the only out put i get is Welcome . (done welcome to test if information was being passed)
<div id=list>
<?php
// Create connection
$con=mysqli_connect('172.16.254.111',"user","password","Faults"); //(connection location , username to sql, password to sql, name of db)
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//where statement in the sql syntax will select where in db to get infor, use AND to add another condition
$result = mysqli_query($con,"SELECT * FROM Fixes WHERE Product='Serv1U' AND Fault_type='Broadcast Manager'"); //this creates a variable that selects the database
//below is the echo statment to create the results in a table format, list collumn titles
echo "<table id=tables border='1'>
<tr>
<th>Products</th>
<th>Fault_type</th>
<th>Fault_Description</th>
<th>Fix</th>
</tr>";
//below is script to list reults in a table format, $row [row name on table]
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Product'] . "</td>";
echo "<td>" . $row['Fault_type'] . "</td>";
echo "<td>" . $row['Fault_Description'] . "</td>";
echo "<td>Click for Fix</td>"; //this is how you link into an echo, alsothe id=" hopefully means i can send ID information.
}
echo "</tr>";
echo "</table>";
// below closes the coonection to mysql
mysqli_close($con);
index.php:
Welcome <?php echo $_GET["Fix"]; ?>.
I'm lost. Any help is appreciated.
Thanks
?>
Is it just a typo here? $GET must be $_GET.
And it should be $row['Fix'] not $rows['Fix']! Note the 's'!

Edit and delete button on each row for table data?

I'm doing a movie library as a school assignment and have list of movies from a database table that I want to have a edit and a delete option next to on each row.
I want to use a edit/delete links for it. Like:
"<a href='moviestorage.php?edit=" . $id . "'>Edit</a>"
But I'm not sure how I can fish up the id for each movie so that it's deleted from the database. What's the query that I should write? Do I need to have a separate delete.php file?
I´m a very newbie so bear with me:)
Below you can see the code that I've done.
<?php
require 'connect.inc.php';
//This feels incomplete... I´m trying here to fish the ID...
$id = "SELECT id from movies";
$query = "DELETE FROM movies WHERE id='$id'";
$query = "SELECT * FROM movies, categories WHERE movies.genre_id = categories.genre_id";
$result = mysql_query($query);
if (!$result) die ("Database access failed:" .mysql_error()) ;
$rows = mysql_num_rows($result);
echo '<table><tr><th>Title</th><th>Release year</th><th>Genre</th><th>Director</th><th>Update</th><th>Delete</th></tr>';
for ($j = 0 ; $j < $rows ; ++$j) {
echo '<tr><td>' . mysql_result($result,$j,'title') . '</td>' ;
echo '<td>' . mysql_result($result,$j,'release_year') . '</td>' ;
echo '<td>' . mysql_result($result,$j,'genre') . '</td>' ;
echo '<td>' . mysql_result($result,$j,'director') . '</td>' ;
echo '<td>'."<a href='edit_movie.php?edit=" . $id . "'>Edit</a>".'</td>' ;
echo '<td>'."<a href='delete.php?delete=" . $id . "'>Delete</a>".'</td></tr>' ;
}
echo '</table>';
include 'add_movie.php';
?>
I would recommend that you use a form for every row with a delete and edit button and a hidden field with the ID. You can then post that form to the right script and determine the action to take there.
If you have to use a link to delete an item, at least have the link lead to another confirmation page with a form that the user has to submit and that posts to your delete script.
if you have to edit and delete on new page than you can put hyperlink this way
echo "<a href=\"edit.php?id=".mysql_result($result,$j,'id')."\"><strong>EDIT</strong>";
echo "<a href=\"delete.php?id=".mysql_result($result,$j,'id')."\"><strong>delete</strong>";
and for conformation for delete you can use this on delete link
echo "<a href=\"delete.php?id=".mysql_result($result,$j,'id')."\" onclick=\"return confirm('You want to delete your own account???');\"><strong>delete</strong>";
than get the id on next page using
$id = $_GET['id'];
hope it will be usefull for you
If you need a simple and effective solution, use datatables. :)
please search in google. spent some time to study how to implement it, it will save a lot of time in future.

Categories