PHP SEARCH and DELETE - php

I've changed the code following people advices but my delete button doesn't work. The empID is a VARCHAR, not an INT
The way i wanted it to be done when i search a string of letters i would get a list of employees containing that string, then choose some checkboxes and when button is pressed they'd get deleted from the DB and the list of not chosen would still stay on that page.
Thanks in advance for any help!!!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Delete Record</title>
<link rel="stylesheet" href="style1.css" />
<style>dialog{margin-left:100px}
select { font-size:24px;}</style>
</head>
<body>
<div class="header">
<h2>List of the employees with the name entered</h2>
</div>
<form name="action_form" action="" method="post" />
<div class="input-group">
<input type="text" name="name" placeholder="Employee name" />
</div>
<button type="submit" class="btn" name="submit">SEARCH</button>
<?php
require('db.php');
$errors = array();
if(isset($_POST["name"])&&!empty($_POST["name"]))
{
$name=$_POST['name'];
$sqlResult=mysqli_query($con, "SELECT * FROM Employee WHERE empName LIKE '%$name%'");
if (mysqli_num_rows($sqlResult) > 0)
{
echo "<table>";
while($row=mysqli_fetch_assoc($sqlResult))
{
echo "<tr>";
echo "<td>"; ?><input type= 'checkbox' name='num[]' value='<?php echo $row['empID'] ?>'/><?php echo "</td>";
echo "<td>".$row['empID']."</td>";
echo "<td>".$row['empName']."</td>";
echo "<td>".$row['deptNo']."</td>";
echo "<td>".$row['addCounty']."</td>";
echo "<td>".$row['salary']."</td>";
echo "</tr>";
}
echo "</table>";
}
if(isset($_POST['delete'])&&(!empty($_POST['num'])))
{
$list = array();
$list = $_REQUEST['num'];
foreach($list as $delID)
{
$sqlResult = mysqli_query($con,"DELETE FROM employee WHERE empID LIKE '$delID'");
}
}
}
?>
<div class="input-group">
<label>Please choose the person from the list below</label>
</div>
<div class="input-group">
<button type="submit" class="btn" name="delete">FIRE SELECTED</button><br><br>
<button type="reset" class="btn" name="reset">RESET</button><br><br>
Back to the Menu
</div>
</form>
</body>
</html>

Try this :
if(isset($_POST["name"])&&!empty($_POST["name"]))
{
$name=$_POST['name'];
$sqlResult=mysqli_query($con, "SELECT * FROM Employee WHERE empName
LIKE '%$name%'")
}

The reason for the error (Undefined variable $name) is because you are only setting $name in your "if" statement when $_POST['name'] is set, but you are running the line:
$sqlResult = mysqli_query($con, "SELECT * FROM Employee WHERE empName LIKE '%$name%'");
every time the page is loaded. Because you have used $name in the SQL string, but it isn't always declared, you get the error.
I'm finding your code a little hard to read, but I think you probably just want to put the mysqli_query() line inside the "if" statement.
if(isset($_POST['name'] && !empty($_POST['name'])) {
$name = $_POST['name'];
$sqlResult = mysqli_query($con, "SELECT * FROM Employee WHERE empName LIKE '%$name%'");
}

Looks like you should wrap the $delId in "%"
So your delete query should look like this:
$sqlResult = mysqli_query($con,"DELETE FROM employee WHERE empID LIKE '%$delID%'")
Also bear in mind that the like statement will delete any row where the id is like any other id. You might consider changing this to:
$sqlResult = mysqli_query($con,"DELETE FROM employee WHERE empID = '$delID' ")
Another thing to keep in mind is that you should consider using parameterized queries to prevent sql injection. Read thise for more details:
What is parameterized query?

Related

Why is the last iteration given, instead of the current one?

I have some PHP & HTML code which fetches id's, names & statuses from a mysql database.
Using buttons and $_POST i'm attempting to update the MYSQL database when said the users button is clicked (it's a simple in/out board)
Here is my code
<?php
include 'confile.php';
if(isset($_POST['update'])) {
echo $_POST['update']. " "; //test to show correct name
echo $_POST['staffid']; //test to show the correct staffid << **THIS IS WHERE THE ISSUE IS**
//$incid = $_POST['staffid'];
//$sql = "SELECT status FROM staff WHERE id=$incid";
//$result = $conn->query($sql);
//echo $result; //show the status
} else {
//do nothing.
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<title>Staff Board</title>
<body>
<div align="center" class="header">
<div class="header text">
<h1>Staff Board</h1>
</div>
<div class="header logo">
<img src="/assets/img/logo.gif" width="64px" height="64px">
</div>
</div>
<div id="conbox" align="center" class="content">
<hr>
<?php
//get all staff and their statuses
$sql = "SELECT id, firstname, surname, status FROM $staff ORDER BY surname ASC";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
// assign results to values
$id = $row["id"];
$firstname = $row["firstname"];
$surname = $row["surname"];
$status = $row["status"];
$fullname = $firstname . " " . $surname . " " . $id; //The $id variable will be dropped from here... it's just for testing. note, it works here, the correct ID is added to the button value
if ($status == 1) { //pick the correct color for the status
$color = "butGreen";
} else {
$color = "butRed";
}
?>
<form class="staffGrid" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
<input type="hidden" id="staffid" name="staffid" value="<?php echo htmlspecialchars($id); ?>"/> <!-- hidden input to pass the id to $_POST -->
<input type="submit" id="update" name="update" value="<?php echo htmlspecialchars($fullname); ?>"/> <!-- submit button to trigger POST -->
</form> <!-- added as per devpro & billyonecan -->
<?php
};
?>
</div>
</div>
</body>
</html>
When I first load the page, the buttons show correctly, and there is no test output at the top of the page, which I expect.
however, when I click a button, the page refreshes correctly, and shows the correct name for the button being pushed (from the echo on line 5), but the wrong staffid is given. It gives the LAST id for the while loop, instead of correct value for that button.
I had assumed that for each iteration, the values would be set for that specific element (the button)... obviously i'm incorrect here.
Why is this happening and how do I fix it?
Additional info
Confile.php has the following variables used in the code:-
$conn = new mysqli($server, $username, $password);
$staff = [Location of db table]
some output :-
echo $sql;
SELECT id, firstname, surname, status FROM inout.staff ORDER BY surname ASC
echo print_r($_POST);
Array ( [staffid] => 17 [update] => First Second 8 )
The solution was to ensure that the closing tag was present in the code, and in the correct location to prevent erroneous iteration!

duplicate messages after clicking comment button

update
Can anyone explain to me why I am getting duplicate messages instead of one?
how can I change my code so that when I type a comment and press "Comment" button, it will only display one message instead of duplicates! When I have one comment boxes it doesn't show duplicate comments, but if I have more than one then it starts duplicating!
COMMENT.INC.PHP
include 'cdbh.inc.php';
function setComments($con)
{
if (isset($_POST['commentSubmit'])) {
$uid = mysqli_real_escape_string($con,$_POST['uid']);
$date = mysqli_real_escape_string($con,$_POST['date']);
$message = mysqli_real_escape_string($con,$_POST['message']);
$sql = "INSERT INTO comments (uid, date, message) VALUES ('$uid','$date','$message')";
$result = mysqli_query($con,$sql);
}
}
function getComments($con)
{
$sql = "SELECT * FROM comments";
$result = mysqli_query($con,$sql);
while ($row=mysqli_fetch_assoc($result)) {
echo $row['uid'];
echo ":";
echo $row['message']."<br><br>";
}
}
page code
<?php
date_default_timezone_set('America/Los_Angeles');
include 'comment.inc.php';
include("connection.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="comment.css" rel ="stylesheet">
</head>
<body>
<?php
$sql="Select * from tbl_images";
$result=mysqli_query($connection,$sql);
while ($row=mysqli_fetch_array($result)) {
?>
<img src="images/<?php echo $row['images_name'] ?>" width="200px" height="200px">
<?php
echo "<form method ='POST' action ='".setComments($con)."'>
<input type ='hidden' name ='uid' value='unknown'>
<input type ='hidden' name ='date' value='".date('Y-m-d H:i:s')."'>
<textarea name='message'></textarea>
<button type ='submit' name='commentSubmit'>Comment</button>
</form>";
}
getComments($con);
?>
</body>
</html>
Maybe you are submiting all your forms instead of one..
check your database in order to know from what img comes each message.
If you have other code like javascript, you should post it.

Data not fetched from MySQL table in PHP

I want to print the name and last name of an ID entered in the text box. Here is the PHP and HTML code:
<head>
<title>
Search your name by ID
</title>
</head>
<?php
if(isset($_POST["searchname"]))
{
$id = $_POST["searchname"];
$connect = new mysqli("localhost","adarsh","Yeah!","adarsh");
$a = mysql_query("Select * from users where id='$id'",$connect);
$row = mysql_fetch_assoc($a);
echo "$row[0] , $row[1] , $row[2]";
}
else
{
echo "error";
}
?>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" maxlength="6" name="searchname">
<input type="Submit" name="Submit">
</form>
</body>
Output when I enter ID:
, ,
There are entries in the MySQL table but I am unable to fetch them. What is wrong with my code?
UPDATE: I have also tried mysql_fetch_array but it is not working.
Main problem is that you're miximg mysqli and mysql. These are absolutely different APIs.
Assuming you have
$id = $_POST["searchname"];
$connect = new mysqli("localhost","adarsh","Yeah!","adarsh");
Next you should:
$result = $connect->query("Select * from users where id='$id'");
Then get results:
while ($row = $result->fetch_assoc()) {
var_dump($row);
}
And of course, instead of directly putting values into your query use prepared statements.
Update:
about mistakes:
Your main mistake is mixing apis. When you use mysql (which is deprecated and you mustn't use it anymore) you can't use any of mysqli functions and vice versa.
Next - as you create mysqli object with new, you should work in object-oriented style, i.e. calling methods from your mysqli object.
Try this:
<html>
<head>
<title>
Search your name by ID
</title>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" maxlength="6" name="searchname">
<input type="Submit" name="Submit">
</form>
</body>
</html>
<?php
if(isset($_POST["searchname"])){
$id = $_POST["searchname"];
$connect = mysql_connect("localhost","adarsh","Yeah!","adarsh");
$result = mysql_query("Select * from users where id='$id'",$connect);
$row = mysql_fetch_assoc($result);
print_R($row);
}else{
echo "there is something wrong";
}

Deleting something in a mysqli database with a button?

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 */
?>

Show phpmyadmin cell in html textbox value

I have a database in phpmyadmin called fleet hire motors, and in that database is a table called customer.
In that table are columns called customerID and Surname. I have already done some coding on one page that lets the user select the customerID to edit the Surname.
On the next page I want a textbox. in that textbox, the default value should be what the current Surname is.
So, if i was to edit customer with customerID 1 (of which surname is currently Brown and I want to change to Green) the second page would show Surname: [Brown], where [] encloses a textbox.
I currently do not have any code, and would like to keep it primarily php. The first page is called editcustomer.php, and the second is called editcustomer2.php.
Any help is appreciated.
My current code is:
<html> <head> <title>Edit Customer</title> </head><body>
<?php mysql_connect("localhost","username","password") or die(mysql_error());
mysql_select_db("fleet hire motors") or die(mysql_error()); ?>
<?php
$CustomerID = $_GET["CustomerID"];
$query=mysql_query(" SELECT * FROM customer WHERE CustomerID = '$CustomerID' ") or die(mysql_error());
while ($row = mysql_fetch_array($query)) {
b$CustomerID = $row["CustomerID"];
} ?>
First Name: <input name="FirstName" type="text" value="
<?php
$FirstName = $_GET["CustomerID"];
include 'db.php';
$query=mysql_query(" SELECT FirstName FROM customer WHERE CustomerID = '$CustomerID' ") or die(mysql_error());
?> ">
<br> <input name="submitbtn" type="submit" value="Save"> <input name="resubmitbtn" type="submit" value="Reset"> </form> </body> </html>
Sorry for all the edits, as I am new to stackoverflow and just learning how to do it.
I have now updated my coding thanks to a response, but it is still not working. My most current coding is:
<html>
<head>
<title>Edit Customer</title>
</head>
<body>
<?php
mysql_connect("localhost","username","password") or die(mysql_error());
mysql_select_db("fleet hire motors") or die(mysql_error());
?>
<?php
$CustomerID = $_GET["CustomerID"];
$query=mysql_query(" SELECT * FROM customer WHERE CustomerID = '$CustomerID' ") or die(mysql_error());
$row = mysql_fetch_array($query);
if (!$row || !is_array($row)){
$CustomerID = 0;
$CustomerFirstName = '';
}
else {
$CustomerID = $row["CustomerID"];
$CustomerFirstName = $row['FirstName'];
}
?>
First Name: <input name="FirstName" type="text" value="<?php echo $CustomerFirstName; ? >">
<input name="submitbtn" type="submit" value="Save">
<input name="resubmitbtn" type="submit" value="Reset">
</form>
</body>
</html>
This does not give me anything in the textbox, and my submit button does not work.
You'll have to make an echo.
In case that your customerId shall be unique you did not need a while.
[...]
<?php
$CustomerID = $_GET["CustomerID"];
$query=mysql_query(" SELECT * FROM customer WHERE CustomerID = '$CustomerID' ") or die(mysql_error());
$row = mysql_fetch_array($query));
if (!$row || !is_array($row)){
$CustomerID = 0;
$CustomerFirstName = 'NoNameFound';
}
else {
$CustomerID = $row["CustomerID"];
$CustomerFirstName = $row['FirstName'];
}
//Debug
echo 'rowcontent: <pre>' . print_r($row, true) . '</pre>';
?>
First Name: <input name="FirstName" type="text" value="<?php
echo $CustomerFirstName;
?>">
[...]
You should also do some validation on your GET and POST before using them in your database e.g.
is_numeric($CustomerId)
or something like
[...] WHERE MD5(CustomerId) = ' . md5($CustomerId) . ' [...]

Categories