This question already has answers here:
delete using where and or
(4 answers)
Closed 4 years ago.
i've gone through most of the questions similar to this but none addressed my problem.
i have table with four columns : id,username,title and date. i want to delete the entire row(s) associated with a specific username when the user clicks a button (anchor tag). pls, how do i achieve this? heres the code i tried.
php
<?php
session_start();
$uname = $_SESSION['username'];
$dbconn = mysqli_connect('localhost','root','','notesdb');
if(!$dbconn){
die("Connection failed:". mysqli_connect_error($dbconn));
}
if($stmt = $dbconn->prepare("DELETE * FROM notes_log where username = ? ")){
$stmt->bind_param("s",$uname);
$stmt->execute();
$stmt->close();
}else{
echo "ERROR: could not prepare SQL statement.";
}
mysqli_close();
// redirect user after delete is successful
header("Location: index.php");
?>
HTML
Delete all
The above code redirected the page but nothing was deleted.
Get rid of the * in the query. The syntax is just:
DELETE FROM notes_log where username = ?
See DELETE Syntax.
In a multi-table DELETE you need to put the table names after DELETE, but a single-table DELETE should have nothing there.
And when an SQL operation fails, you should print the SQL error message, not just could not prepare SQL statement, e.g.
echo "ERROR: could not prepare SQL statement: " . $dbconn->error;
Edit: mysqli_close() requires a database connection as its only argument.
Ref: http://php.net/manual/en/mysqli.close.php
You will need to use mysqli_close($dbconn).
Related
This question already has answers here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
How can I prevent SQL injection in PHP?
(27 answers)
Closed 5 years ago.
I am trying to store form data into database using mysqli but it is generating query error my code is given below....
When ever I try to submit the database connection is generating.. the $_POST is working perfectly.. the error only generating by mysqli_query..
<?php
$name = $_POST["firstname"] . " " . $_POST["lastname"];
$email = $_POST["email"];
$happen = $_POST["whendidhappen"];
$howlong = $_POST["howlong"];
$howmany = $_POST["howmany"];
$describe = $_POST["describe"];
$whattheydid= $_POST["whattheydid"];
$seenmycat = $_POST["seenmycat"];
$anythingelse = $_POST["anythingelse"];
$dbc = mysqli_connect('localhost','root','','abductionreport')
or die('Database connection error');
$query = "INSERT INTO abductionform (firstname, lastname, email,whendidhappen, howlong, describe, whattheydid, seenmycat,anythingelse)VALUES('$name','$name','$email','$happen','$howlong', '$howmany','$describe','$whattheydid', '$seenmycat','$anythingelse')";
$result = mysqli_query($dbc,$query) or die ("Query Error");
mysqli_close($dbc);
?>
<h3>Aliens Abducted Me - Report an Abduction</h3>
<p>Thanks for Submiting the form.</p>
<?php
echo "$name it happend to you on $happen it take $howlong <br>";
echo "Number of aliens: $howmany<br>";
echo "Describe: $describe<br>";
echo "What they did to you: $whattheydid<br>";
echo "Have you seen my cat: $seenmycat<br>";
echo "Anything else : $anythingelse<br>";
echo "Your Email Address is : $email<br>";
?>
DESCRIBE is a mysql keyword. Wrap the column name in backticks. For that matter wrap your table and all columns in backticks. Always check that $_POST elements exist with isset () before trying to access them. Use mysqli prepared statements with placeholders for improved security. Always perform error checking BEFORE posting to SO.
You also have 9 columns and 10 values in your query - this will cause a failure every time.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am doing a system with php code,But delete function with SQL is not working.I don't know why it happens.
Below is my code:
function deleteEmployee($params)
{
$tid = $_SESSION['tmid'];
$data = array();
//print_R($_POST);die;
$sql = "delete from `cusinfo` WHERE TICKET_ID='".$params["id"]."' AND AGENT_CODE_STAFF_ID IN (SELECT id FROM `users` where tm_groupid = '$tid')";
echo $result = mysqli_query($this->conn, $sql) or die("error to delete employee data");
}
The problem probably is in the line echo $result = mysqli_query($this->conn, $sql) or die("error to delete employee data");
As I said in one comment, replacing the die string with mysqli_error($this->conn) should display an error.
However after some testing I found that assigning a variable in a echo might give strange results, i test echo $test = "hello" or die("test"); and found that neither hello nor test was displayed on the screen, but 1 was displayed, which probably was the boolean true.
A better way to see if the query was executed could be:
//other code that stayed the same
$statement = mysqli_prepare($this->conn, "delete from `cusinfo` WHERE TICKET_ID=? AND AGENT_CODE_STAFF_ID IN (SELECT id FROM `users` where tm_groupid = ?)");
$statement = mysqli_stmt_bind_param($this->conn, $params['id'], $tid); //
$sql = msyqli_stmt_execute($statement); // returns either true or false
if ($sql === true) {
echo "Successfull"; // executing successfull code
}
else {
var_dump(mysqli_stmt_error_list($statement)); // handling error
die;
}
This will handle some sql errors in a way that is expected(they are 'dumped and died').
Using prepared statements the correct way will mean that most sql injections are able to be stopped, and with a DELETE query, you want to make sure that sql injections are stopped.
Note: I am no expert on sql injections
Note 2: I would have used PDO for prepared statements though, it seems to me to be much more logical to work with
echo $result = mysqli_query($this->conn, $sql) or die("error to delete employee data");
In above line you are execution query and echo it. But if it is not executed you are echo your own message. This will prevent you from actual error message. And if the row that you are going to delete from TICKET_ID not exsist you cannot see it, you only see your message "error to delete employee data".
To solve this:
echo mysqli_error($this->conn);
This will give you connection error.
Or:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($result) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
Many many function have to handle these errors. stackoverflow question, php manual and this.
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I have issue with the query. i don't know why its not working,
it always shows , there is an error, and do not insert data into table, although it is collecting data from form.
there is no error or warning notification but it chooses the else option from if condition and does not insert data into table, don't know why.
<?php
$con=mysqli_connect('localhost','root','','flentox');
if(mysqli_connect_error($con))
{
echo "there is an error in connection";
}
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$area=$_POST['select'];
$address=$_POST['address'];
$eaddress=$_POST['eaddress'];
$query= mysqli_query($con, "INSERT INTO order(Fname,Lname,Email,Phone,Area,Address,Eaddress) VALUES(`$fname`,`$lname`,`$email`,`$phone`,`$area`,`$address`,`$eaddress`)");
if ($query) {
echo "order confirm";
}
else {
echo "There is an error";
}
?>
Your query is not correct, you don't need to use ( `` ) in VALUES. Don't forget to check if your values is empty or not.
So if there is no data has come from $_POST, your query also will be crashed.
Also don't forget about SQL injections. It is not recommended to insert $_POST or $_GET data immediately in query. Use Prepared Statements.
Try this.
$fname = (empty($_POST['fname']) ? 'default value' : $_POST['fname']);
.......... (for other params too).
"INSERT INTO order (`Fname`,`Lname`,`Email`,`Phone`,`Area`,`Address`,`Eaddress`)
VALUES('".$fname."','".$lname."','".$email."','".$phone."','".$area."','".$address."','".$eaddress."')";
Also to show your errors, run this code at the very top of the php file -
error_reporting(1);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i have the following php:
<?php
$connection=mysqli_connect("host","user","pass","db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($connection,"SELECT ID FROM tbname");
while($row = mysqli_fetch_array($result))
{
mysqli_query($connection,"UPDATE tbname SET amount= (amount+ 1) WHERE ID='$row[ID]' ");
}
mysqli_close($connection);
echo 'OK'; ?>
I want to 'corelate' the pressing of a button to update the associated row value from the table but when i use this code i get all my values updated. Can anyone help me ?
This assumes that your ajax request is passing an 'id' parameter. Note that this code is open to SQL injection attacks. I am assuming that you know how to properly sanitize your inputs and parameterize your queries to protect yourself. If you don't, Jay's answer includes some good links that you should check.
<?php
if(!empty($_POST["id"]))
{
$id = $_POST["id"];
$connection=mysqli_connect("host","user","pass","db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
mysqli_query($connection,"UPDATE tbname SET amount= (amount+ 1) WHERE ID = '" . $id . "'");
mysqli_close($connection);
echo 'OK';
}
else
{
echo 'NO ID PASSED';
}
?>
You have to properly identify the variable in the array and concatenate the variable in the query:
mysqli_query($connection,"UPDATE tbname SET amount = amount+ 1 WHERE ID='" . $row['ID']. "' ");
you also do not need the parentheses around the calculation in the SET clause.
Since you're selecting all of the rows in your table and then looping through all of the rows and changing the value, which is not what you want, you have to select with a filter:
SELECT ID FROM tbname WHERE *some condition is met*
Once you do that you'll be able to update a subset of your records as you desire.
Since you're using MySQLi you should learn about prepared statements for MySQLi to guard yourself from potential SQL Injection Attacks.
in addition you should employ error checking, such as or die(mysqli_error()) to your connection and queries. If not you'll have to look in your error logs to fish out any problems that you could have with these.
This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 7 years ago.
I am currently trying to use PHP as a backend and MYSQL as my database to setup a simple PHP script that will send a friend request.
There are two parameters for a friend request in my MYSQL data base, From, Too. The Database name is send_friendreq and the table in that database is pending_req.
I have tried multiple ways of sending a post, including PostMan and a different addon but everytime I send the post, I get an error from my PHP code which is "Failed". From my understanding this means that it is connecting to the database fine, but it's not actually sending the data too the Database.
I'm not sure if I have the database set up wrong, or if my PHP is wrong but any help would be extrememly appreciated.
Here is my code for the PHP backend
//Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_errno();
}
if (isset($_POST['Username']) && isset($_POST['FriendReq']))
{
$username = $_POST['Username'];
$usernamebeingreq = $_POST['FriendReq'];
//$sqlCheck = "SELECT Username FROM Users WHERE Username = '" . $usernamebeingreq . "'";
//$resultCheck = mysqli_query($con, $sqlCheck);
//if(!$resultCheck)
//{
//echo "Invalid Username";
//}
//else
//{
$sql="INSERT INTO pending_req (To, From) VALUES ('$usernamebeingreq', '$username')";
$result = mysqli_query($con, $sql);
if(!$result)
{
echo 'Failed';
}
else
{
echo 'Friend added!';
}
//}
}
else
{
echo 'Missing Parameters';
}
?>
If you are in need of my database information, I can reveal that!
from and to are reserved words in SQL you have to add backticks arrond:
$sql="INSERT INTO pending_req (`To`, `From`) VALUES ('$usernamebeingreq', '$username')";
or better rename the column.
Hint: use prepared statement. it is much more safty.