I'm trying to delete a row in an SQL database by an id. I have found questions here related to this but nothing seems to work, perhaps because my page is populated (dynamically?) based on selecting a variable. The rows are displayed on my page based on a dropdown (locationlab) and I have a delete button after each row. It looks like this.
I have the Id displayed temporarily at the end of the row just be sure that the code sees the variable (& it does!).
The code to populate the page looks like this:
<?php
$locationlab = $_POST[locationlab];
$sql = "SELECT * FROM lab WHERE locationlab LIKE '{$locationlab}'";
echo($locationlab);
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo'
<table>
<form action=testpage2.php method=post>
<td width="10%"><input type=text name=make value='. $row["make"].'></td>
<td width="10%"><input type=text name=model value='. $row["model"].'></td>
<td width="20%"><input type=text name=hostname value='. $row["hostname"].'></td>
<td width="15%"><input type=text name=ipaddress value='. $row["ipaddress"].'></td>
<td width="20%"><input type=text name=ipmiipaddress value='. $row["ipmiipaddress"].'></td>
<td width="15%"><input type=text name=terminalserveraddress value='. $row["terminalserveraddress"].'></td>
<td width="10%"><input type=text name=locationlab value='. $row["locationlab"].'></td>
<td><input type=submit name=update value=update></td>
<td><input type=submit name=delete value=delete></td>
<td id=id name=id value='. $row["id"].'>'. $row["id"].'</td>
</table>
</form>';
}}
?>
I can input the SQL query below manually in the phpMyAdmin page so I know it is correct.
The code for the Delete button looks like this:
<?php
if(isset($_POST['delete'])) {
$deletequery = ("DELETE * FROM lab WHERE ='$_POST[id]'");
mysql_query($deletequery, $conn);
};
?>
When I click the delete button it appears to refresh the page but nothing changes. I imagine that if I can get the delete button working, the update will work in a similar fashion but for now I'm stumped.
<?php
if(isset($_POST['delete'])) {
$deletequery = ("DELETE FROM lab WHERE **columnName** ='$_POST[id]'");
mysql_query($deletequery, $conn);
}
?>
You are missing column name in query. Also there is no * in DELETE statement, because deleting means deleting row.
First of all let me help you in formatting the code
you should not write entire HTML code in echo...
instead try this one....
<?php
while($row = $result->fetch_assoc()) {
?>
<table>
<form action="testpage2.php" method="pos">
<td width="10%"><input type="text" name="make" value="<?= $row["make"] ?>"></td>
....
....
</table>
</form>
<?php
}
?>
also you should use mysqli instead of mysql
and your database query is also incorrect, it must be like this..
DELETE FROM lab WHERE id ='$_POST[id]'
if you use mysqli then you can also use some functions like this..
mysqli_query($con,$deletequery)
if(mysqli_errno($con))
{
echo("SOme error while executing query : ".mysqli_error($con));
}
Related
code:
<?php
if(isset($_POST['save']))
{
$comment1 = $_POST['comment2'].",".date('Y-m-d');
$comment2 = $_POST['comment2'];
$id = $_POST['id'];
$query = "update enquires2 set comment1 = '$comment1', comment2 = '$comment2', s_date = '$s_datee' where id='$id'";
$result = mysqli_query($link,$query);
if($result==true)
{
echo "successfull";
}
else
{
echo "error!";
}
}
?>
<form method="post" name="myform">
<table>
<tr>
<th>comment1</th>
<th>comment2</th>
<th>Action</th>
</tr>
<?php
$sql = "select * from enquires2 ";
$result = mysqli_query($link,$sql);
while ($row = mysqli_fetch_array($result))
{
?>
<tr>
<td>
<input type='hidden' name='id' value='<?php echo $row['id']; ?>'>
</td>
<td>
<?php echo $row['comment1']; ?>
</td>
<td>
<input type='text' name='comment2' id='comment2' value=""/>
</td>
<td>
<input type ='submit' name='save' id='save' value='Save' />
</td>
</tr>
<?php
}
?>
</table>
</form>
In this code I want to update table enquires2 with unique id. In following image you see that table row having save button this is only one row similarly it have multiple row which having save button in each row. Now I want that when I click on save button of particular row only that row data will be update. How can I fix this problem ? Please help.
Thank You
You could use AJAX and jQuery to do this and send the data to a separate PHP file and assigning the $row['ID'] to a data-value attribute of the button,
$("#save-btn").click(function(){
id = $(this).attr(data-value);
***** rest of values here
$.ajax({
method: "GET",
data: {id: id, rest of: data here},
url: phpfile.php,
success: function(){
console.log("Success");
}
})
});
While in the PHP file you would take get the id like,
$_GET['id'], and same with the other values since we are using the GET method and then put them in the update query.
First of all, for security reason you need to change this query to a prepared statement see PHP MySQLI Prevent SQL Injection:
$id = $_POST['id'];
$query = "update enquires2 set comment1 = '$comment1', comment2 = $comment2', s_date = '$s_datee' where id='$id'";
$result = mysqli_query($link,$query);
This line is bad anyway, you are missing a opening quote for $comment2.
$query = "update enquires2 set comment1 = '$comment1', comment2 = $comment2', s_date = '$s_datee' where id='$id'";
Are you sure $link is an actual mysqli link?
As for the html part, you need to mkae one form for each record. See the link posted HTML: Is it possible to have a FORM tag in each TABLE ROW in a XHTML valid way?
alternatively you could do something bad like only adding the $id to evry field for every row (similar to:)
<input type ='submit' name='save[<?=$id;?>]' id='save' value='Save' />
and in the php code check witch key is set.
if(isset($_POST['save']) && is_array($_POST['save'])){
$id=key($_POST['save']);
}
You will need to replicate the bad thing for your comments as well but as a proof of concept you can run this snippet on phpfiddle.org
<?php
print_r($_POST);
if(isset($_POST['save']) && is_array($_POST['save'])){
echo key($_POST['save']);
}
?>
<html>
<form method='post'>
<input type='submit' name='save[1]' value='1' />
<input type='submit' name='save[2]' value='2' />
</form>
</html>
Wish i could provide you a really full answer but there's alot of work to be done on your code for it to be 'proper coding'. Again this becaome a matter of opinion beside the fact that your code is vunerable to sql injection and is NOT accepable.
Don't use your code at all for security vulnerability. Read more about sql injection Here. After all, For each row () create a form with a hidden input storing id of row .
I revised my code to make it work,create a nested table inside your td, so that tag will be accepted,
also see this link for a working reference,
HTML: Is it possible to have a FORM tag in each TABLE ROW in a XHTML valid way?
<?php
if(isset($_POST['save']))
{
$comment1 = $_POST['comment2'].",".date('Y-m-d');
$comment2 = $_POST['comment2'];
$id = $_POST['id'];
$query = "update enquires2 set comment1 = '$comment1', comment2 = '$comment2', s_date = '$s_datee' where id='$id'";
$result = mysqli_query($link,$query);
if($result==true)
{
echo "successfull";
}
else
{
echo "error!";
}
}
?>
<table>
<tr>
<th>comment1</th>
<th>comment2</th>
<th>Action</th>
</tr>
<?php
$sql = "select * from enquires2 ";
$result = mysqli_query($link,$sql);
while ($row = mysqli_fetch_array($result))
{
?>
<tr><td><table>
<form method="post" name="myform">
<tr>
<td>
<input type='hidden' name='id' value='<?php echo $row['id']; ?>'>
</td>
<td>
<?php echo $row['comment1']; ?>
</td>
<td>
<input type='text' name='comment2' id='comment2' value=""/>
</td>
<td>
<input type ='submit' name='save' id='save' value='Save' />
</td>
</tr>
</form>
</table>
</td>
</tr>
<?php
}
?>
</table>
I have modified my mysql table from InnoDB to MyISAM and then i have added FULLTEXT using this sentence :
ALTER TABLE personal ADD FULLTEXT(personal_name,surname,initials,email,telephone,adegree);
In my application, i have 6 input fields like these:
- id
-personal_name
-surname
-initials
-email
-telephone
and 1 select field like this:
-adegree
As you know , i have to retrieve information acording these fields, so how i can to do using MATCH/AGAINST ? , if not is possible using MATCH/AGAINS for a multiple search, i'm available to implement any other way.
I have used the %LIKE% sentence, but it doesn't work good, here is the code:
file: searchUser.php
$(document).ready(function(){
$("#search").on("click",function(e){
e.preventDefault();
$.ajax({
dataType:'html',
type: "POST",
url: "processarSearchUser.php",
data: dades ,
success: function(data){
$("#contenidor").show("500",function(){
$("#contenidor").html(data);
})
}//succes
});//ajax
});//search
});//document
<form name="formulariFilter" id="formulariFilter" method="post" enctype="multipart/form-data">
<h1>Search User</h1>
<tr>
<td><b>id:</b></td>
<td><input type="text" name="id" id="id"></td>
</tr>
<tr>
<td><b>Personal name:</b></td>
<td><input type="text" name="personalname" id="personalname" ></td>
</tr>
<tr>
<td><b>Surname:</b></td>
<td><input type="text" name="surname" id="surname" ></td>
</tr>
<tr>
<td><b>Initials:</b></td>
<td><input type="text" name="initials" id="initials" ></td>
</tr>
<tr>
<td><b>Email:</b></td>
<td><input type="text" name="email" id="email" ></td>
</tr>
<tr>
<td><b>Telephone:</b></td>
<td><input type="text" name="telephone" id="telephone" ></td>
</tr>
<tr>
<td><b>Academic degree:</b></td>
<td><select name="adegree" id="adegree">
<option value="0">---Select something---</option>
<?php
$consulta= mysqli_query($conexio, "SELECT adegree from personal" );
while($fila=mysqli_fetch_assoc($consulta)){
echo"<option value='".$fila['adegree']."'/>"."<b>".$fila['adegree']."</b>"."</option>";
}
?>
</select></td>
<!--<td><input type="text" name="adegree" id="adegree" ></td>-->
</tr>
<tr>
<td colspan="2" id="td_boto"><input type="button" name="search" id="search" value="SEARCH" ></td>
</tr>
</form>
file : processarSearchUser.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
include("../Projecte Bonita/conectar.php");
$conexio=conectar_bd();
$id = mysqli_real_escape_string($conexio,addslashes($_POST['id']));
$personalname = mysqli_real_escape_string($conexio,addslashes($_POST['personalname']));
$surname = mysqli_real_escape_string($conexio,addslashes($_POST['surname']));
$initials = mysqli_real_escape_string($conexio,addslashes($_POST['initials']));
$email = mysqli_real_escape_string($conexio,addslashes($_POST['email']));
$telephone = mysqli_real_escape_string($conexio,addslashes($_POST['telephone']));
$adegree = mysqli_real_escape_string($conexio,addslashes($_POST['adegree']));
/*$sql="SELECT applus_code,personal_name,surname,initials,email,telephone,adegree from personal WHERE
id LIKE '%".$id."%' or
personal_name LIKE '%".$personalname."%' or
surname LIKE '%".$surname."%' or
initials LIKE '%".$initials."%' or
email LIKE '%".$email."%' or
telephone LIKE '%".$telephone."%' or
adegree LIKE '%".$adegree."%'";*/
if($adegree != 0){
$sql="SELECT * from personal WHERE
id LIKE '%".$id."%' and
personal_name LIKE '%%' and
surname LIKE '%".$surname."%' and
initials LIKE '%".$initials."%' and
email LIKE '%".$email."%' and
telephone LIKE '%".$telephone."%' and
adegree LIKE '%".$adegree."%'";
}
else{
$sql="SELECT * from personal WHERE
id LIKE '%".$id."%' and
personal_name LIKE '%%' and
surname LIKE '%".$surname."%' and
initials LIKE '%".$initials."%' and
email LIKE '%".$email."%' and
telephone LIKE '%".$telephone."%' ";
}
$consulta= mysqli_query($conexio,$sql);
$resultat=mysqli_fetch_assoc($consulta);
if($consulta){
if(mysqli_num_rows($consulta) >0){
if(!empty($resultat)){
echo "<table id='reultat' class='taula'>";
echo"<thead>";
echo "<tr>";
echo"<th>id</th>";
echo"<th>Personal name</th>";
echo"<th>Surname</th>";
echo"<th>Initials</th>";
echo"<th>Email</th>";
echo"<th>Telephone</th>";
echo"<th>Adegree</th>";
echo"</tr>";
echo"</thead>";
echo"<tbody";
while($fila=mysqli_fetch_assoc($consulta)){
echo"<tr>";
echo "<td>".$fila['id']."</td>";
echo "<td>".$fila['personal_name']."</td>";
echo "<td>".$fila['surname']."</td>";
echo "<td>".$fila['initials']."</td>";
echo "<td>".$fila['email']."</td>";
echo "<td>".$fila['telephone']."</td>";
echo "<td>".$fila['adegree']."</td>";
echo"</tr>";
}
echo "</tbody>";
echo "<table>";
liberar($consulta);
desconectar_bd($conexio);
}
else{
echo"<table id='resultat'class='noResults' align='center'>";
echo"<tr>";
echo"<td>No results!</td>";
echo"</tr>";
echo"</table>";
}
}
else{
echo"<table id='resultat'class='noResults' align='center'>";
echo"<tr>";
echo"<td>No results!</td>";
echo"</tr>";
echo"</table>";
}
}
else{
echo"<table id='resultat'class='noResults' align='center'>";
echo"<tr>";
echo"<td>Query error!</td>";
echo"</tr>";
echo"</table>";
}
}
else{
echo"no post";
}
?>
I recently added a search feature to one of my websites using the LIKE function.
When I submit my search form via GET, I build the database query string based on those variables that are passed with the form.
if(strcmp($_GET['SSeries'],'') != 0) {
$searchString .= "Series LIKE '%".$_GET['SSeries']."%' AND ";
$uFriend .= "Series CONTAINS '".$_GET['SSeries']."' AND ";
}
if(strcmp($_GET['SModel'],'') != 0) {
$searchString .= "Model LIKE '%".$_GET['SModel']."%' AND ";
$uFriend .= "Model CONTAINS '".$_GET['SModel']."' AND ";
}
if(strcmp($_GET['SSerial'],'') != 0) {
$searchString .= "Serial LIKE '%".$_GET['SSerial']."%' AND ";
$uFriend .= "Serial CONTAINS '".$_GET['SSerial']."' AND ";
}
$_SESSION['searchString'] = $searchString;
then at the end, declare a variable that connects them all together.
Then, I just use that variable in my search string like so:
if(empty($_SESSION['searchString'])) {
$sql = "SELECT * from identification;";
$sqluFriend = "Search ALL";
} else {
$sql = "SELECT * from identification WHERE ".substr($_SESSION['searchString'], 0, -5).";";
$sqluFriend = "Search ".substr($_SESSION['uFriend'], 0, -5)."";
}
If the search string is empty, I create a query that has no where clause.
Also, note the use of the substr() method used, as removes the last 5 symbols from the search string (Basically so the string doesn't end with AND as that would cause issues with the query.) Also, you can ignore the $sqluFriend variables, I use those to display a user friendly version of the query.
Basically, as shown above, I build the search string depending on if the GET variable is posted, it makes it a dynamic search query.
Another thing is you should wrap your $searchString builder with if statements that check if any of the data is posted, to avoid errors/return error codes etc. Here is how I did that:
if((isSet($_GET['SSSeries']))
|| (isSet($_GET['SSModel']))
|| (isSet($_GET['SSSerial']))) {
You can of course expand this to meet your needs fairly easily.
What I did was connected my form to an ajax request every time an input was changed, so that when someone entered anything it would automatically reload the table with the results.
Hope I could help.
I have a PHP script that connects to a MySQL database using the mysqli extension to search for Blog Posts based on Username or ID. I created a VIEW called BlogSearch that uses joins form other tables to aggregate the information I need together that is represented like this:
The Tables it pulls from are called Profiles that has the User information, BlogPosts and BlogCategory
Everytime I search I get the error:
Unknown column 'chenzhen' in 'where clause'
The PHP code I'm using below:
require 'database.php';
$query = "SELECT * FROM BlogSearch";
echo <<<EOF
<form method='post' action='' style="padding: 30px 0;">
<table cellspacing="0" border="0" style="float: left;">
<tr>
<td>Search Blog Posts by Username/ID</td>
<td><input type="text" id="search" name="search" style="width: 300px;"/></td>
<td><input type="submit" id="submit_button" value="Search" name="submit_button" style="float: right;" /></td>
</tr>
</table>
</form>
EOF;
if(isset($_POST['submit_button']))
{
$search_term = $_POST['search'];
$query = $query . " WHERE `NickName` LIKE '%$search_term%' OR ID = $search_term ";
// run the query and store the results in the $result variable.
$result = $mysqli->query($query) or die(mysqli_error($mysqli));
}
if ($result) {
// create a new form and then put the results
// into a table.
echo "<form method='post' action='delete.php' style='clear: both;'>";
echo "<table cellspacing='0' cellpadding='15'>
<th width='5%'>
<input type='checkbox' id='allcb' onclick='checkAll(this)' name='allcb' />Check All
</th>
<th width='10%'>User</th>
<th width='85%'>Blog Post Title</th>
";
while ($row = $result->fetch_object()) {
$title = substr($row->PostCaption,0,50);
$id = $row->PostID;
$user = $row->NickName;
//put each record into a new table row with a checkbox
echo "<tr>
<td><input type='checkbox' name='checkbox[]' id='checkbox[]' value=$id />
<td>$user</td>
<td>$title</td>
</tr>";
}
// when the loop is complete, close off the list.
echo "</table><p><input id='delete' type='submit' class='button' name='delete' value='Delete Selected Items'/></p></form>";
}
I don't know why it's even identify the username as a column. Can anyone point me in the right direction to fix this?
Thanks in advance.
Any element in an SQL query that isn't an SQL keyword or a literal (denoted by single quotes), is assumed to be an object (e.g. table, column) name.
Your problem is the missing quotes around $search_term in your WHERE clause:
$query = $query . " WHERE `NickName` LIKE '%$search_term%' OR ID = $search_term ";
You should add them, as thus:
$query = $query . " WHERE `NickName` LIKE '%$search_term%' OR ID = '$search_term' ";
Enclose your $search_term in single quotes in where clause like this '$search_term'
I have a table with some data from a mysql database. I need to update that information from within the table itself so when I press the button submit (table is inside a form) I need that all that data gets updated on the database. I can get the information from the database with no problem but I'm unable to update it! Here is the code:
<table border=1 cellpadding=4 cellspacing=0 width=960px style='font-size:10px'>
<form id='form1' name='form1' method='post' action='itself.php'>
<thead>
<tr>
<th colspan=3> People on the list </th>
<th><input type='submit' name='filtrar' id='filtrar' value='Filtrar'/></th>
<th><input type='submit' name='modificar' id='modificar' value='Modificar'/></th>
</tr>
<tr>
<th><label for='id'>ID</label></th>
<th><label for='id'>Friends</label></th>
<th><label for='id'>On the list?</label></th>
</tr>
<?
while($row = mysqli_fetch_array($result_listas, MYSQLI_BOTH))
$id= $row['id'];
{
?>
<tr>
<td><? echo "$row[id]" ?>
</td>
<td><select name='friends[<? echo "$id" ?>]' size='1' id='friends[<? echo "$id" ?>]'>
<option selected='selected'><? echo "$row[friends]" ?></option>
<option>less than 10</option>
<option>more than 10</option>
</select>
</td>
<td><select name='onlist[<? echo "$id" ?>]' size='1' id='onlist[<? echo "$id" ?>]'>
<option selected='selected'><? echo "$row[onlist]" ?></option>
<option>SI</option>
<option>NO</option>
</select>
</td>
<?
$ssql_min="select min(id) as id from listas_old";
$result_min= mysqli_query($link, $ssql_min);
$resultado_min = mysqli_fetch_array($result_min, MYSQLI_BOTH);
$ssql_max="select max(id) as id from listas_old";
$result_max= mysqli_query($link, $ssql_max);
$resultado_max = mysqli_fetch_array($result_max, MYSQLI_BOTH);
if(isset($_POST[modificar]))
{
for($i=$resultado_min['id']; $i<$resultado_max['id']; $i++)
{
$sql1="UPDATE listas_old SET friends='$friends[$i]', onlist='$onlist[$i]' WHERE id='$i'";
$result1=mysqli_query($link, $sql1);
}
}
?>
The OP wrote in a comment:
Got the solution for myself! This is what I did...
Change the for sentence like this:
for($i=$resultado_min['id'];
$i<=$resultado_max['id'];
$i++) {
$friendsfor= $_POST['friends('.$i.')'];
$onlistfor= $_POST['onlist('.$i.')'];
$sql1="UPDATE listas_old SET friends='$friendsfor', anotado= '$onlistfor' WHERE id='$i'";
}
It seems like you have your quotes all wrong in the update. You are trying to concatenate a string (your update sql) with php variables. But you need to make sure that php recognizes them as a variable instead of just as a string.
Should be like this
$sql1= "UPDATE listas_old SET friends='" . $friends[$i] . "', onlist='" . $onlist[$i] . "' WHERE id='" . $i . "'";
You only need to add in the single quotes if you are adding a varchar or date or something. If it is an int, you don't need the single quotes. Also I'm not sure what onlist would do, or if that is valid.
My main issue that I am running into is basically this:
I have a while loop that generates results from a query. With the results that have been generated, I want the ability to update the table the original query was from.
The query produces the expected results, but the table is not being updated when I click the REMOVE button. I am also trying to find a solution for the results to be updated after the UPDATE query executes...
<?php
$sql = "SELECT * FROM vehicles WHERE sold='n' ORDER BY year DESC";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
echo
"
<tr>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['year'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['make'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['model'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'><input type='submit' name='remove' value='REMOVE' style='background-color:#C33;color:white;padding:10px;border-radius:5px;width:70px'/></td>
</tr>";
if(isset($_POST['remove'])){
$removeSql = "UPDATE `table`.`vehicles` SET `display`='0' WHERE `vin`='{$row['vin']}'";
mysql_query($removeSql) or die('check that code dummy');
}
}
mysql_close($connection);
?>
That's a submit button, will not work without form tag. You can't do it this way.
You can write the remove code on a separate page and convert that submit button to normal button and pass vin id on click of that button and call that page using ajax.
Or if you don't know ajax and want to do it on that page itself then do it this way :
<?php
$sql = "SELECT * FROM vehicles WHERE sold='n' ORDER BY year DESC";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
echo
"
<tr>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['year'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['make'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['model'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>
<form action="" method="POST">
<input type="hidden" name="vin_id" value="<?php echo $row['vin']; ?>">
<input type='submit' name='remove' value='REMOVE' style='background-color:#C33;color:white;padding:10px;border-radius:5px;width:70px'/>
</form></td>
</tr>";
}
if(isset($_POST['remove'])){
$removeSql = "UPDATE `table`.`vehicles` SET `display`='0' WHERE `vin`='".$_POST['vin_id']."'";
mysql_query($removeSql) or die('check that code dummy');
}
mysql_close($connection);
?>