Delete query removes same records in any row - php

In my code, sql query deletes the record in table with same name. For example, I have 2 records with same name mani & mani. This code deletes 2 records.
form Code:
<form method="post" action="admin.php">
<h3>Delete a user</h3>
<select name="username">
<?php
$sql = mysqli_query($connection, "SELECT username FROM users");
while ($row = $sql->fetch_assoc()){?>
<option value="<?php echo $row['username']; ?>"><?php echo
$row['username']; ?></option>
<?php }?>
</select>
<input type="submit" name="delete" value="Delete User">
</form>
Sql
<?php
include('connect.php');
if(isset($_POST['delete'])) {
$username = $_POST['username'];
mysqli_query($connection, "DELETE FROM `users` WHERE `username` = '$username' ");
echo "User was deleted!";
}
?>

You need to select unique value such as ID in this case
Try this one:
<form method="post" action="admin.php">
<h3>Delete a user</h3>
<select name="username">
<?php
$sql = mysqli_query($connection, "SELECT username FROM users");
while ($row = $sql->fetch_assoc()){?>
<option value="<?php echo $row['user_id']; ?>"><?php echo
$row['username']; ?></option>
<?php }?>
</select>
<input type="submit" name="delete" value="Delete User">
</form>
SQL
<?php
include('connect.php');
if(isset($_POST['delete'])) {
$user_id = $_POST['user_id'];
mysqli_query($connection, "DELETE FROM `users` WHERE user_id = '$user_id' ");
echo "User was deleted!";
}
?>

Yes, your code will delete rows with matching names because you have Query :
DELETE FROM `users` WHERE `username` = '$username'
To delete specific row you need to use some unique value to refer the row, like primary key!
Say for example :
If a user has EmployeeId, CustomerId or StudentRollNo; you could use these options in where clause. These tips are very basic things in Query.

Related

Deleting data in database with dropdown menu in PHP

I am struggling with deleting data in my database with my drop-down menu.
My drop-down menu looks like this
<form method="post" action="admin.php">
<h3>Delete a user</h3>
<select name="username">
$sql = mysqli_query($connection, "SELECT username FROM users");
while ($row = $sql->fetch_assoc()){
?>
<option value="username" name="username">
<?php echo $row['username']; ?></option>
<?php } ?>
<input type="submit" name="delete" value="Delete User">
</form>
And this is displaying the users all good like i want it, so here is the php for it
<?php
include('connect.php');
if(isset($_POST['delete'])) {
$username = $_POST['username'];
mysqli_query("DELETE FROM `users` WHERE `username` = '$username' ");
echo "User was deleted!";
}
?>
So when i hit the submit button "Delete User", it looks like i get sent to admin.php and nothing happens.
How can i fix this?
Thanks.
Replace name="username" from <option></option>
Echo value in value of option.
Connection variable missing in admin.php page
Updated Code
<select name="username">
<?php
$sql = mysqli_query($connection, "SELECT username FROM users");
while ($row = $sql->fetch_assoc()){?>
<option value="<?php echo $row['username']; ?>"><?php echo $row['username']; ?></option>
<?php }?>
</select>
admin.php
$stmt = $connection->prepare("DELETE FROM `users` WHERE `username` = ?");
$stmt->bind_param('s', $username);
$stmt->execute();
1.<option value="username" name="username"> Need to be <option value="<?php echo $row['username']; ?>">
2.Connection variable is missing . Need to be:-
mysqli_query($connection,"DELETE FROM `users` WHERE `username` = '$username' ");
Modified code need to be:-
Form code:-
<?php
//comment these two lines when code started working fine
error_reporting(E_ALL);
ini_set('display_errors',1);
include('connect.php');
?>
<form method="post" action="admin.php">
<h3>Delete a user</h3>
<select name="username">
<?php
$sql = mysqli_query($connection, "SELECT username FROM users");
while ($row = mysqli_fetch_assoc($sql)){?>
<option value="<?php echo $row['username']; ?>"><?php echo $row['username']; ?></option>
<?php }?>
</select>
<input type="submit" name="delete" value="Delete User">
</form>
Php code:-
<?php
//comment these two lines when code started working fine
error_reporting(E_ALL);
ini_set('display_errors',1);
include('connect.php');
if(isset($_POST['delete'])) {
$username = $_POST['username'];
if(mysqli_query($connection,"DELETE FROM `users` WHERE `username` = '$username' ")){
echo "User was deleted!";
}
}
?>
Note:- Always do some error-reporting so that you will get error and rectify that.
Your query is vulnerable to SQL INJECTION so read about prepared statements and use them.
Change
<option value="username" name="username">
<?php echo $row['username']; ?></option>
To
<option value="<?php echo $row['username'] ?>" name="username">
<?php echo $row['username']; ?></option>
You are not putting the value in select option that's why nothing happens
Just replace
<option value="username" name="username">
<?php echo $row['username']; ?></option>
<?php } ?>
with
<option value="<?php echo $row['username']; ?>">
<?php echo $row['username']; ?></option>
<?php } ?>
It will work for you.

Checkbox in a while loop php

I have a check box inside a while loop like this:
<form method="POST">
<?php $sql= mysql_query("SELECT * FROM names WHERE `id` ='$id' ");
while ($get = mysql_fetch_array($sql)){ ?>
<input type="checkbox" name="id_names" value="<? echo $get ['id'];?>"><?php echo $get ['name']; ?>
<?php } ?>
<input id="submitbtn" type="submit" value="Submit" /><br><br>
</form>
The problem is at this part I am unable to get specific checkbox properties and even if the user selects two check boxes I am unable to echo the id out
<?php
if(isset($_POST['id_names']))
{
$id_names= $_POST['id_names'];
$email = mysql_query("SELECT `email` FROM users WHERE `id` = '$id_names' ");
while ($getemail = mysql_fetch_array($email))
{
echo $getemail['email'];
}
}
?>
I have tried searching for answers but I am unable to understand them. Is there a simple way to do this?
The form name name="id_names" needs to be an array to allow the parameter to carry more than one value: name="id_names[]".
$_POST['id_names'] will now be an array of all the posted values.
Here your input field is multiple so you have to use name attribute as a array:
FYI: You are using mysql that is deprecated you should use mysqli/pdo.
<form method="POST" action="test.php">
<?php $sql= mysql_query("SELECT * FROM names WHERE `id` =$id ");
while ($get = mysql_fetch_array($sql)){ ?>
<input type="checkbox" name="id_names[]" value="<?php echo $get['id'];?>"><?php echo $get['name']; ?>
<input type="checkbox" name="id_names[]" value="<?php echo $get['id'];?>"><?php echo $get['name']; ?>
<?php } ?>
<input id="submitbtn" type="submit" value="Submit" /><br><br>
</form>
Form action: test.php (If your query is okay.)
<?php
if(isset($_POST['id_names'])){
foreach ($_POST['id_names'] as $id) {
$email = mysql_query("SELECT `email` FROM users WHERE `id` = $id");
$getemail = mysql_fetch_array($email); //Here always data will single so no need while loop
print_r($getemail);
}
}
?>

How to pass table id to another table in PHP

There are 02 tables called item and customer.
item(item_id, item_name)
customer(cus_id, iid, cus_name)
I just tried to store item_id from item to the iid in the customer.
but it always showing null values.
My database is item_sales.
Here is my PHP code
<html>
<title></title>
<head></head>
<body>
<?php
$hostname = "localhost";
$database = "item_sales";
$username = "root";
$password = "";
$con = mysql_pconnect($hostname, $username, $password);
error_reporting(0);
?>
<form action="index.php" method="post" enctype="multipart/form-data">
<p>Customer Name : <input type="text" name="cus_name" /><br/><br/> </p>
<p>Select an Item:
<select name="iid">
<?php
$sql = mysql_query("SELECT * FROM item");
mysql_select_db($database,$con);
while($sqlv = mysql_fetch_array($sql))
{ ?>
<option id="<?php echo $sqlv['item_id']; ?>"><?php echo $sqlv['item_name']; ?></option>
<?php } ?>
</select>
</p>
<?php
if(isset($_POST['submit']))
{
$sql2 = "SELECT * FROM item WHERE iid='%item_id%'";
mysql_select_db($database,$con);
$mydata = mysql_query($sql2);
$cus_name = $_POST['cus_name'];
$sql3 = "INSERT INTO customer (cus_id, iid, cus_name) VALUES ('', '$_POST[iid]', '$cus_name')";
mysql_query($sql3);
}
?>
<input type="submit" name="submit" value="Add Sale" />
</form>
</body>
</html>
The reason it is not working is that you are attempting to save the iid select into the iid field, and I'm guessing the iid field in customer is a numeric type field, like INT - using the POST variable like this, you are going to be saving the text of the SELECT rather than the val.
What you need to do to fix this particular problem is set a "value" on each of the select options. You've set an ID but thats no real help here.
<select name="iid">
<?php
$sql = mysql_query("SELECT * FROM item");
mysql_select_db($database,$con);
while($sqlv = mysql_fetch_array($sql))
{ ?>
<option value="<?php echo $sqlv['item_id']; ?>"><?php echo $sqlv['item_name']; ?></option>
<?php } ?>
</select>
This is besides the point your code is very dangerous. I would recommend you do not use the original mysql functions as, 1) they don't offer any real protection from malicious users, and 2) they will be removed from PHP support very soon.
See this SO article on how to replace the mysql functionality from your PHP code : How can I prevent SQL injection in PHP?
That article also might help you understand the dangers your code offers.
The correct code is following :
<html>
<title></title>
<head></head>
<body>
<?php
$hostname = "localhost";
$database = "item_sales";
$username = "root";
$password = "";
$con = mysql_pconnect($hostname, $username, $password);
error_reporting(0);
?>
<form action="index.php" method="post" enctype="multipart/form-data">
<p>Customer Name : <input type="text" name="cus_name" /><br/><br/> </p>
<p>Select an Item:
<select name="iid">
<?php
$sql = mysql_query("SELECT * FROM item");
mysql_select_db($database,$con);
while($sqlv = mysql_fetch_array($sql))
{ ?>
<option value="<?php echo $sqlv['item_id']; ?>"><?php echo $sqlv['item_name']; ?></option>
<?php } ?>
</select>
</p>
<?php
if(isset($_POST['submit']))
{
$sql2 = "SELECT * FROM item";
mysql_select_db($database,$con);
$mydata = mysql_query($sql2);
$cus_name = $_POST['cus_name'];
$iid = $_GET['item_id'];
$sql3 = "INSERT INTO customer (cus_id, iid, cus_name) VALUES ('', '$_POST[iid]', '$cus_name')";
mysql_query($sql3);
}
?>
<input type="submit" name="submit" value="Add Sale" />
</form>
</body>
</html>

Update a MySQL Database with a Form

I'm trying to create a form that allows a user to select a field from a drop down box and then change what is currently written in the field.
My current code allows me to view the drop down list select the field I want to change and then enter my new text into a box. But when I click update, nothing happens.
<?php
mysql_connect("", "", "") or die(mysql_error());
mysql_select_db("") or die(mysql_error());
$query = "SELECT * FROM news_updates";
$result=mysql_query($query) or die("Query Failed : ".mysql_error());
$i=0;
while($rows=mysql_fetch_array($result))
{
$roll[$i]=$rows['Text'];
$i++;
}
$total_elmt=count($roll);
?>
---------------------------------------------------------Now I have the form
<form method="POST" action="">
Select the news post to Update: <select name="sel">
<option>Select</option>
<?php
for($j=0;$j<$total_elmt;$j++)
{
?><option><?php
echo $roll[$j];
?></option><?php
}
?>
</select><br />
Text Field: <input name="username" type="text" /><br />
<input name="submit" type="submit" value="Update"/><br />
<input name="reset" type="reset" value="Reset"/>
</form>
-----------------------------------------------Now I have the update php
<?php
if(isset($_POST['submit']))
{
$username=$_POST['username'];
$query2 = "UPDATE news_updates SET username='$username' WHERE rollno='$value'";
$result2=mysql_query($query2) or die("Query Failed : ".mysql_error());
echo "Successfully Updated";
}
?>
Well, you seem to be missing the $value part. Something like this should do, for the last part:
<?php
if(isset($_POST['submit']))
{
$username = mysql_real_escape_string($_POST['username']);
$value = mysql_real_escape_string($_POST['sel']);
$query2 = "UPDATE news_updates SET username='$username' WHERE rollno='$value'";
echo $query2; //For test, to see what is generated, and sent to database
$result2=mysql_query($query2) or die("Query Failed : ".mysql_error());
echo "Successfully Updated";
}
?>
Also, you should not use mysql_* functions as they are deprecated. You should switch to mysqli or PDO.
First, try adding a value to your options, like so:
for($j=0;$j<$total_elmt;$j++)
{
?>
<option value="<?php echo $roll['id']; ?>"><?php echo $roll['option_name']; ?></option>
<?php
}
Then, when you parse your file, go like so:
$value = $_POST['sel']; // add any desired security here
That should do it for you
You need to change this
<?php
for($j=0;$j<$total_elmt;$j++)
{
?><option><?php
echo $roll[$j];
?></option><?php
}
to this
<?php
for($j=0;$j<$total_elmt;$j++)
{
?><option value="<?php echo $roll[$j];?>"> <?php echo $roll[$j];?></option> <?php
}
And you also need to change the update query from this
$query2 = "UPDATE news_updates SET username='$username' WHERE rollno='$value'";
to this
$query2 = "UPDATE news_updates SET username='$username' WHERE rollno='".$_POST['sel']."'";
N. B.: Here I am assuming that $_POST['sel'] has the value selected by the user from the drop down menu because I could not find anything which corresponds to $value

using multi where when select items from database

I want to selected items from mytable when using three tables and &_GET another id to open in this page so i want to use where and where to complete fetch my data by using two roles .
<?php
$sel = "SELECT * FROM `informations` where `cate_id` =".$_GET['info_id'];
$done = mysql_query($sel);
?>
<form action="" method="post" enctype="multipart/form-data">
<label for="location"></label>
<select name="location" id="location"><?php
$sel_cate = "SELECT * FROM locations";
$done_cate = mysql_query($sel_cate);
while($get_cate = mysql_fetch_array($done_cate)){
echo '<option value="'.$get_cate['id'].'">'.$get_cate['location'].'</option>';
$loc=$get_cate['id'];
}
?>
</select>
<input type="submit" name="go" id="go" value="Go">
<input type="submit" name="all" id="all" value="Show All...">
</form>
<?php
if(isset($_POST['go'])){
$sel ='SELECT * FROM `pharmacies` WHERE `cate_id` ="'.$_GET['info_id'].'" || `location_id` = "'.$_POST['location'].'"';
?>
I tried this code and when isset($_POST['go']) variable $sel got $_GET['info_id'] and $_POST['location'] values. Query generated without errors, and must fetch information.
I not see mysql_query in your: if(isset($_POST['go'])). Maybe you forget query:
if(isset($_POST['go']))
{
$sel = 'SELECT * FROM `pharmacies` WHERE `cate_id` ="'.addslashes($_GET['info_id']).'" or `location_id` = "'.addslashes($_POST['location']).'"';
$selRslt = mysql_query($sel);
while($row = mysql_fetch_array($selRslt))
{
var_dump($row);
}
}

Categories