My question is how can i change GET method to the POST method after click action on the delete button on page Users List.
After delete using POST on top of page users.php must be message "User $name deleted!"
users.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Users</title>
</head>
<body>
<h1>Users List</h1>
<?php
include('db_connect.php');
$db_conn = #new mysqli($host, $db_user, $db_password, $db_name);
if($result=$db_conn->query("SELECT * FROM user ORDER BY id")){
if($result->num_rows > 0){
echo "<table border='1' cellpadding='10'>";
echo "<tr><th>ID</th><th>Name</th></tr>";
while($row=$result->fetch_object()){
echo "<tr>";
echo "<td>".$row->id."</td>";
echo "<td>".$row->name."</td>";
echo "<td><a href='delete.php?id=" . $row->id . "'>Delete</a></td>";
echo "</tr>";
}
echo "</table>";
}else{
echo "No records";
}
}else{
echo "error: ". $db_conn->error;
}
$db_conn->close();
?>
<br>Add user
</body>
</html>
delete.php
<?php
require_once 'db_connect.php';
$db_conn = #new mysqli($host, $db_user, $db_password, $db_name);
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
$id = $_GET['id'];
if ($stmt = $db_conn->prepare("DELETE FROM user WHERE id = ? LIMIT 1"))
{
$stmt->bind_param("i",$id);
$stmt->execute();
$stmt->close();
}
else
{
echo "ERROR: could not prepare SQL statement.";
}
$db_conn->close();
header("Location: users.php");
}
else
{
header("Location: users.php");
}
Please help! :)
Use form with hidden inputs & submit button instead of links:
Change:
echo "<td><a href='delete.php?id=" . $row->id . "'>Delete</a></td>";
With:
echo '<td><form action="delete.php" method="POST"><input type="hidden" name="id" value="' . $row->id . '"><input type="submit" name="submit" value="Delete"></form></td>';
& surely this should be handled in PHP:
Change:
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
$id = $_GET['id'];
To:
if (isset($_POST['id']) && is_numeric($_POST['id']))
{
$id = $_POST['id'];
You can do the following then
In your delete.php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
//DO the deletin here
}
In users.php
echo "<td><form action='delete.php' method = 'post'><input type = 'hidden' name = 'user_id' value = '" . $row->id . "' /><button type = 'submit'> Delete</button></form></td>";
Related
I am making a school project.
The meaning of this project is that i create a login/registration form,
where i can register, login, view the record.
But i also need to make a dropdown menu were i can see all the records (users) and below it i need to make a button and when i select a record/user and press the delete button it need to be deleted from the database. and i have no clue how i can do this.
here is my code:
<?php
include ("connectie.php");
include ("deletecode.php");
$conn = new mysqli("localhost", "student14_admin", "lol12345","student14_jordi");
mysqli_select_db($conn,'student14_jordi');
$sql = "DELETE FROM users WHERE ID='$_GET[id]'";
echo "<select name='user'>";
if ($result->num_rows>0) {
while($row = $result->fetch_assoc()) {
echo "<option value=" . $row['username'] . ">" . $row['username'] . "</option>";
}
}
echo "</select>";
?>
<form action="">
<a class="delete" href="delete.php?id=<?php echo $row['id']; ?>">Delete</a>
</form>
Create a button and name it Delete
<a class="delete" href="delete.php?id=<?php echo $row['id']; ?>">Delete</a>
Then make a delete.php file and have these code there.
<?php include_once 'db_config_filename.php';
// get id value
$id = $_GET['id'];
// sql to delete a record
$sql = "DELETE FROM tablename WHERE id='$id'";
// print_r($sql);
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
}
else {
echo "Error deleting record: " . mysqli_error($conn);
}
//redirect here
include 'data.php';
?>
I almost have it working. i have now this code:
delete.php:
<?php
include ("connectie.php");
$sql = "SELECT * FROM users ";
$result = $conn->query($sql);
echo "<select name='user'>";
if ($result->num_rows>0) {
while($row = $result->fetch_assoc()) {
echo "<option value=" . $row['username'] . ">" . $row['username'] . "
</option>";
}
}
echo "</select>";
?>
<form action="" method="GET">
<input type="hidden" name="id" value=".$row['id']." />
<input type="submit" name="delete" value="verwijderen">
</form>
<?php
include ("deletecode.php");
?>
Deletecode.php:
<?php
$servername = "localhost";
$username = "student14_admin";
$password = "lol12345";
$dbname = "student14_jordi";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to delete a record
$sql = "DELETE FROM users WHERE id=3";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
well this works for only record 3 afcourse. but now i need to have it that if i select a record from the dropdown menu and click on the delete button it needs to delete that record from my database.
I made from in php. When I select a class, for example I select the class9, it shows me the table of class9. I also have inserted a row in the table containing the delete button to delete the corresponding row. Now I want to delete a row buy clicking the button which is in the row. how can I do that?
First I choose a class from this option as in the image below ;The image from which we select the class
And then the corresponding table is going to be shown.
This is the image. When I click on the button, the corresponding row should be deleted.
<?php
include "connection.php";
?>
<!doctype html>
<html>
<head>
<title>KDR</title>
</head>
<body>
<table border="2px" width="50%" height="auto">
<tr>
<th>No</th>
<th>Name</th>
<th>F/Name</th>
<th>Age</th>
<th>Delete</th>
</tr>
<?php
$table = $_POST['formCountry'];
$sql = "SELECT * FROM $table";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['fname'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td><form method='POST' ><input type='submit' name='deletestudent' value='Delete'/></form></td>";
echo "</tr>";
}
?>
</table>
</body>
Something like this. Maybe will need to adjust it a bit.
Your table button:
echo "<td><form method='POST' action="delete_row.php" ><input type='submit' name='deletestudent' value="'.$row['id'].'"/></form></td>";
In PHP (delete_row.php) you should do the following
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['id']) and is_numeric($_POST['id']))
{
$delete = $_POST['id']
$stmt = $conn->prepare("DELETE FROM YOURTABLENAME WHERE id = ?");
$stmt->bind_param('i', $delete);
$stmt->execute();
$stmt->close();
}
Note: Not tested and I'm using mysqli_* here.
Update: As #icecub suggested you can use also hidden field to get the ID
echo "<td>
<form method='POST' action='delete_row.php' >
<input type='hidden' name='deletestudent' value='".$row['id']."'/>
<input type='submit' value='Delete'/>
</form>
</td>";
This is how not to do , see the comments below , important !
Should be send the current id of the element , so when you click the button
get the element ID by $_GET['id'];
<td><a href='?id=".$row['id']."'>delete</a></td>
if (isset($_GET['id'])) {
//Throw query DELETE ... WHERE id = $_GET['id'];
}
How do I refresh the table when I click EDIT NOW Button? or this is easier, how do I make refresh button to refresh the table? I have no knowledge on JSP to auto refresh. However, I manage to make an onchange event so when I choose menu, it will refresh upon changing. When I edit a data and submit, it does not refresh. How do I re-execute the echo of table? Thanks!
<?php
$selected='';
function get_options($select)
{
$conn = new mysqli('localhost', 'root', 'jared17', 'hbadb')
or die ('Cannot connect to db');
$result = $conn->query("select * from students");
$options='';
while ($row = $result->fetch_assoc())
{
$LRN = $row['LRN'];
$Last = $row['Last_Name'];
$First = $row['First_Name'];
if($LRN == $_GET['Students'])
{
$options.='<option value="'.$LRN.'" selected>'.$Last.', '.$First.'</option>';
}
else
{
$options.='<option value="'.$LRN.'">'.$Last.', '.$First.'</option>';
}
}
return $options;
}
if (isset($_GET['Students'])) {
$conn = new mysqli('localhost', 'root', 'jared17', 'hbadb')
or die ('Cannot connect to db');
$result = $conn->query("select * from students");
$lrn = $_GET['Students'];
$stmt = $conn->prepare("SELECT Last_Name, First_Name, Level, Q1, Q2, Q3, Q4, FINAL FROM english WHERE LRN = ?");
$stmt->bind_param('i', $lrn);
$stmt->execute();
$stmt->bind_result($last, $first, $level, $q1, $q2, $q3, $q4, $final);
$stmt->fetch();
echo "<table><tr><th>LRN</th><th>Name</th><th>Level</th><th>Q1</th><th>Q2</th><th>Q3</th><th>Q4</th><th>Final</th></tr>";
echo "<tr><td>$lrn</td><td>$last, $first</td><td>$level</td><td>$q1</td><td>$q2</td><td>$q3</td><td>$q4</td><td>$final</td></tr></table>";
}
echo "<html>";
echo "<body>";
echo "<form method=GET>";
echo "<select name=Students onchange=this.form.submit();>";
echo get_options();
echo "</select>";
echo "</form>";
echo "<form method=POST>";
///////////EDIT DATA
echo "Edit Data: ";
echo "<select name = 'Edit'>";
echo '<option value=Q1>Q1</option>';
echo '<option value=Q2>Q2</option>';
echo '<option value=Q3>Q3</option>';
echo '<option value=Q4>Q4</option>';
echo '<option value=FINAL>FINAL</option>';
echo '<input type="number" max="100" name="editdata" required>';
echo "</select>";
echo "<input type='submit' name='submit2' value='Edit Now'>";
if (isset($_POST['Edit'])) {
$conn2 = new mysqli('localhost', 'root', 'jared17', 'hbadb')
or die ('Cannot connect to db');
$upd = $_POST['Edit'];
$txt = $_POST['editdata'];
$now = "UPDATE english SET $upd='$txt' WHERE LRN='$lrn'";
$res = $conn2->query($now);
if (!$conn2->error) {
echo "Errormessage: $conn->error";
}
echo $now;
}
echo "</form>";
echo "</body>";
echo "</html>";
?>
I would use 2 pages view.php and edit.php. View would display the data with link to edit. When you click edit it would open edit.php to load the form to edit data and save it to db. Then issue the command
header("Location: view.php");
to reload the view.php and display the new data
I have uploaded the scripts I use as a basis for databases so you can see if this is what you want - feel free to amend any data it is just a test database. If you want more code just ask
www.cambodia.me.uk/php/view.php
Edited to include scripts as requested - sorry it is old code and mysql not mysqli
Connect script
<?php
/*
CONNECT-DB.PHP
Allows PHP to connect to your database
*/
// Database Variables (edit with your own server information)
$server = 'server';
$user = 'user';
$pass = 'pass';
$db = 'database';
// Connect to Database
$connection = mysql_connect($server, $user, $pass)
or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($db)
or die ("Could not connect to database ... \n" . mysql_error ());
?>
View script
<?php
include('remote-connect.php');
$result = mysql_query("SELECT * FROM stats")
or die(mysql_error());
echo "<p><b>View All</b> | <a href='view-paginated.php?page=1'>View Paginated</a></p>";
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>date</th> <th>Home Team</th> <th></th><th></th><th>Away Team</th> <th></th> </tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr>";
echo '<td>' . $row['date'] . '</td>';
echo '<td>' . $row['hometeam'] . '</td>';
echo '<td>' . $row['fthg'] . '</td>';
echo '<td>' . $row['ftag'] . '</td>';
echo '<td>' . $row['awayteam'] . '</td>';
echo '<td>Edit</td>';
//echo '<td>Delete</td>';
echo "</tr>";
}
echo "</table>";
?>
<p>Add a new record</p>
</body>
</html>
Edit script
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
function renderForm($id, $hometeam, $awayteam, $error)
{
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>First Name: *</strong> <input type="text" name="hometeam" value="<?php echo $hometeam; ?>"/><br/>
<strong>Last Name: *</strong> <input type="text" name="awayteam" value="<?php echo $awayteam; ?>"/><br/>
<p>* Required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
include('remote-connect.php');
if (isset($_POST['submit']))
{
if (is_numeric($_POST['id']))
{
$id = $_POST['id'];
$hometeam = mysql_real_escape_string(htmlspecialchars($_POST['hometeam']));
$awayteam = mysql_real_escape_string(htmlspecialchars($_POST['awayteam']));
if ($hometeam == '' || $awayteam == '')
{
$error = 'ERROR: Please complete all mandatory fields!';
renderForm($id, $hometeam, $awayteam, $error);
}
else
{
mysql_query("UPDATE stats SET hometeam='$hometeam', awayteam='$awayteam' WHERE id='$id'")
or die(mysql_error());
// Go back to view page and redisplay the edited data
header("Location: view.php");
}
}
else
{
echo 'Error!';
}
}
else
{
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM stats WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
if($row)
{
$hometeam = $row['hometeam'];
$awayteam = $row['awayteam'];
renderForm($id, $hometeam, $awayteam, '');
}
else
{
echo "No results!";
}
}
else
{
echo 'Error!';
}
}
?>
</body>
</html>
It's so easy. If you fetch your table's values after edit or delete operation, sql will bring fresh data.
I want to ensure "StaffID" is stored when the "View Contacts" page is loaded from a link, rather than straight from the Login Form
LOGIN FORM:
<?php session_start(); // Start PHP session
$StaffID = isset($_SESSION["StaffID"]) ? $_SESSION["StaffID"] : "";?>
<form name="staffaccess" method="post" action="staff-login.php">
<table border="1" cellpadding="3" cellspacing="1">
<tr>
<td colspan="3"><strong>Staff Login </strong></td>
</tr>
<input type="hidden" name="StaffID" id="StaffID" value="<?php echo $StaffID; ?>" />
<tr>
<td>Username:</td>
<td><input name="StaffUsername" size= "30" type="text" id="StaffUsername" value="<?php echo $StaffUsername; ?>"/></td>
</tr>
<tr>
<td>Password:</td>
<td><input name="StaffPassword" size= "30" type="text" id="StaffPassword" value="<?php echo $StaffPassword; ?>"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="Login"/></td>
</tr>
</table>
</form>
LOGIN CHECK:
<?php session_start(); // Start PHP session?>
<body>
<?php
$_SESSION["StaffUsername"] = isset($_POST["StaffUsername"]) ? $_POST["StaffUsername"] : "";
$_SESSION["StaffPassword"] = isset($_POST["StaffPassword"]) ? $_POST["StaffPassword"] : "";
$_SESSION["StaffID"] = isset($_GET["StaffID"]) ? $_GET["StaffID"] : "";
<?php
//connect to database//
$dbc = mysql_connect("", "", "");
if (!$dbc)
die ('Could not connect: ' .mysql_error());
//select database//
$db_selected = mysql_select_db("tafe", $dbc );
if (!$db_selected)
die ('Could not connect: ' . mysql_error());
// username and password sent from form
$StaffUsername=$_POST['StaffUsername'];
$StaffPassword=$_POST['StaffPassword'];
// To protect MySQL injection (more detail about MySQL injection)
$StaffUsername = stripslashes($StaffUsername);
$StaffPassword = stripslashes($StaffPassword);
$StaffUsername = mysql_real_escape_string($StaffUsername);
$StaffPassword = mysql_real_escape_string($StaffPassword);
$qry=("SELECT * FROM staffaccess WHERE Username= '" . $StaffUsername . "' AND Password= '" .$StaffPassword ."'");
$rst = mysql_query($qry, $dbc);
$row = mysql_fetch_array($rst);
if ($row["Username"]==$StaffUsername && $row["Password"]==$StaffPassword)
{
$_SESSION["StaffID"] = $row["StaffID"];
echo "Your login was successful";
echo "</br></br>";
echo "<a href=list-contacts.php>Continue</a>";
}
else {
echo "Sorry your details are not valid";
echo "</br></br>";
echo "<a href=staff-login.htm>Return</a>";
}
?>
VIEW CONTACTS (i only want this to allow to view contacts that particular user has added)
<?php
//connect to database
$dbc = mysql_connect("", "", "");
if (!$dbc)
die ('Could not connect: ' .mysql_error());
//select database
$db_selected = mysql_select_db("tafe", $dbc );
if (!$db_selected)
die ('Could not connect: ' . mysql_error());
$StaffID = (int)$_GET['StaffId'];
// build sql insert statement
**$qry = "SELECT * FROM contacts WHERE StaffID= $StaffID ORDER by name ASC";**
//run insert satement against database
$rst = mysql_query($qry, $dbc);
// print whether successful or not
if ($rst)
{
if (mysql_num_rows($rst)>0) // check that there are records
{
echo "<table border=\"1\" cellspacing=\"0\">";
/***print out field names***/
echo "<tr>"; // start row
for ($i=0; $i<mysql_num_fields($rst); $i++) // for each field print out field name
{
echo "<th>" . mysql_field_name($rst, $i) . "</th>";
}
echo "<th> </th>";
echo "<th> </th>";
echo "</tr>";
/***print out field values***/
while ($row = mysql_fetch_array($rst)) // fetch each of the rows
{
echo "<tr>";
echo "<td>".$row['ContactID']."</td>";
echo "<td>".$row['Name']."</td>";
echo "<td>".$row['Address']."</td>";
echo "<td>".$row['Phone']."</td>";
echo "<td>".$row['Mobile']."</td>";
echo "<td>".$row['Email']."</td>";
echo "<td><a href='edit-contact.php?id=".$row['ContactID']."'>Edit</a></td>";
echo "<td><a href='delete-contact.php?id=".$row['ContactID']."'>Delete</a></td><tr>";
echo "</tr>";
}
echo "</table>";
}
else
{
echo "<b><font color='black'>No records returned.</font></b>";
}
}
else
{
echo "<b><font color='red'>Error: ".mysql_error($dbc) . "</font></b>";
}
?>
you didnt pass the staff id on contact page so you pass the staff id like this
change following change in logincheck page
if ($row["Username"]==$StaffUsername && $row["Password"]==$StaffPassword)
{
echo "Your login was successful";
echo "</br></br>";
echo "Continue";
}
you can also use session for logged user
Depending on you mysql version, you may need to quote your where properties, I'm not sure if this is causing your problem, but it may be related. Also, are you sure that your value for the StaffID field is being correctly inserted into the database?
I checked the code and you are using
echo "<a href=list-contacts.php>Continue</a>";
to send user to see the contacts and in this page you are doing
$StaffID = (int)$_GET['StaffId'];
So you need to pass that value in the query string as
echo "Continue";
I am trying to get the code to update some data that has been selected by the user.
What is happening is that its updating everything in that column to the value the user has edited it to.
For example i have bob, bob1, bob2 and i want to select bob1 to edit. I then edit it so bob1 is now fred1, when it updates it updates every value to fred1. So there is 3 fred1's.
Could someone help? please.
update.php
<?php
session_start();
include_once 'connection.php';
if (isset($_POST['update'])) {
$success = updateValue($_POST['name']);
if (!$success)
echo 'Sorry, the update failed';
session_destroy();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Main Page</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method='post'>
View a Member's Details:
<select name='members' value='members'id="Mmembers">
<?php
$results = getResults('members');
if ($results) {
foreach ($results as $row) {
echo '<option value="' . $row['member_id'] . '">' . $row['name'] . '</option>';
}
}
else
echo '<option value="0"0"> No Data</option>';
?>
</select>
<input type="submit" id="submit" value="Submit"/>
<br/>
<br/>
</form>
<?php
if (isset($_POST['members'])) {
$ResultSet = getMemberResults(($_POST['members']));
echo "<h1> Member Details. </h1>";
echo "<table border='1' cellpadding='6'>";
echo "<tr> <th>Id</th> <th>Name</th>";
foreach ($ResultSet as $row) {
echo "<form action=update.php method=POST>";
echo "<tr>";
echo "<td>" . "<input type=text name=member_id value=" . $row ['member_id'] . " </td>";
echo "<td>" . "<input type=text name=name value=" . $row ['name'] . " </td>";
echo "<td>" . "<input type=submit name=update value=update" . " </td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
}
?>
</body>
</html>
connection.php
<?php
//Connect to the database
function getSQLConnection() {
$mysqlConnection = new PDO('mysql:host=localhost;dbname=', "root", "");
return $mysqlConnection;
}
//Get all results from members table
function getResults($tablename) {
$sql = "SELECT * FROM " . $tablename;
$mysqlConnection = getSQLConnection();
$ResultSet = $mysqlConnection->query($sql);
return $ResultSet;
}
function getMemberResults($id) {
$sql = "SELECT * FROM members WHERE members.member_id = '$id'";
$mysqlConnection = getSQLConnection();
$ResultSet = $mysqlConnection->query($sql);
return $ResultSet;
}
function updateValue($id) {
$sql = "UPDATE members SET name='$id' WHERE members.member_id = members.member_id";
$mysqlConnection = getSQLConnection();
$ResultSetting = $mysqlConnection->query($sql);
return $ResultSetting;
}
?>
Your SQL UPDATE statement is incorrect.
WHERE members.member_id = members.member_id
The above where is always going to resolve true for all rows, making your call
UPDATE members SET name='$id'
You should set the name and also add the members id (a unique identity) in the WHERE cause.
/** give functions descriptive names **/
function updateMemberName($id, $name) {
$sql = "UPDATE members SET name='$name' WHERE id = '$id'";
//...
update.php
You would then just need to modify the function call
if (isset($_POST['update'])) {
$success = updateMemberName($_POST['member_id'], $_POST['name']);
function updateValue($id) {
$sql = "UPDATE members SET name='$id' WHERE members.member_id = members.member_id";
This is equivalent to
UPDATE members SET name='$id'
as the where clause evaluates to TRUE for all rows
Answering only to make it work like you expect it to, This function:
function updateValue($id) {
$sql = "UPDATE members SET name='$id' WHERE members.member_id = members.member_id";
...
}
Needs to be
function updateValue($id, $value) {
$sql = "UPDATE members SET name='$value' WHERE members.member_id=$id";
...
}