Delete hyperlink and function not working on web page - php

I tried to add a delete "button"(link to file with function) it should delete a row from the database, but it didn't work. I looked for tutorials and answers on forums but found nothing how solve for my problem.
<td>Delete</td>
link from code:
The link works correctly, but when I tried to delete it just doesn't want to take 'commentId' variable and go back to test.php page
Table on website:
dbh.inc.php
<?php
$serverName = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "php-login";
$conn = mysqli_connect($serverName, $dBUsername, $dBPassword, $dBName);
if (!$conn){
die("connection failed: " . mysqli_connect_error());
}
test.php
<?php
include_once 'header.php';
include "includes/dbh.inc.php";
include 'includes/test.inc.php';
?>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="box">
<h4 class="display-4 text-center">Comments</h4><br>
<?php if (isset($_GET['success'])) { ?>
<div class="alert alert-success" role="alert">
<?php echo $_GET['success']; ?>
</div>
<?php } ?>
<table class="table table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Username</th>
<th scope="col">Comment</th>
<th scope="col">Action</th>
</tr>
</thead>
<?php
$i=0;
while($row = mysqli_fetch_array($result)) {
?>
<td><?php echo $row["commentId"]; ?></td>
<td><?php echo $row["usersUid"]; ?></td>
<td><?php echo $row["comment"]; ?></td>
<td>Delete</td>
</tr>
<?php
$i++;
}
?>
</table>
</div>
</div>
</body>
</html>
test.inc.php
<?php
include "dbh.inc.php";
$sql = "SELECT * FROM commenttb ORDER BY commentId DESC";
$result = mysqli_query($conn, $sql);
delete.inc.php
<?php
include "dbh.inc.php";
if(isset($_GET['commentId'])) {
$id = $_GET['commentId'];
$delete = "DELETE FROM `commenttb` WHERE `commentId` ='$id'";
$result = mysqli_query($conn, $delete);
if ($result) {
header("Location: ../test.php?success=successfully deleted");
} else {
header("Location: ../test.php?error=unknown error occurred");
}
}else {
header("Location: ../test.php?error=smth gone wrong");
}
If I press on the link "delete" it should take 'commentId' variable from row e.g. 5 and by SQL query from delete.inc.php file delete row with this id from my database
I tried change $_Get to $_POST and add method="POST" to link on delete.inc.php file, but it didn't work

Related

Why is the record I wanted to delete still there even though I had the function up and running?

I am working on an assignment in PHP and MySQL, where I am needed to create a function to delete records from a table via ID with a push of a button with JavaScript. Even though I followed by teacher's videos, it still is not able to delete the record away.
My teacher and I suspected that it has got to do with the bind_param part, but still it is not solved.
Here are the files:
db-connect.php
<?php
$servername = "localhost";
$username = "root";
$password = ""; // this should be empty
$dbName = "newDB"; // add your database name here
$conn = new mysqli($servername, $username, $password, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
/**
* $conn->connect_error - contains an error message from the database server (if any)
*/
}
?>
index.php
<?php
require "db-connect.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP Code-Along 2</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>List of Records</h1>
<div>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Email</th>
<th>Actions</th>
</tr>
<?php
$sql = "SELECT * FROM `Employee`;";
$sql_run = $conn->query($sql);
if($sql_run) { // if it is not false, then proceed
if($sql_run->num_rows > 0) { // num_rows will check if there are row(s) of results
while($row = $sql_run->fetch_assoc()) {
?>
<tr>
<td><?= $row['id']; ?></td>
<td><?= $row['name']; ?></td>
<td><?= $row['age']; ?></td>
<td><?= $row['email']; ?></td>
<td>
<button onclick="document.location.href = 'form.php?id=<?= $row['id']; ?>'">Edit</button>
<button onclick="deleteConfirm(<?= $row['id']; ?>);">Delete</button>
</td>
</tr>
<?php
}
} else {
// echo "No table rows found.";
?>
<tr>
<td colspan="5">No records found.</td>
</tr>
<?php
}
} else {
?>
<tr>
<td colspan="5">Error retrieving table rows: <?= $conn->error; ?></td>
</tr>
<?php
}
?>
</table>
</div>
<script src="main.js"></script>
</body>
</html>
main.js
function deleteConfirm(id) {
const response = confirm(`Are you sure you want to delete record #${id}?`);
if(response) {
document.location.href = "db-deleterecord.php?=id" + id;
}
}
db-deleterecord.php
<?php
if(isset($_GET['id'])) { // check if "?id=..." exists, i.e. if a GET value id is obtained.
require "db-connect.php";
$sql = "DELETE FROM `Employee` WHERE `id` = ?;";
$stmt = $conn->prepare($sql);
if($stmt) {
$stmt->bind_param("i", $_GET['id']);
if($stmt->execute()) {
echo "Deleted record with ID: " .$_GET['id'];
} else echo "Unable to delete record #" . $_GET['id'] . ": " .$stmt->error;
} else echo "Unable to prepare statement: " . $conn->error;
}
header("refresh:5; url=index.php");
?>
There's an error in your string concatenation for the url -
document.location.href = "db-deleterecord.php?=id" + id;
should be -
document.location.href = "db-deleterecord.php?id=" + id;

How to display each submitted form data in another page

I want to display form data on another page so that when I click "More View" button and the inputed data of each user will display on another page.
This is the code of the HTML form:
registerbooks.php
<!DOCTYPE Html>
<<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Register books</title>
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
</head>
<body>
<div id='main-content'>
<form action="connect.php" method="POST">
<input type="text" name="tittle" placeholder="Book Tittle"></br>
<input type="text" name="author" placeholder="Author"></br>
<input type="text" name="copies" placeholder="Copies Available"></br>
<button type="submit" name="submit">submit</button>
<button type="reset" value="Reset">Reset</button>
</form>
</div>
</body>
</html>
This is the connection.php
<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'list';
// Create connection
$connect = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$connect) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_POST['submit'])){
$Tittle = $_POST['tittle'];
$Author = $_POST['author'];
$Copies = $_POST['copies'];
$query = "INSERT INTO books(Tittle,Author,Copies) VALUES('$Tittle' , '$Author' , '$Copies')";
$result=mysqli_query($connect, $query);
if($result){
echo 'Available Books updated';
}
else{
echo "Failed to update";
}
}
?>
The fom is displayed in this page:
Availablebooks.php
<!DOCTYPE HTML>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Available books</title>
</head>
<body>
<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'list';
$connect = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$connect) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM books";
$result=mysqli_query($connect, $sql);
?>
<table align="centre" border="1px" width="600px" line-height="30px" >
<tr>
<th colspan="4">Available books</th>
</tr>
<tr>
<th>ID</th>
<th>Book tittle</th>
<th>Author</th>
<th>More Details</th>
</tr>;
<?php
while ($rows = $result->fetch_assoc())
{
?>
<tr>
<td><?php echo $rows['ID']; ?> </td>
<td> <?php echo $rows['Tittle']; ?> </td>
<td> <?php echo $rows['Author']; ?> </td>
<td> <button type="submit">More Views</button> </td>
</tr>
<?php
}
?>
</table>
</body>
</html>
When I click "more views" button, I want each user data to be displayed in "orders.php"
<!DOCTYPE HTML>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Available books</title>
</head>
<body>
<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'list';
$connect = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$connect) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM books WHERE id=(Tittle,Author,Copies )";
$result=mysqli_query($connect, $sql);
?>
<table align="left" border="1px" width="600px" line-height="30px" >
<tr>
<th colspan="4">Ordered books</th>
</tr>
<tr>
<th>ID</th>
<th>Book tittle</th>
<th>Author</th>
<th>Number of copies</th>
</tr>
<?php
while ($rows = $result->fetch_assoc())
{
?>
<tr>
<td><?php echo $rows['ID']; ?> </td>
<td><?php echo $rows['id']; ?> </td>
<td> <?php echo $rows['id']; ?> </td>
<td> <?php echo $rows['id']; ?> </td>
</tr>
<?php
}
?>
</table>
</body>
</html>
But the code is not working. Please help me to resolve this issue.
Thanks

applying search or filter to table with pagination

hello kind sirs can you help me with this code. What i try to do is when i type something in the search box, ex. pending it will show the 5 pending reservation per page(5 rows of pending reservation). but when i try it, it shows all the pending reservation which is more than 10.
here is the image
i try something like this.. but it shows nothing
$query = "SELECT * FROM reservations WHERE CONCAT(firstname, lastname, reservationstatus)LIKE '%".$valueToSearch."%' LIMIT " . $this_page_first_result . ',' . $results_per_page";
Here is the whole code
<?php
error_reporting(E_ALL & ~E_NOTICE);
error_reporting(E_ERROR | E_PARSE);
session_start();
?>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "srdatabase";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$results_per_page = 5;
$select= "SELECT * FROM reservations";
$result = mysqli_query($conn, $select);
$number_of_results = mysqli_num_rows($result);
if(!isset($_GET['page']))
{
$page = 1;
}
else
{
$page = $_GET['page'];
}
$this_page_first_result = ($page-1)*$results_per_page;
$sql = "SELECT * FROM reservations LIMIT " . $this_page_first_result . ',' . $results_per_page;
$result = mysqli_query($conn, $sql);
$number_of_pages = ceil($number_of_results/$results_per_page);
?>
<div id="paging-div">
<?php
for($page=1;$page<=$number_of_pages;$page++)
{
echo '<a id="pagingLink" href="adminControl.php?page=' . $page . '">' . $page . '</a>';
}
?>
<?php
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
$query = "SELECT * FROM reservations WHERE CONCAT(firstname, lastname, reservationstatus)LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else
{
$query = "SELECT * FROM reservations";
$search_result = filterTable($query);
}
function filterTable($query)
{
$conn = mysqli_connect("localhost", "root", "", "srdatabase");
$filter_Result = mysqli_query($conn, $query);
return $filter_Result;
}
?>
</div>
<!DOCTYPE html>
<html>
<head>
<title>Admin Control</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="topnav" id="myTopnav">
Home
Speakers
About
Contact
Reservation
Sign Out
<?php echo $_SESSION['firstname']; ?>
Sign Up
Sign In
Admin control
☰
</div>
<br>
<br>
<br>
<br>
<h4 style="padding-left:10px; text-align:center;">Reservation List</h4>
<hr>
<form action="adminControl.php" method="POST">
<input type="text" name="valueToSearch" placeholder="type a value">
<input type="submit" name="search" value="Filter">
</form>
<br>
<br>
<div style="overflow-x:auto;">
<table class="reservations-table">
<tr>
<th class="thFirstName">First Name</th>
<th class="thLastName">Last Name</th>
<th class="thEmailAddress">Email Address</th>
<th class="thContactNumber">Contact Number</th>
<th class="thSpeaker">Speaker</th>
<th class="thTopic">Topic</th>
<th class="thLocation">Location</th>
<th class="thAudience">Audience</th>
<th class="thCount">Count</th>
<th class="thTime">Time</th>
<th class="thDate">Date</th>
<th class="thAction">Reservation Date</th>
<th class="thAction">Status</th>
<th class="thAction">Action</th>
<th class="thAction">Action</th>
</tr>
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['firstname'];?></td>
<td><?php echo $row['lastname'];?></td>
<td><?php echo $row['emailaddress'];?></td>
<td><?php echo $row['contactnumber'];?></td>
<td><?php echo $row['speaker'];?></td>
<td><?php echo $row['topic'];?></td>
<td><?php echo $row['location'];?></td>
<td><?php echo $row['audience'];?></td>
<td><?php echo $row['count'];?></td>
<td><?php echo $row['time'];?></td>
<td><?php echo $row['date'];?></td>
<td><?php echo $row['reservationdate'];?></td>
<td><?php echo $row['reservationstatus'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</div>
<?php
$epr='';
$msg='';
if(isset($_GET['epr']))
$epr=$_GET['epr'];
if($epr=='delete')
{
$id=$_GET['id'];
$delete=mysqli_query($conn, "DELETE FROM reservations WHERE id=$id");
if($delete)
header('location:adminControl.php');
else
$msg='Error :'.mysqli_error();
}
?>
<?php
$epr='';
$msg='';
if(isset($_GET['epr']))
$epr=$_GET['epr'];
if($epr=='approve')
{
$id=$_GET['id'];
$approve=mysqli_query($conn, "UPDATE reservations SET reservationstatus='approved' WHERE id=$id");
header('location:adminControl.php');
}
?>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
<script>
function ifAdmin()
{
document.getElementById("signIn").style.display = "none";
document.getElementById("signUp").style.display = "none";
document.getElementById("signOut").style.display = "block";
document.getElementById("adminControl").style.display = "block";
}
</script>
<script>
function ifNotAdmin()
{
document.getElementById("signIn").style.display = "none";
document.getElementById("signUp").style.display = "none";
document.getElementById("signOut").style.display = "block";
document.getElementById("adminControl").style.display = "none";
}
</script>
<script>
function ifNotLogin()
{
document.getElementById("user").style.display = "none";
document.getElementById("signOut").style.display = "none";
document.getElementById("adminControl").style.display = "none";
}
</script>
<?php
if (isset($_SESSION['signedIn']) && $_SESSION['signedIn'] == true)
//if login
{
if($_SESSION['type'] == 1)
{
echo "<script type='text/javascript'>ifAdmin();</script>";
}
elseif($_SESSION['type'] == 0)
{
echo "<script type='text/javascript'>ifNotAdmin();</script>";
}
}
//if not login
else
{
echo "<script type='text/javascript'>ifNotLogin();</script>";
}
?>
<div id="footer" class="push">Copyright 2017</div>
</body>
</html>
... when i try it, it shows all the pending reservation which is more than 10.
That's because when you hit 2nd, 3rd, ... pages(after navigating from the 1st page), the $_POST array would be empty i.e. $_POST['search'] won't be set, and that's why else{...} part of the code will get executed every time you navigate to 2nd, 3rd, ... pages. Since you're not sending any sensitive data with the form, use GET instead of POST in the method attribute of the form, like this:
<form action="..." method="get">
and get the user inputted data like this:
if (isset($_GET['search'])) {
$valueToSearch = $_GET['valueToSearch'];
...
Subsequently, you need to attach that search query in each of your pagination links, so that the search query would be available when you hop from page to page.
// your code
<?php
for($page=1;$page<=$number_of_pages;$page++)
{
echo "<a id='pagingLink' href='adminControl.php?page=" . $page . "&valueToSearch=". urlencode($_GET['valueToSearch']) ."&search'>" . $page . "</a>";
}
?>
// your code

MySQL doesn't seem to work

So I made my first database online. I used phpmyadmin, I created the table and the user.
Now I'd like to show the table on a page of my site, as well as giving the possibility to people to edit the database from the site.
My problem is that the database does not work: it doesn't connect. I have no idea what to do.
My database is called letstenf_santi and my table passeggeri.
This is the code I'm trying to use to show the table on the site.
<?php
//establishing connection
mysql_connect('localhost', 'root', '');
//selecting a database
mysql_select_db('letstenf_santi');
$sql = 'SELECT * FROM `letstenf_santi`.`passeggeri`';
$records=mysql_query($sql);
?>
<html>
<head>
<title>mostra</title>
</head>
<body>
<table width="300" border="1" cellpadding="10" cellspacing="1">
<tr>
<th>id pass</th>
<th>nome</th>
<th>eta</th>
<th>sesso</th>
</tr>
<?php
while($pass=mysql_fetch_assoc($records)){
echo "<tr>";
echo "<td>".$pass['idpasseggero']."</td>";
echo "<td>".$pass['nome']."</td>";
echo "<td>".$pass['eta']."</td>";
echo "<td>".$pass['sesso']."</td>";
echo "</tr>";
}
?>
</table>
</body>
</html>
instead of this,
mysql_connect('localhost', 'root', '');
mysql_select_db('letstenf_santi');
you can try this,
$connection=mysql_connect('localhost', 'root', '');
$db=mysql_select_db('letstenf_santi',$connection);
try this code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "letstenf_santi";//your db name
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM tablename";//replace table name with your table name
$result = mysqli_query($conn, $sql); ?>
<html>
<head>
<title>mostra</title>
</head>
<body>
<table width="300" border="1" cellpadding="10" cellspacing="1">
<tr>
<th>id pass</th>
<th>nome</th>
<th>eta</th>
<th>sesso</th>
</tr>
<?php if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row['idpasseggero']."</td>";
echo "<td>".$row['nome']."</td>";
echo "<td>".$row['eta']."</td>";
echo "<td>".$row['sesso']."</td>";
echo "</tr>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
</table>
</body>
</html>

PHP Store a Hyperlink String into a Variable on Click

I am making a page where it displays a table with staffID and staffName using PHP. When the user clicks the staffID it should then display a new table using the code from another file with extra details about that staffID such as shippingDate, OrderID, etc.
task9.php file below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Task 9</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<?php
$sID= isset($_GET['staffID']) ? $_GET['staffID'] : '';
$conn = mysqli_connect('localhost', 'TWA', 'TWA_test', 'factory');
if ( !$conn ) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT s.staffID,s.staffName
FROM staff s";
$results = mysqli_query($conn, $sql)
or die ('Problem with query' . mysqli_error($conn));
?>
<h1> Staff Table </h1>
<table>
<tr>
<th>Staff ID</th>
<th>Staff Name</th>
</tr>
<?php while($row = mysqli_fetch_array($results)) { ?>
<tr>
<td> <?php echo $row[0] ?></td>
<td><?php echo $row[1] ?></td>
</tr>
<?php } ?>
<?php mysqli_close($conn); ?>
</table>
</body>
</html>
task8.php asks a user to enter a staffID and it displays all of the details, if the staffID does not exist then it displays an error. This file works fine and displays everything correctly. task8.php file below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Task 8</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<?php
$conn = mysqli_connect('localhost', 'TWA', 'TWA_test', 'factory');
if ( !$conn ) {
die("Connection failed: " . mysqli_connect_error());
}
//obtain the staff ID input from the $_GET array
$sID= isset($_GET['staffID']) ? $_GET['staffID'] : '';
$sql = "SELECT s.staffID, p.orderID, p.orderDate, p.shippingDate,s.staffName
FROM purchase p
INNER JOIN staff s
ON p.staffID = s.staffID
WHERE p.staffID = '$sID'";
$results = mysqli_query($conn, $sql)
or die ('Problem with query' . mysqli_error($conn));
?>
<h1> Order Details </h1>
<?php $rows = mysqli_num_rows($results); ?>
<?php if($rows <= 0){ ?>
<p><?php echo "The staff ID entered is invalid"; ?></p>
<?php } else { ?>
<table>
<tr>
<th>Staff ID</th>
<th>Order ID</th>
<th>Order Date</th>
<th>Shipping Date</th>
<th>Staff Name</th>
</tr>
<?php while ($row = mysqli_fetch_array($results)) { ?>
<tr>
<?php if($row[0] != ""): ?>
<td><?php echo $row[0]; ?></td>
<?php else: ?>
<td><?php echo "N/A"; ?></td>
<?php endif; ?>
<?php if($row[1] != ""): ?>
<td><?php echo $row[1]; ?></td>
<?php else: ?>
<td><?php echo "N/A"; ?></td>
<?php endif; ?>
<?php if($row[2] != ""): ?>
<td><?php echo $row[2]; ?></td>
<?php else: ?>
<td><?php echo "N/A"; ?></td>
<?php endif; ?>
<?php if($row[3] != ""): ?>
<td><?php echo $row[3]; ?></td>
<?php else: ?>
<td><?php echo "N/A"; ?></td>
<?php endif; ?>
<?php if($row[4] != ""): ?>
<td><?php echo $row[4]; ?></td>
<?php else: ?>
<td><?php echo "N/A"; ?></td>
<?php endif; ?>
</tr>
<?php } ?>
<?php } ?>
<?php mysqli_close($conn); ?>
</table>
</body>
</html>
The problem I am facing is that when I click the staffID from the table on task9.php it just shows the error I included in task8.php "The staff ID entered is invalid". I don't know why it isn't displaying the details from task8.php
you did not build your link correctly, it should be
<?php echo $row[0] ?>
also, i feel somehow uncomfortable echoing outputs without htmlentities().
Yes, it is boring to type that everytime so i usually keep a function in every of my PHP projects like this
function e($whatToConvert){
return htmlentities($whatToConvert); //or htmlspecialchars
}
so the above code for instance becomes
<?php echo e($row[0]) ?>
You need to pass the parameter like this
<a href = "task8.php?staffID=<?php echo $row[0]?>">

Categories