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++;
}
?>
Related
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 ...
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
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.
I am having an issue sorting my datatable by the column header.
I have a build-query mechanism on my site that can take in 1 or more values the user selects. The values get turned into PHP variables that then get passed into the query and prints out the datatable to the screen. The address bar URL is updated as well.
I want to be able to sort by the column headers of the table.
I will show you the PHP code bypassing the whole build-query function. I'll start right at the SORT portion and the query:
<?php
if ($_GET['sort'] == "") {
$sort_by = "BOL_NUMBER";
} else {
$sort_by = $_GET['sort'];
}
$select = "";
if ($_SESSION['where'] != "") {
$select = "SELECT * FROM `mainTable` WHERE (". $_SESSION['where'] . ") ORDER BY " . $sort_by . "";
}
// $_SESSION['where'] comes from the build query and can contain 1 or more values
$QueryResult = mysql_query($select) or die ();
$resnum = mysql_num_rows($QueryResult);
This next part is where the table gets populated:
if ($resnum == 0) {
echo "no results";
} else {
echo "<table>\n";
echo "<thead><tr>" .
"<th>BOL</th>" .
"<th>CONTAINER</th>" .
"<th>LOCATION</th>" .
"<th>STATUS</th>" .
"</tr></thead><tbody>\n";
while(($Row = mysql_fetch_assoc($QueryResult)) !== FALSE) {
echo "<tr>";
echo "<td>{$Row[BOL_NUMBER]}</td>";
echo "<td>{$Row[CONTAINER_NUMBER]}</td>";
echo "<td>{$Row[LOCATION_CITY]}</td>";
echo "<td>{$Row[STATUS_TYPE]}</td>";
echo "</tr>";
}
echo "</tbody></table>\n";
?>
There are many more columns. I just picked a couple.
I found this page for this next part:
Sorting html table with a href and php from sql database
So I tried to apply what I read in the link to the headers, like this:
"<th><a href='myPage.php?sort=BOL_NUMBER'>BOL</a></th>" .
"<th><a href='myPage.php?sort=CONTAINER_NUMBER'>CONTAINER</a></th>" .
"<th><a href='myPage.php?sort=LOCATION_CITY'>LOCATION</a></th>" .
"<th><a href='myPage.php?sort=STATUS_TYPE'>STATUS</a></th>" .
Now, I can click on the column headers, but when I do, it does not keep the user's selection and I can tell because the URL changes like this example below:
(this is just an example. it does not include the parameters in the table above)
(just keep note of the &sort in this url)
http://home.someCompany.com/myAPP/mypage.php?direction=I&type=&submit=Go&city=&pod=&terminal=&ramp=&container=&bol=&voyage=&conStatus=&con_location=&sort=&status=
Will change to this (if I select the header for CONTAINER):
http://home.someCompany.com/myAPP/mypage.php?&sort=CONTAINER_NUMBER
When this happens, the datatable is no longer on the screen. It's like it removes everything from the query and just adds the sort. But there is now nothing to sort.
The $_SERVER['QUERY_STRING'] superglobal variable give you access to the GET parameters. By using it you can keep the current parameters of the request.
So by changing your link by this :
$urlQuery = str_replace(array('&sort=BOL_NUMBER', '&sort=CONTAINER_NUMBER', '&sort=LOCATION_CITY', '&sort=STATUS_TYPE'), '', $_SERVER['QUERY_STRING']); // To clean previous sorting, maybe replace by a regex
"<th><a href='myPage.php?' . $urlQuery . '&sort=BOL_NUMBER'>BOL</a></th>" .
"<th><a href='myPage.php?' . $urlQuery . '&sort=CONTAINER_NUMBER'>CONTAINER</a></th>" .
"<th><a href='myPage.php?' . $urlQuery . '&sort=LOCATION_CITY'>LOCATION</a></th>" .
"<th><a href='myPage.php?' . $urlQuery . '&sort=STATUS_TYPE'>STATUS</a></th>" .
You should reach your goal.
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.