Read out data and edit - php

i would like to read out all data records from a table and give individual data records a new value in "status" according to their "id".
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<title>Table</title>
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<?php
$conn = new mysqli ("localhost", "root", "Z&r*%/Nm#X4x", "cms");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, position, status FROM data";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();
$data = $result->fetch_all(MYSQLI_ASSOC);
if ($data) {
foreach($data as $row) {
?>
<form method="post">
<div class="table-responsive d-table">
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>POSITION</th>
<th>STATUS</th>
<th><button type="submit" name="change">CHANGE STATUS</button></th>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row["position"]; ?></td>
<td><?php echo $row["status"]; ?></td>
<td>
<?php
if (isset($_POST['change'])) {
$update = $update = "UPDATE data Set status = '2' WHERE id = {$row['id']}";
mysqli_query($conn, $update);
echo "Successful";
} elseif (!isset($_POST['change'])) {
echo "Not clicked";
} else {
echo "Failed";
}
?>
</td>
</tr>
</tbody>
</table>
</div>
</form>
</body>
<?php
}
} else {
echo "No data found!";
$conn->close();
}
?>
</html>
My problem is, when I click the button, all records are changed and not just one. I hope someone can help to solve the problem.
.........................................................................................................................................................................................................

Try using {} to embed array elements into a string and enclose 'id' value
$update = "UPDATE data Set status = '0' WHERE id = {$row['id']}"
Otherwise, your query will interpret $row and [id] as separated items:
UPDATE data Set status = '0' WHERE id = [id]
and as a result, all your rows updated
Also consider to apply the status update button to each single row, there is no way to update only one row with a general "update status" button without sending a parameter of which row id will update. For example:
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<title>Table</title>
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<?php
$conn = new mysqli ("localhost", "root", "Z&r*%/Nm#X4x", "cms");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, position, status FROM data";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();
$data = $result->fetch_all(MYSQLI_ASSOC);
if ($data) {
foreach($data as $row) {
?>
<form method="post">
<div class="table-responsive d-table">
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>POSITION</th>
<th>STATUS</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row["position"]; ?></td>
<td><?php echo $row["status"]; ?></td>
<td>
<button type="submit" name="change" value="<?php echo $row['id']; ?>">CHANGE STATUS</button>
<?php
if (isset($_POST['change']) && $_POST["change"]==$row['id']) {
$update = $update = "UPDATE data Set status = '2' WHERE id = {$row['id']}";
mysqli_query($conn, $update);
echo "Successful";
} elseif (!isset($_POST['change'])) {
echo "Not clicked";
} else {
echo "Failed";
}
?>
</td>
</tr>
</tbody>
</table>
</div>
</form>
</body>
<?php
}
} else {
echo "No data found!";
$conn->close();
}
?>
</html>

Related

update.php file in not working properly. and error is not showing

i create a curd apllication with the help of php and mysql there is work all operation insert, read and delete but in update option it not work. when i click on update button it is jump directly on display.php page.
this is my display.php code
<?php
include 'conc.php';
// $username = $_POST["username"];
// $password = $_POST["password"];
$q = "select * from cued_data";
$query = mysqli_query($con , $q);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>display data</title>
<link rel="stylesheet" href="curd.css">
</head>
<body>
<div class="container">
<h1>display Table Data</h1>
<table class="table">
<tr>
<th>Id</th>
<th>Username</th>
<th>Password</th>
<th>Delete</th>
<th>Update</th>
</tr>
<?php
include 'conc.php';
$q = "select * from cued_data";
$query = mysqli_query($con , $q);
while($res = mysqli_fetch_array($query)){
?>
<tr>
<td> <?php echo $res['id']; ?> </td>
<td> <?php echo $res['name']; ?> </td>
<td> <?php echo $res['password']; ?> </td>
<td><button class="dlt"> <a href="delete.php?id= <?php echo $res['id']; ?>" > Delete: </a> </button> </td>
<td><button class="dlt"> <a href="update.html?id= <?php echo $res['id']; ?>" > Update: </a> </button> </td>
</tr>
<?php
}
?>
</table>
</div>
</body>
</html>
this is my update.php file
<?php
include "conc.php";
include "display.php";
$id = $_GET["id"]; # i think error in this section
$username = $_POST["name"];
$password = $_POST["password"];
// $q = "delete from `cued_data` where id = $id" ;
$msql= " update cued_data set id ='$id', name = '$username', password = '$password' where id = '$id' ";
$query = mysqli_query($con, $msql);
header("location:display.php");
?>
this is my delete.php file
<?php
include "conc.php";
$id = $_GET["id"];
$q = "delete from `cued_data` where id = $id" ;
$query = mysqli_query($con, $q);
header("location:display.php");
?>

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

i want to make delete button [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
So i start the language in this summer,and i have problem,i don't know how to make delete button,i looked lot of pages but i can't find how to make with pdo.
countryandcity.php
<?php
require 'pdo.php';
$connect=connect();
?><!DOCTYPE html>
<html>
<head>
<link href="style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div class="wrapper">
<table class="table" >
<thead>
<tr>
<th>Country</th>
<th>City</th>
<th>Image</th>
</tr>
<form action="deleteall.php" method="POST" >
<?php
$sql = connect()->prepare("SELECT * FROM countries ORDER BY country");
$sql->execute();
while($result = $sql->fetch(PDO::FETCH_ASSOC)) {
echo"<tr>";
echo"<td>".$result['country']."</td>";
echo"<td>".$result['city']."</td>";
if(!empty($result['image'])){
echo '<td><img src="images/'.$result['image'].'"/></td>';
}
else {
echo"<td>-</td>";
}
echo "<td><a href='edit.php?uid=".$result['country']."'>Edit</a></td>";
echo "<td><a href='deleteall.php?uid=".$result['country']."'>Delete</a></td>";
echo"</tr>";
}
?>
</form>
</thead>
</table>
</div>
</body>
deleteall.php
<?php
require 'pdo.php';
$connect=connect();
if(isset($_POST['delete_btn']))
?><!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form>
<div class="form-group">
<label>Do u want to delete?</label>
</div>
<button>
<input type="submit" value="YES" name="delete_btn">
</button>
<button>
<input type="submit" name="no" value="NO">
</button>
</form>
</body>
</html>
Please help me with the sql query and php code after if(isset), i need help!
I just want to delete on row from the database.
How can I solve this?
Sorry for my bad english.
Thanks!
Here is correction of your firsts page (content in <tbody> instead of <thead>, no <form> needed, ...) countryandcity.php :
<table>
<thead>
<tr>
<th>column name...</th>
</tr>
</thead>
<tbody>
<?php
$sql = connect()->prepare("SELECT * FROM countries ORDER BY country");
$sql->execute();
if($result = $sql->fetch(PDO::FETCH_ASSOC)) {
foreach($result as $i => $item) {
extract($item);
echo "<tr><td>$country</td>";
echo "<td>$city</td>";
if(!empty($image)) {
echo "<td><img src=\"images/$image\"/></td>";
}
else {
echo "<td>-</td>";
}
echo "<td>Edit</td>";
echo "<td>Delete</td></tr>";
}
}
?>
</tbody>
</table>
</div>
</body>
</html>
And here solution for deleting your record in deleteall.php :
<?php
if(isset($_GET['delete_btn'])) {
$country = addslashes($_GET['delete_btn']);
$q = "DELETE FROM countries WHERE country = '$country'";
require 'pdo.php';
$sql = connect()->prepare($q);
$sql->execute();
}
?>
hope it will help you, you can add delete link then go this page it will delete
Edit
Delete
<?php
require 'pdo.php';
$connect = connect();
?>
<!DOCTYPE html>
<html>
<head>
<link href="style.css" type="text/css" rel="stylesheet"/>
</head>
<body>
<div class="wrapper">
<table class="table">
<thead>
<tr>
<th>Country</th>
<th>City</th>
<th>Image</th>
</tr>
<form action="deleteall.php" method="POST">
<?php
$sql = connect()->prepare("SELECT * FROM countries ORDER BY country");
$sql->execute();
while ($result = $sql->fetch(PDO::FETCH_ASSOC)) {
if (!empty($result['image'])) {
$content_image = '<td><img src="images/' . $result['image'] . '"/></td>';
} else {
$content_image = '<td>-</td>';
}
?>
<tr>
<td> <?= $result['country'] ?></td>
<td><?= $result['city'] ?></td>
<?= $content_image ?>
<td>Edit</td>
<td>Delete
</td>
</tr>
<?php }
?>
</form>
</thead>
</table>
</div>
</body>
</html>
then this is your deleteall.php
<?php
$uid = trim($_GET['uid']);
if(isset($uid)) {
$sql = "DELETE FROM countries WHERE country = ?";
$q = connect()->prepare($sql);
$response = $q->execute(array($uid));
}
?>
For the form, I'd recommend having a button that acts as the function, that way you don't accidentally lose all your data when the page loads, or anything like that. This is simply three lines of code.
<form action="deleteall.php" method="POST">
<input type="hidden" value="true" name="cameFromForm">
<button type="submit" name="confirmButton">Delete All</button>
</form>
When the button is clicked, then it will trigger the entry point of deleteall.php, which then takes the input and deletes ALL data from the table.
<?php
if(isset($_POST["cameFromForm"]) && $_POST["cameFromForm"] == "true") {
// This makes sure that the form actually sent it.
try {
$tableName = "Insert the name of your table here";
$mysqli = new mysqli(
'databaseHost',
'databaseUser',
'databasePassword',
'databaseName');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("DELETE FROM ?");
$stmt->bind_param('s', $tableName);
$stmt->execute();
$stmt->close();
$mysqli->close();
header('Location: http://afterDeltePage.com');
}
catch (Exception $e) {
print($e);
die();
}
}
else {
header('Location: http://notAuthorisedPage.com');
}
?>
Once you've finished the process, you should send the user to a page with UI. Try to separate the things you need to show the user and your processes. Also, if this is going to be public, you need to make sure that deleteall is not accessible by anyone by URL.
To do that, you need to move your file out of the wwwroot (public_html usually). There are various topics on how to do that.
PHP Forms information and PHP MySQLi information.

Get specific data from database with PHP code when a user login

I want to get data from my database with PHP code. In brief when a user log in with id & password i want to show his data only in user panel, but i got some error: Here is my user admin panel code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>User Panel</title>
<link rel="stylesheet" href="assets/demo.css">
<link rel="stylesheet" href="assets/form-labels-on-top.css">
</head>
<body>
<header>
<h1 align="center"><b>User Information Details</b></h1></br>
</header>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "xyz";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
include('user_login_check.php');
$result= mysql_query("SELECT * FROM `user_information` WHERE `user_id` = '".$_SESSION['id']."' ")or die(mysql_error());
// $result = mysql_query("SELECT * FROM user_information WHERE user_name='" . $_POST["user_name"] . "' and user_password = '". $_POST["user_password"]."'");
?>
<form>
<table border="5" style= "background-color: #333333; color: #FFF; margin: 0 auto; padding:100px" >
<thead>
<tr>
<th>User ID</th>
<th>User Type</th>
<th>User Name</th>
<th>User Country</th>
<th>User Email</th>
<th>User Phone</th>
<td>User Address</td>
<td>User Password</td>
<td>User Status</td>
<td>Edit</td>
</tr>
</thead>
<tbody>
<?php
while( $row = mysqli_fetch_assoc( $result ) ){
echo
"<tr>
<td>{$row['user_id']}</td>
<td>{$row['user_type']}</td>
<td>{$row['user_name']}</td>
<td>{$row['user_country']}</td>
<td>{$row['user_email']}</td>
<td>{$row['user_phone']}</td>
<td>{$row['user_address']}</td>
<td>{$row['user_password']}</td>
<td>{$row['user_status']}</td>
<td><img src='image/editicon.jpeg'/></td>;
</tr>\n";
}
?>
</tbody>
<div align="left" style="background:#333333">
<h1><input type="button" value="Log Out" onClick="window.location.href='logout_user.php'" /> </h1>
</div>
</table>
</form>
</body>
</html>
problem is in specially this section
$result= mysql_query("SELECT * FROM `user_information` WHERE `user_id` = '".$_SESSION['id']."' ")or die(mysql_error());
here is my login check code:
<?php
//connect the database
$hostName="localhost";
$dbUsername="root";
$dbPassword="";
$dbName="xyz";
mysql_connect($hostName,$dbUsername,$dbPassword) or die("Connection failed");
mysql_select_db($dbName) or die("Database name doesn't exist");
//start session
#session_start();
if(isset($_POST["user_name"] , $_POST["user_password"]))
{
$User_name = $_POST["user_name"];
// echo "$User_name";
$User_password = $_POST["user_password"];
// echo "$User_password";
$sql = "SELECT * FROM `user_information` WHERE `user_name`='".$User_name."' AND `user_password`='".$User_password."' ";
$result = mysql_query($sql) or trigger_error(mysql_error().$sql);
// $result = mysql_query("SELECT * FROM `user_info` WHERE `User_name`='".$username."' AND `User_password``='".$password."'");
$my_arary = array();
while($row = mysql_fetch_assoc($result))
{
$_SESSION['id']= $row["Id"];
// echo $_SESSION['login_user_id'];
$_SESSION['user_password']= $row["user_password"];
//echo $_SESSION['login_user_password'];
$_SESSION['user_name']= $row["user_name"];
//echo $_SESSION['login_user_name'];
$my_arary[] = $row;
print_r($row);
if($User_name == $_SESSION['user_name'] && $User_password == $_SESSION['user_password']){
header("Location: userpanel.php");
//echo "successfully logged in";
}
else{
echo "no matches";
header("Location: user_login_basic.php");
}
}
}
?>
You set your $_SESSION['id']= $row["Id"] . Are you sure there column Id in your table? Because you using user_id instead of Id in your query in user admin panel code

Categories