I am a new PHP programmer. I created a user login page where can i see list of user who is logged in. I am using PDO for connecting database. The Problem is if I want to delete user from the list it only delete the last inserted user. What i am doing wrong ? Can someone please help me...
Here is my HTML code:
<form action="" method="post">
<?php
foreach($rows as $row){
$time = $row['time_out'];
echo "
<input type='text' value='$row[user_name]' name='user_name'>
<input type='text' value=' $row[course]' name='course'>
<input type='text' value=' $time'>
<input type='submit' value='submit' name='submit'>
<br>";
}
?>
</form>
if(isset($_POST['submit'])){
//get course
$course = $_POST['course'];
//get user_name
$user_name = $_POST['user_name'];
//deleting user from the database
$database->delete($user_name);
//Redirect to current page
header('Location: tutor.php');
exit;
}
Here is my method for getting logged in user:
public function selectFromOnline()
{
$sql = $this->connection()->prepare("SELECT * FROM online");
$sql->execute();
return $sql->fetchAll();
}
Here is my method for deleting user:
public function delete($user_name)
{
$sql = $this->connection()->prepare("DELETE FROM online WHERE user_name = :user_name");
$sql->bindValue(':user_name', $user_name, PDO::PARAM_STR);
$sql->execute();
return $sql;
}
Sorry But I didn't understand your code but I understood your problem and here it is my solution with "mysqli_query"....
<?php
//Please set these veriables according to your values....
$host_name = "YOUR_DB_HOST_NAME"; //Normally 'localhost'
$password = "YOUR_PASSWORD_FOR_MYSQL"; //your password
$username = "YOUR_USERNAME_FOR_MYSQL"; //Normally Root
$database_name = "NAME_OF_YOUR_DATABASE";
$connect = mysqli_connect($host_name, $username, $password, $database_name);
if(!$connect){
echo "Something is Wrong Please Check your host name, user name, password or database name";
}
?>
<!--YOUR FORM STARTS----------------------------------------------------->
<!--DON'T FORGET TO SET ACTION TO #(ON THE SAME PAGE)------------------------------------>
<form action="#" method="post">
<?php
foreach($rows as $row){
$time = $row['time_out'];
//Any Two Input Fields Cant have same Name So...
echo "
<input type='text' value='$row[user_name]' name='user_name_display'>
<input type='text' value=' $row[course]' name='course'>
<input type='text' value=' $time'>
<input type='hidden' value='$row[user_name]' name='user_name'>
<input type='submit' value='submit' name='submit'>
<br>";
}
?>
</form>
<!--YOUR FORM ENDS----------------------------------------------------->
<?PHP
if(isset($_POST['submit'])){
//get course
$course = $_POST['course'];
//get user_name
$user_name = $_POST['user_name'];
//Creating and running mysqli query
$delete = "DELETE FROM online WHERE user_name='$user_name'";
$query = mysqli_query($connect, $delete);
if($query){
//Code to run when user is deleted
header("Location: tutor.php")
}else{
//Error to show when can't delete user
echo "Sorry Can't delete the user";
}
}
?>
Just forget about some semicolons and some minor errors (if there is any), It'll Defiantly Work....
Please Don't Forget to Vote if it works....
The problem is that every input has the same name so you get nothing when you try to obtain POST values. Try a different approach. Maybe you can add a new field (hyperlink) that performs the redirect action and send the parameters of deleting action with GET.
Example:
echo "
<input type='text' value='$row[user_name]' name='user_name'>
<input type='text' value=' $row[course]' name='course'>
<input type='text' value=' $time'>
<a href='Test.php?username=$row[user_name]&course=$row[course]'>delete</a>
<br>";
}
Test.php is the name of your php page.
Then you can query the database by using the the GET value:
$_GET["username"]
Related
I've created a mysql table with two columns. One is ID and other is Heading. I have a textarea on which I run UPDATE code and whenever someone submits a form its being updated in the datebase column under heading. And that works fine but I want to show the last inputted submit inside my textarea.
My code is showing the last inputted value but when I reset the page it all turns out blank and its not showing anymore. I looked out in datebase and the heading is still there so I don't know why its dissapearing from the front end.
My page:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
So for example if I type Aleksa, after submit it will get url like edit.php?heading=Aleksa&submit=Submit. And then when I delete url just to edit.php, the value is missing.
You can test the page here: https://www.easybewussterschaffen.com/admin/edit.php
This is happening, because it's always trying to insert the heading when you refresh the page. You should check to see if the request is GET or the request is POST, and only insert it if they're submitting the form.
Update your form method, specify it to POST, and specifically check the method or check for the existance of $_POST['submit'] as shown below:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
// Use one of the 2 if statements:
if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Trying to insert a new heading
if (isset($_POST['submit'])) { // Alternative
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="POST">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
Alternatively, if you still wish to make a GET request, you should check to make sure that the heading is set:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
if (isset($_GET['submit'])) {
$heading = mysqli_real_escape_string($link, $_GET['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="GET">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
I did it like this, is this good tho? Its working
<?php
$sql = "SELECT * FROM content";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo '';
while($row = mysqli_fetch_array($result)){
echo $row['heading'];
}
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>
Hi iam inserting the data into database table and redirecting to another page and need to insert the details into the same table by comparing ids and email.But how to get the last inserted id and compare in where condition to update the details.
Here is my code:
index.php
<form method="post" action="properties.php" id="myform">
<input type='hidden' value="<?php echo $username; ?>" name='email'>
<tr><th>Interest Paid</th><td><input type="text" name="house_interest_paid" value=""/></td>
<tr><th>Total Interest Paid</th><input type="text" name="house_total_interest_paid" value=""/></td>
<tr><th>House Number</th><input type="text" name="house_number" value=""/></td>
<tr><th>Street</th><input type="text" name="house_street" value=""/></td>
<button type="submit" class = "large awesome yellows" onClick="document.location.href='ownerproperty.php'"> Specify Co-owners Property</button> </span>
</form>
properties.php
$email=$_POST['email'];
$interest=$_POST['house_interest_paid'];
$interestpaid=$_POST['house_total_interest_paid'];
$number=$_POST['house_number'];
$street=$_POST['house_street'];
$query=mysql_query("INSERT INTO house_details(email,house_interest_paid,house_total_interest_paid,house_number,house_street)values ('$email','$interest','$interestpaid','$number','$street')");
if($query)
{
session_start();
header("Location:ownerproperty.php");
}
else{
echo "Registration has not been completed.Please try again";
}
ownerproperty.php
<form style="display:none" method="POST" action="owner.php">
<h2>Owner Property details</h2>
<input type='hidden' value="<?php echo $username; ?>" name='email'>
<?php include "ownership.php"; ?>
<p><label for="name_coowner">Coowner Name</label> <input value="<?php echo $row['name_coowner'];?>" type="text" name="name_coowner" /></p>
<p><label for="pan_coowner">PAN Of Coowner</label> <input value="<?php echo $row['pan_coowner'];?>" type="text" name="pan_coowner" /></p>
<button type="submit" class = "medium" style="background-color: #2daebf;">Save</button>
</form>
Ownership.php
$res = "SELECT * FROM house_details
WHERE email ='$username'";
$result=mysql_query($res);
$row = mysql_fetch_array($result);
Owner.php
$email=$_POST['email'];
$owner_name=$_POST['name_coowner'];
$pan_owner=$_POST['pan_coowner'];
$query=mysql_query("UPDATE house_details SET name_coowner='$owner_name',pan_coowner='$pan_owner'
WHERE email='$email' AND house_details_id='2'");
if($query)
{
session_start();
header("Location:rentalproperty.php");
}
For the first time when i click on submit button the data is inserting into db and redirecting to ownerproperty.php .in that i need to get the inserted id and need to comapre that id and email and need to update the owner property details in the same column when the email and id are same.But how to get that id and compare in the where condition can anyone help me.
properties.php
$query=mysql_query("INSERT INTO house_details(email,house_interest_paid,house_total_interest_paid,house_number,house_street)values ('$email','$interest','$interestpaid','$number','$street')");
$id = mysql_insert_id(); //For last inserted id.
if($query)
{
session_start();
$_SESSION['sess_id'] = $id; // Set one session variable for last inserted id.
header("Location:ownerproperty.php");
}
owner.php
<?php
session_start(); // Start your session
$id = $_SESSION['sess_id']; // Use this id in query
$email=$_POST['email'];
$owner_name=$_POST['name_coowner'];
$pan_owner=$_POST['pan_coowner'];
$query=mysql_query("UPDATE house_details SET name_coowner='$owner_name',pan_coowner='$pan_owner'
WHERE email='$email' AND house_details_id='2'");
if($query)
{
session_start();
header("Location:rentalproperty.php");
}
[NOTE : mysql extensions are deprecated. Use PDO or mysqli_ database extensions.]
You can add this:
$stmt = 'SELECT LAST_INSERT_ID() as sessionId';
Which should grab the ID from the last insert.
$query=mysql_query("INSERT INTO house_details(email,house_interest_paid,house_total_interest_paid,house_number,house_street)values ('$email','$interest','$interestpaid','$number','$street')");
if($query)
{
//Last inserted ID
$last_id = $query->insert_id;
session_start();
header("Location:ownerproperty.php");
}
else{
echo "Registration has not been completed.Please try again";
}
You can add this:
$stmt = 'SELECT MAX(house_details_id) AS "id" FROM house_details';
$result=mysql_query($stmt);
$row = mysql_fetch_array($result);
$id = $row['id'];
So I'm just making a simple program that puts names into a database. I got that part down, I can enter a name into a form, then display it on the page, but now I'd like to know how to delete them from the database, and no longer show them on the page.
I added a button next to each name that triggers the third if statement (with the commented out query), and from what I can tell it's best to run a query based on the element's id (my primary key that auto increments), but I have no idea how to get the id from the element who's button I'm clicking on.
How do I get the id from one of the elements in my while loop? Or if there's a better way to delete them, what's that?
if (mysqli_connect_errno()) {
die('could not connect');
}
if (isset($_POST['first_name'], $_POST['last_name'])){
$first_name = trim($_POST['first_name']);
$last_name = trim($_POST['last_name']);
$putitin = mysqli_query($db, "INSERT INTO names (first_name, last_name) VALUES ('$first_name', '$last_name')");
}
if (isset($_POST['del'])){
//$takeitout = mysqli_query($db, "DELETE FROM names WHERE id = ");
}
?>
<html>
<head>
</head>
<body>
<form action='' method='post'>
<div>
<label for "first_name">First name</label>
<input type="text" name="first_name">
</div>
<div>
<label for "last_name">Last name</label>
<input type="text" name="last_name">
</div>
<div>
<input type="submit" value="Insert">
</div>
</form>
<hr>
<?php
$resultset = $db->query('SELECT * FROM names');
if($resultset->num_rows != 0){
while($rows = $resultset->fetch_assoc()) {
$fname = $rows['first_name'];
$lname = $rows['last_name'];
$id = $rows['id'];
echo "<form action='' method='post'><p>Name: $fname $lname $id<input type='submit' name='del'></form></p>";
}
} else {
echo 'No results';
}
?>
</body>
</html>
This is one way.
change your html part to
<form action='' method='post'>
<input type='hidden' name='id' value='$id' />
<p>Name: $fname $lname $id
<input type='submit' name='del' value=''>
</form></p>
and your php
if (isset($_POST['del'])){
$id = $_POST['id'];
$takeitout = mysqli_query($db, "DELETE FROM names WHERE id = '$id'");
}
Note:
What you can do is to put all your input fields inside your while loop. Then assign values to each of them, but we have to use array to store them accordingly.
We can use checkbox to store the IDs.
What will happen, is user can select from the list of names they wanted to delete by ticking the corresponding checkbox, then pressing the Delete button below.
Your code
<form action="" method="POST">
<?php
$resultset = $db->query('SELECT * FROM names');
if($resultset->num_rows != 0){
while($rows = $resultset->fetch_assoc()) {
$fname = $rows['first_name'];
$lname = $rows['last_name'];
$id = $rows['id'];
echo '<input type="checkbox" name="id[]" value="'.$id.'">'.$fname.' '.$lname.'<br>';
} /* END OF WHILE LOOP */
?>
<input type="submit" value="Delete" name="delete">
</form>
And your PHP that will process the form:
<?php
if(isset($_POST["delete"])){
$counter = count($_POST["id"]);
for($x = 0; $x<$counter; $x++){
if(!empty($_POST["id"][$x])){ /* CHECK IF AN ITEM IS SELECTED */
/* DELETE QUERY */
if($stmt = $db->prepare("DELETE FROM names WHERE id = ?")){
$stmt->bind_param("i",$_POST["id"][$x]);
$stmt->execute();
$stmt->close();
} /* END OF PREPARED STATEMENT */
} /* END OF IF; CHECKING IF IT IS SELECTED */
} /* END OF FOR LOOP */
} /* END OF ISSET DELETE */
?>
after trying to debug this snipet of code for hours, I find I cannot figure out why my edit form wont update for the life of me. I'm not sure if it's because I'm not using GET or POST methods correctly, I'm mis-using mysql, or a combination of the both. I cant even figure out why a line of print "hi"; wont show up. if i take out the line of code testing when the edit submit button is hit the print lines come out but my database wont update. So I figure I'm stuck where I can't do anymore print line debugging untill I figure out what I'm doing wrong. here is my code.. I commented next to the "print "hi";" line that doesnt show up. keep in mind I'm pretty sure I tried every combination of GET and POST and it still doesnt show up...
<html lang="en">
<head>
<title>Employee</title>
</head>
<body>
Clean <br>
<form method="post" action="employ.php">
<input type="text" name="fname">First Name<br>
<input type="text" name="lname">Last Name<br>
<input type="text" name="email">email<br>
<input type="text" name="zip">zip code<br>
<input type="submit" name="add" value="Add"> <!-- button itself -->
</form>
<br>
<?php //server login name password database
$link = mysqli_connect("server", "login", "password", "database") or die(mysqli_error());
if(isset($_POST['add'])) //this processes after user submits data.
{
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$zip = $_POST['zip'];
$re = "/^[a-zA-Z]+(([\'\- ][a-zA-Z])?[a-zA-Z]*)*$/";
$reEmail = "/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/";
$reZip = "/^\d{5}$/";
//if user passes re test
if( preg_match($re, $fname) && preg_match($re, $lname)
&& preg_match($reEmail, $email) && preg_match($reZip, $zip) )
{ //display current table
$querycheck = "select * from employees where fname='$fname' and email='$email'";
$resultcheck = mysqli_query($link, $querycheck); //link query to database
if(mysqli_num_rows($resultcheck) == 0)// test if query does "nothing"
{//if not process the insert query
$query = "insert into employees values('', '$fname', '$lname', '$email', '$zip')";
mysqli_query($link, $query); //link query to database
print "Employee Added"; // print confirmation
}
else
{
print "That record already exists!";
}
}
else
{
print "You did not fill out the form correctly!";
}
} ////////////////////////////////edit portion/////////////////////////////
if(isset($_GET['edit']))
{
print "teseting edit<br><br>";
?>
<form method="get" action="employ.php">
<input type="text" name="fname" value = "<?php echo $_GET['fname']?>">First Name<br>
<input type="text" name="lname" value = "<?php echo $_GET['lname']?>">Last Name<br>
<input type="text" name="email" value = "<?php echo $_GET['email']?>">email<br>
<input type="text" name="zip" value = "<?php echo $_GET['zip']?>">zip code<br>
<input type="hidden" name="employeeid" value = "<?php echo $_GET['employeeid']?>">
<input type="submit" name="endedit" value="Edit"> <!-- button itself -->
</form>
<?php
print "teseting end edit <br><br>";
if(isset($_POST['endedit'])) //this processes after user submits edited data
{ //tried get and post
print "hi"; // DOESNT APPEAR
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$zip = $_POST['zip'];
$employeeidtemp = $_POST['employeeid'];
$re = "/^[a-zA-Z]+(([\'\- ][a-zA-Z])?[a-zA-Z]*)*$/";
$reEmail = "/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/";
$reZip = "/^\d{5}$/";
//if user passes re test
if( preg_match($re, $fname) && preg_match($re, $lname)
&& preg_match($reEmail, $email) && preg_match($reZip, $zip) )
{ //display current table
//$querycheck = "select * from employees where employeeid='$employeeidtemp'";
//$resultcheck = mysqli_query($link, $querycheck); //link query to database
// if(mysqli_num_rows($resultcheck) == 0)// test if query does "nothing"
// {
$query = "UPDATE employees SET fname='$fname', lname='$lname', email='$email', zip='$zip' WHERE employeeid='$employeeidtemp'";
mysqli_query($link, $query); //link query to database
print "Employee Updated"; // print confirmation
// }
// else
// print "huh?";
}
else
{
print "You did not fill out the form correctly!";
}
}
}
if(isset($_GET['delete']))
{
print "teseting delete<br><br>";
}
showemp();
function showemp()
{
global $link;
if(isset($_GET['choice']))
{
$choice = $_GET['choice'];
}
else
{
$choice = "lname";
}
$query = "select * from employees order by $choice";
$result = mysqli_query($link, $query);
// print table (happens first before input)
// first print row of links/headers that sort
print "<table border='1'>
<tr>
<th>Edit</th>
<th>Delete</th>
<th><a href='employ.php?choice=fname'>FNAME</a></th>
<th><a href='employ.php?choice=lname'>LNAME</a></th>
<th><a href='employ.php?choice=email'>EMAIL</a></th>
<th><a href='employ.php?choice=zip'>ZIP</a></th>
</tr>";
//while the next row (set by query) exists?
while($row = mysqli_fetch_row($result))
{
list($employeeid, $fname, $lname, $email, $zip) = $row;
print "<tr>
<td><a href='employ.php?edit=yes&employeeid=$employeeid&fname=$fname&lname=$lname&email=$email&zip=$zip'>Edit</a></td>
<td><a href='employ.php?delete=yes&employeeid=$employeeid
onclick='return confirm(\"Are you sure\")'>Delete</a></td>
<td>$fname</td>
<td>$lname</td>
<td>$email</td>
<td>$zip</td>
</tr>";
}
print "</table>";
}
?>
</body>
</html>
You have several errors:
You do not check the result of queries, use at least
code mysqli_query($link, $query) or die(mysqli_error($link));
When I kick your code with checking errors, I found that adding query does not work - your empty string value for employeeid does not accepted for my integer field.
Do not use GET in forms. Always POST. If you need reaction on GET-url, write it separately or use $_REQUEST var.
In INSERT query always write fields. When you will decide to change list of fields in mysql table, then you can get the strange behavior of this code.
Your main error is that your condition with print 'hi' is inside the condition if(isset($_GET['edit'])), it does not work when user sublim form.
created a user login page. Where I can see which user is logged in. But I can’t delete user from database. I am using PDO for connecting database. Here is my method for deleting user:
public function delete($user_name)
{
$sql = $this->connection()->prepare("delete from online where user_name = :user_name");
$sql->bindValue(':user_name', $user_name, PDO::PARAM_STR);
$sql->execute();
return $sql;
}
here is my HTML code:
if(isset($_POST['submit'])){
$user_name = isset($_POST['user_name']);
print_r($user_name);
//call delete method to delete the user from database
$database->delete($user_name);
}
<form action="" method="post">
<?php
foreach($rows as $row){
$time = $row['time_out'];
echo "<input type='text' value='$row[user_name]' name='user_name'>
<input type='text' value=' $row[course]' >
<input type='text' value=' $time '>
<input type='hidden' value='$row[user_name]' name='user_name'>
<input type='submit' value='delete' name='submit'><br>";
}
?>
</form>
$user_name is a boolean because you're setting it to the result of isset()
Perhaps you meant to do something like:
if(isset($_POST['submit'])){
$user_name = isset($_POST['user_name']) ? $_POST['user_name'] : false;
if($user_name) {
print_r($user_name);
//call delete method to delete the user from database
$database->delete($user_name);
} else {
echo "No user name found!";
}
}
Try using this -
if (isset($_POST['user_name'])) {
$user_name = $_POST['user_name'];
$database->delete($user_name);
}
And you should study how to use isset()- http://php.net/manual/en/function.isset.php