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
Related
I have a comments section in a website that uses a "setComments" function to enter data into a SQL DB. This works great, but I found that if I refresh the page, the comment is re-entered into the DB and displayed as multiple comments using a "getComments" function.
I know I need to drop the values of the comment variables but tried a few places in the code and no joy.
This is the form to enter the comment:
<?php
echo "<form method='POST' action='".setComments($conn)."'>
<input type='hidden' name='uid' value='Anonymous'>
<input type='hidden' name='pid' value='$post_id'>
<input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
<label>Add Comment</label>
<textarea name='message'class='form-control' width='50' cols='40'
rows='3'></textarea><br>
<button type = 'submit' name ='commentSubmit' class='btn btn-
primary'>Submit<span class='glyphicon glyphicon-chevron-right'></span>
</button>
</form>";
getComments($conn)
?>
<?php
function setComments($conn){
if (isset($_POST ['commentSubmit'])) {
$uid=$_POST['uid'];
$pid=$_POST['pid'];
$date=$_POST['date'];
$message=$_POST['message'];
$sql = "INSERT INTO comments (uid, pid, date, message)
VALUES('$uid','$pid', '$date', '$message')";
$result = $conn->query($sql);
}
}
function getComments($conn) {
if (isset($_GET['post'])) {
$pid = $_GET['post'];
$sql = "SELECT * FROM comments WHERE pid=$pid";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
if (mysqli_num_rows($result) > 0) {
while($row = $result->fetch_assoc()){
echo "<div class='comment-box'>";
echo $row['uid']."<br>";
echo $row['date']."<br>";
echo $row['message'];
echo "</div>";
}
}
else {
echo "Be the first to comment";
}
}
}
Comments are entered into sql DB fine, but variables not discarded once complete so they are re-entered into DB and displayed again on page refresh (page containing the comment form also displays the comments.
I ended up using the following script in the page - it seems to work fine:
<script>
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
This is the code I wrote to generate as many forms as there is entries in a table.
I'd like to know which Submit button (i.e. of which exact form) was clicked to then execute some SQL actions.
Thank you for your help!
<?php
require_once 'header.php';
if (!$loggedin) die();
$result = queryMysql("SELECT * FROM audit_requests");
$num_rows = $result->num_rows;
echo "<div class='main'><h3>$num_rows audit requests found!</h3>";
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
$requester = stripslashes($row['user']);
$audit_request_id = stripslashes($row['audit_request_id']);
echo <<<_END
<form method='post' action='audit_listings.php' enctype='multipart/form-data'>
<span class='text'><br>Audit request number</span>
<input disabled type='text' maxlength='10' name='audit_request_id' value='$audit_request_id'>
<span class='text'><br>Auditee name</span>
<input disabled type='text' maxlength='16' name='user' value='$requester'>
_END;
if (getCategory($user) == 'Auditor')
{
echo "<input type='submit' value='Apply for this audit request'>";
}
echo <<<_END
</form></div><br>
_END;
}
if (isset($_POST['audit_request_id']))
{
$audit_request_id = stripslashes('audit_request_id');
queryMysql("INSERT INTO audit_plan SELECT * FROM audit_requests WHERE audit_request_id='$audit_request_id'");
queryMysql("UPDATE audit_plan SET applicant='$user' WHERE audit_request_id='$audit_request_id'");
queryMysql("INSERT INTO messages VALUES('', 'TrustusChain', '$org_name', '$address', '', '$city'");
}
?>
You could add a hidden field to the form. Like:
echo "<input type=\"hidden\" value=\"form_xxx\">";
You can generate random id's to the form like
<form method="post" onsubmit="return myfunc(this.id)" id="From_php">
in javascript
<script>
function myfunc(id){
//do anything with id of form
}
</script>
You can pass ajax requests to server accordingly.
echo "<form action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\">";
if ($isAdmin === '1'){
echo "<input id=\"checkbox\" name=\"checkbox\" type=\"checkbox\" checked=\"checked\" value=\"1\" />";
} else {
echo "<input id=\"checkbox\" name=\"checkbox\" type=\"checkbox\" value=\"0\" />";
}
echo "<input type=\"submit\" name=\"formSubmit\" value=\"X\" />";
echo "</form>";
The above code is inside a while loop so it makes a form for each user. My php code looks like this:
$status = '0';
if (isset($_POST['checkbox']) && $_POST['checkbox'] == '1') {
$status = $_POST['checkbox'];
}
$stmt = $mysqli->prepare("UPDATE members SET isAdmin = ? WHERE id = \"$id\"");
$stmt->bind_param('s', $status);
$stmt->execute();
$stmt->close();
$mysqli->close();
Without actually submitting the form to the server, why does the admin user become a non-admin user just by refreshing the page?
UPDATED CODE:
?>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
<input type="checkbox" id="checkbox" name="checkbox" value="<?php echo ($checked)? '1' : '0'; ?>"<?php if($checked) echo ' checked="checked"'; ?> />
<input type="hidden" id="userid" name="userid" value="<? echo $members_row['id']; ?>" />
<input type="submit" id="submit" name="submit" value=">>" />
</form>
<?
$status = '0';
if (isset($_POST['checkbox']) && $_POST['checkbox'] == '1') {
$status = $_POST['checkbox'];
$id = $_POST['id'];
$stmt = $mysqli->prepare("UPDATE members SET isAdmin = ? WHERE id = \"$id\"");
$stmt->bind_param('s', $status);
$stmt->execute();
$stmt->close();
$mysqli->close();
}
Couple things, move your bracket to the end of the php snippet, and just check that the post is set but not that it equals anything. $status will be used to update it at the time of post. Side note, since the form is in a loop, id="checkbox" is going to be a problem when/if you use javascript. id="*" should to be unique in order to provide value. Finally, the origin of $id is unknown from the script provided, you will want to make sure you bind_param on that value as well (perhaps it should be provided by the post?). Not sure on the origin of that variable so hard to comment on that.
$checked = ($isAdmin == '1');
?>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
<input id="checkbox" name="checkbox" type="checkbox" value="<?php echo ($checked)? '1' : '0'; ?>"<?php if($checked) echo ' checked="checked"'; ?> />
<input type="submit" name="formSubmit" value="X" />
</form>
<?php //continue with loop
Presumably this is at the top since your forms reference PHP_SELF:
<?php
if (isset($_POST['checkbox'])) {
$status = $_POST['checkbox'];
// The $id variable is suspect here. Probably should be provided by the post?
$stmt = $mysqli->prepare("UPDATE members SET isAdmin = ? WHERE id = '$id'");
$stmt->bind_param('s', $status);
$stmt->execute();
$stmt->close();
$mysqli->close();
}
If I were doing this, I would either use a function or a class/method to make it more human-readable and reusable:
function updateUserRole($id,$status,$mysqli)
{
$stmt = $mysqli->prepare("UPDATE members SET isAdmin = ? WHERE id = ?");
$stmt->bind_param('si', $status,$id);
$stmt->execute();
$stmt->close();
}
// To execute, include the function
// then run the "if" condition
if (isset($_POST['checkbox']))
updateUserRole($_POST['id'],$_POST['checkbox'],$mysqli);
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 */
?>
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"]