I would like to delete a row from an MySQL database. The row that I'd like to delete is displayed in a box, with each being obtained via a loop and SELECT statement.
I've already got the rows in the database being displayed accordingly; however, I'd like a button that once pressed, would delete the selected option from the database.
Here is my current code:
<form action="" method="post">
<label>Patient Name:</label>
<br><br>
<select name="patient" id="patient">
<?php
$conn = new mysqli("localhost", "root", "", "as2");
$result = $conn->query("SELECT patientID, patientName, address FROM patient ORDER BY patientName ASC");
while ($row = $result->fetch_assoc()){
$patientName = $row['patientName'];
$address = $row['address'];
echo "<option value=\"patient\">" .$patientName. ", ".$address."</option>";
}
?>
</select>
<input type="submit" name="delete" value="Delete Record">
</form>
How would I go about making the "Delete Record" button delete the selected option from the database?
first record (patientID) in a string
$patientID = $row['patientID'];
then Add $patientIDto (option value) so it become :
echo "<option value=".$patientID.">" .$patientName. ", ".$address."</option>";
then add this code After everything (ofc outside the "while" loop) :
<?php
$selected_patient = $_POST['patient'];
if( $_SERVER['REQUEST_METHOD'] === 'POST'
&& isset($_POST['delete']) && isset($_POST['patient']) ) {
if( !empty($_POST['patient']) ){
$patient_ID = mysql_real_escape_string($selected_patient);
if ( $conn->query("DELETE FROM patient WHERE patientID={$patient_ID}") )
echo "user has been deleted successfully";
else
echo "Error deleting";
}
}
?>
now you'r good to go , after click delete button refresh your page and Boom! , the user will Disappears
and if you want a real time Action u can use (Ajax)
Try this
while ($row = $result->fetch_assoc()){
$patientName = $row['patientName'];
$address = $row['address'];
$patientID = $row['patientID']; //get patient id
echo "<option value=\"$patientID\">" .$patientName. ", ".$address."</option>"; // change in option value
}
Now on form submit, you will get patient id in $_POST['patient'] , can write your delete query.
Hope this will hope.
Related
I tried to build an admin page. The admin will fill a form to add new product in the database and display it in the shop website. The problem is when I tried to select a gender from the dropbox, the new product doesn't add in the product table in the database as you can see below: (I want to select gender such as Boys)
The Admin Page and database result:
The code I used:
$host = "";
$userMS = "";
$passwordMS = "";
$connection = mysql_connect($host,$userMS,$passwordMS) or die("Couldn't connect:".mysql_error());
$database = "projectDataBase";
$db = mysql_select_db($database,$connection) or die("Couldn't select database");
if (isset($_POST['sAddProduct']))
{
addNewProduct();
}else if(isset($_POST['delete']))
{
$Product_ID=$_POST['Product_ID'];
$mysqlquery="delete from Product where Product_ID= ".$Product_ID."";
mysql_query($mysqlquery);
echo "Deleted successfully";
echo("<FORM><INPUT Type='button' VALUE='Back' onClick='history.go(-1);return true;'></FORM>");
}else{
showForm();
}
// add new product
function addNewProduct()
{
$ProductName = $_POST['Product_Name'];
$ProductPrice = $_POST['Price'];
$Gender = $_POST['Gender_ID'];
//database query to add product
$insertStringProduct = "INSERT into Product(Product_Name, Price,Gender_ID)
VALUE('$ProductName', '$ProductPrice', '$Gender')";
$result = mysql_query($insertStringProduct);
echo ("<p1>Product added Successfully</p1>");
echo("<FORM><INPUT Type='button' VALUE='Back' onClick='history.go(-1);return true;'></FORM>");
}
//function for the form page
function showForm()
{
//First form for adding new product
$self = htmlentities($_SERVER['PHP_SELF']);
echo("<form action = '$self' method='POST'>
<fieldset>
<legend>Adding New Product</legend>
Product Name: <input name='Product_Name' type='text' size = '40'>
<br /><br />
Price: <input name='Price' type='text' size = '20'><br><br />
Gender:
<select name='Gender_Description'>
<option value = '%'> <-- select--></option>");
$dbQuary = " SELECT DISTINCT Gender_Description from Gender";
$result = mysql_query($dbQuary);
while($row = mysql_fetch_row($result)){
echo("<option value ='$row[0]'> $row[0]</option>");
}
echo("
</select>
<br/><br/>
<input type='submit' name='sAddProduct' value = 'Add'/>
<input type='reset' value='Clear' />
</fieldset>
</form>");
}
The result ( nothing added)
However, when I change the code to
Gender:
<select name='Gender_ID'>
<option value = '%'> <-- select--></option>");
$dbQuary = " SELECT DISTINCT Gender_ID from Gender";
$result = mysql_query($dbQuary);
It's working
Can anyone help me with this?
In addNewProduct you are expecting $_POST['Gender_ID'] to be set. So of course, <select name='Gender_Description'> would not work, because Gender_Description != Gender_ID. That's also why it does work when you change it.
I'm assuming what you want to achive is to display the gender description, and it still to work. For that, you need both the id and the description:
$dbQuary = " SELECT DISTINCT Gender_ID, Gender_Description from Gender";
$result = mysql_query($dbQuary);
while($row = mysql_fetch_row($result)){
echo("<option value ='$row[0]'> $row[1]</option>");
}
Security
Your code is extremely unsafe. You are using mysql_* which is deprecated since 2013, and you are not sanitizing the input in any way, so your code is open to SQL injection (which is possibly in all kinds of queries; insert, update, delete, etc, and allows for data leaks, DOS, and possibly code execution and deletion/changing of data). The preferred way to prevent this are prepared statements (either using mysqli_* or PDO). They are not difficult to use, and the resulting code is also nicer.
You are not concatenating values as it should
Change
echo("<option value ='$row[0]'> $row[0]</option>");
to
echo("<option value =". '$row[0]' . "> ". $row[0]. "</option>");
OR
echo("<option value ='{$row[0]}'> {$row[0]}</option>");
EDIT:
Change your While-loop
while($row = mysql_fetch_array($result,MYSQL_BOTH)) {
echo("<option value ='{$row['gender_id']}'> {$row['gender_description']}</option>");
}
This will generate a Select list showing the Gender Description and and values will be numeric(of database)
I am having a problem.
I am creating a script that allows a person to select a record by it's primary ID and then delete the row by clicking a confirmation button.
This is the code with the form:
"confirmdelete.php"
<?php
include("dbinfo.php");
$sel_record = $_POST[sel_record];
//SQL statement to select info where the ID is the same as what was just passed in
$sql = "SELECT * FROM contacts WHERE id = '$sel_record'";
//execute SELECT statement to get the result
$result = mysql_query($sql, $db) or die (mysql_error());//search dat db
if (!$result){// if a problem
echo 'something has gone wrong!';
}
else{
//loop through and get dem records
while($record = mysql_fetch_array($result)){
//assign values of fields to var names
$id = $record['ID'];
$email = $record['email'];
$first = $record['first'];
$last = $record['last'];
$status = $record['status'];
$image = $record['image'];
$filename = "images/$image";
}
$pageTitle = "Delete a Monkey";
include('header.php');
echo <<<HERE
Are you sure you want to delete this record?<br/>
It will be permanently removed:</br>
<img src="$filename" />
<ul>
<li>ID: $id</li>
<li>Name: $first $last</li>
<li>E-mail: $email</li>
<li>Status: $status</li>
</ul>
<p><br/>
<form method="post" action="reallydelete.php">
<input type="hidden" name="id" value="$id">
<input type="submit" name="reallydelete" value="really truly delete"/>
<input type="button" name="cancel" value="cancel" onClick="location.href='index.php'" /></a>
</p></form>
HERE;
}//close else
//when button is clicked takes user back to index
?>
and here is the reallydelete.php code it calls upon
<?php
include ("dbinfo.php");
$id = $_POST[id];//get value from confirmdelete.php and assign to ID
$sql = "SELECT * FROM contacts WHERE id = '$id'";//where primary key is equal to $id (or what was passed in)
$result=mysql_query($sql) or die (mysql_error());
//get values from DB and display from db before deleting it
while ($row=mysql_fetch_array($result)){
$id = $row["id"];
$email = $row["email"];
$first= $row["first"];
$last = $row["last"];
$status = $row["status"];
include ("header.php");
//displays here
echo "<p>$id, $first, $last, $email, $status has been deleted permanently</p>";
}
$sql="DELETE FROM contacts WHERE id = '$id'";
//actually deletes
$result = mysql_query($sql) or die (mysql_error());
?>
The problem is that it never actually ends up going into the "while" loop
The connection is absolutely fine.
Any help would be much appreciated.
1: It should not be $_POST[id]; it should be $_POST['id'];
Try after changing this.
if it does not still work try a var_dump() to your results to see if it is returning any rows.
if it is empty or no rows than it is absolutely normal that it is not working.
and make sure id is reaching to your php page properly.
Ok as you are just starting, take care of these syntax, and later try switching to PDO or mysqli_* instead of mysql..
Two major syntax error in your code:
Parameters must be written in ''
E.g:
$_POST['id'] and not $_POST[id]
Secondly you must use the connecting dots for echoing variables:
E.g:
echo "Nane:".$nane; or echo $name; but not echo "Name: $name";
Similarly in mysql_query
E.g:
$sql = "SELECT * FROM table_name WHERE id="'.$id.'";
I hope you get it..take care of these stuff..
I have a form that is dynamically created based off multiple mysql tables. This form sends to an external page for processing.
this means that my $_POST data will always be different. I need to extract the post array, strip it down and create a query.
here's the print_r of the Posted array:
Array ( [userid] => 1 [modid1] => on [fid1] => on [fid3] => on [fid5] => on [fid7] => on [fid8] => on [modid3] => on )
as you can see I have three parts to this userid, modid, and fid. the catch is, the only way I could pass the id's I need is to name the fields that. So each modid and fid are rows in the db. the number after that is the id that needs updating, and of course "on" is from the check box.
so end result would be something like:
to give a better idea here's how I would write the query normally
for modid1:
UPDATE table SET var = var WHERE modid = 1
for fid1
UPDATE table SET var = var WHERE fid = 1
heres the code that generated this array:
<form id="ajaxsubmit" method="post" action="modules/users/updaterights.php">
<?php
$modsql = mysql_query("SELECT * FROM modules")or die("Mod failed " .mysql_error());
while($row = mysql_fetch_array($modsql))
{
echo '<div class="rights">';
echo "<ul>";
$userid = safe($_POST['user']);
$id = $row['id'];
$sql = mysql_query("SELECT * FROM modpermissions WHERE userid = '$userid' AND modid = '$id'")or die("Mod died " .mysql_error());
$sql2 = mysql_fetch_array($sql);
$modper = $sql2['modpermission'];
if($modper == 1){
echo '<li><input type="checkbox" name="modid'.$row["id"].'" checked> <b>'.$row["name"].'</b></li>';
}
if($modper == 0){
echo '<li><input type="checkbox" name="modid'.$row["id"].'"> <b>'.$row["name"].'</b></li>';
}
if($row['features'] == 1)
{
echo "<ul>";
$sql = mysql_query("SELECT * FROM features WHERE modid = '$id'")or die("Features loop failed " .mysql_error());
while($row2 = mysql_fetch_array($sql))
{
$userid2 = safe($_POST['user']);
$id2 = $row2['id'];
$sql3 = mysql_query("SELECT * FROM fpermissions WHERE userid = '$userid2' AND fid = '$id2'")or die("features died " .mysql_error());
$sql4 = mysql_fetch_array($sql3);
$fper = $sql4['fpermission'];
if($fper == 1){
echo '<li><input type="checkbox" name="fid'.$row2["id"].'" checked> '.$row2['feature'].'</li>';
}
if($fper == 0){
echo '<li><input type="checkbox" name="fid'.$row2["id"].'"> '.$row2['feature'].'</li>';
}
}
echo "</ul>";
}
echo "</ul>";
echo '</div>';
}
?>
<p><input type="submit" id="submit" value="Submit" class="button"> <input type="reset" class="reset" value="Reset Form"> </p>
</form>
its a mess I know, im learning. If someone can understand my question and point me in the right direction to accomplish what Im attempting I would be grateful.
First thing to do is to store the old value as well as having the check box (using a hidden field).
I would also suggest as a minimum using a fixed character as a delimeter in your field names so you can explode the field name to easy get the part that is the id.
Also consider using joins rather than looping around one result, and for each one doing another query.
Your output script would look something like this:-
<form id="ajaxsubmit" method="post" action="modules/users/updaterights.php">
<?php
$userid = safe($_POST['user']);
$modsql = mysql_query("SELECT modules.id, modules.features, modules.name, modpermissions.modpermission
FROM modules
LEFT OUTER JOIN modpermissions
ON modules.id = modpermissions.modid
AND modpermissions.userid = '$userid'")or die("Mod failed " .mysql_error());
$PrevModuleId = 0;
while($row = mysql_fetch_array($modsql))
{
if ($PrevModuleId != $row['id'])
{
if ($PrevModuleId != 0)
{
echo "</ul>";
echo '</div>';
}
echo '<div class="rights">';
echo "<ul>";
$PrevModuleId = $row['id'];
}
echo '<li><input type="checkbox" name="modid_'.$row["id"].'" '.(($row['modpermission'] == 1) ? "checked='checked'" : "").'><input type="hidden" name="modid_old_'.$row["id"].'" value="'.$row['modpermission'].'"> <b>'.$row["name"].'</b></li>';
if($row['features'] == 1)
{
echo "<ul>";
$sql = mysql_query("SELECT features.id, features.feature, fpermissions.fpermission
FROM features
INNER JOIN fpermissions
ON features.id = fpermissions.fid
AND fpermissions.userid = $userid
WHERE modid = '$id'")or die("Features loop failed " .mysql_error());
while($row2 = mysql_fetch_array($sql))
{
echo '<li><input type="checkbox" name="fid_'.$row2["id"].'" '.(($row2['fpermission'] == 1) ? "checked='checked'" : "").'><input type="hidden" name="fid_old_'.$row2["id"].'" value="'.$row2['fpermission'].'"> '.$row2['feature'].'</li>';
}
echo "</ul>";
}
}
if ($PrevModuleId != 0)
{
echo "</ul>";
echo '</div>';
}
?>
<p><input type="submit" id="submit" value="Submit" class="button"> <input type="reset" class="reset" value="Reset Form"> </p>
</form>
You can then loop through each entry on the $_POST array, explode the key based on the _ character, check when the values have changed and if needs be do an update Or possibly you can use an INSERT instead, but using ON DUPLICATE KEY update type syntax (this way you can update many rows with different values easily).
Note you also need to put the userid value somewhere in your form (probably as another hidden field) so you have the value to process with the updates.
I have a php form with some textbox and checkboxes which is connected to a database
I want to enter all the details into the database from the form.All the textbox values are getting entered except the checkbox values.I have a single column in my table for entering the checkbox values and the column name is URLID.I want to enter all the selected checkbox(URLID)values to that single column only ,separated by commas.I have attached the codings used.can anyone find the error and correct me?
NOTE: (The URLID values in the form is brought from the previous php page.those codings are also included.need not care about it)
URLID[]:
<BR><?php
$query = "SELECT URLID FROM webmeasurements";
$result = mysql_query($query);
while($row = mysql_fetch_row($result))
{
$URLID = $row[0];
echo "<input type=\"checkbox\" name=\"checkbox_URLID[]\" value=\"$row[0]\" />$row[0]<br />";
$checkbox_values = implode(',', $_POST['checkbox_URLID[]']);
}
?>
$URLID='';
if(isset($_POST['URLID']))
{
foreach ($_POST['URLID'] as $statename)
{
$URLID=implode(',',$statename)
}
}
$q="insert into table (URLID) values ($URLID)";
You really should separate your model from the view. It's 2011, not 2004 ;o
if (isset($_POST['checkbox_URLID']))
{
// Notice the lack of '[]' here.
$checkbox_values = implode(',', $_POST['checkbox_URLID']);
}
$URLIDs = array();
while($row = mysql_fetch_row($result))
{
$URLIDs[] = $row[0];
}
foreach ($URLIDs as $id)
{
?>
<input type="checkbox" name="checkbox_URLID[]" value="<?php echo $id; ?>" /><?php echo $id; ?><br />
<?php
}
?>
<input type="submit"/>
using a drop-down list that's populated from database fields, i need to select an option and then delete that from the database. i'm trying to do this by sending the form to a process php page where i pull in the select option from the post array and then delete it from the database and return to the index page.
having issues with getting the array variable from the post array. can anyone help with some code on how to get the variable and then delete the mysql title
<form method="post" action="deleteReview_process.php">
<select name="title">
<?php
while($row = mysql_fetch_array($sql_result)) {
$movieTitle = $row['title'];
?>
<option><?php echo $movieTitle; ?></option>
<?php } ?>
</select>
<input type="submit" name="delete" id="delete" value="delete" />
---- and the process page ---
include 'inc/db.inc.php';
if($_POST['delete']) {
$title = $_POST['title'][$movieTitle]; <------ NOT WORKING
$sql = "DELETE" . $title . "FROM pageTitle";
mysql_query($sql, $conn)
or die("couldn't execute query");
header("Location: http://localhost/cms/index.php");
}
else
{
header("Location: http://localhost/cms/deleteReview.php");
}
Because your SELECT element is named "title," it will be represented as $_POST["title"] when it arrives to the backend script:
$title = $_POST['title'];
Also, your query needs to be corrected:
$sql = "DELETE" . $title . "FROM pageTitle";
Should be:
$sql = "DELETE FROM tableName WHERE title = '{$title}'";
$title is going to be in $_POST['title'] ie. $title = $_POST['title']