delete button in PHP not working - php

I've made a delete button and I want that whenever is get pressed it deletes a 'reservation' in my database. This is my code:
require_once"database.php";
if(isset($_POST["verwijderen"])) {
$email = ($_SESSION["userId"]);
$delete = mysql_query("DELETE FROM reserveringen WHERE Email = $email ");
}
verwijderen is the name of my delete button. $email gives me the email of the person who's logged in and $delete is the query. reserveringen is my table name and email is the colomn's name. I've tried this but it isn't working. $email does give me the email of the logged in person (I've checked it with echo($email)).
Edit:
full code:
<?php
session_start();
$loggedIn = "";
if (isset($_SESSION["loggedIn"])) {
$loggedIn = $_SESSION["loggedIn"];
} else {
header('Location:reserveringssysteeminloggen.php');
}
$email = ($_SESSION["userId"]);
require_once"database.php";
if(isset($_POST["verwijderen"])) {
$email = ($_SESSION["userId"]);
$result = $mysql_query("DELETE FROM reserveringen WHERE Email = '$email' ");}
?>

SQL uses single quotes (') to denote string literals, which you are currently missing:
$delete = mysql_query("DELETE FROM reserveringen WHERE Email = '$email'");
EDIT:
Obligatory warnings:
mysql_query is deprecated, please consider either mysqli or PDO.
This approach is vulnerable to SQL injection attacks. Consider using a prepared statement.

Add a quotes around $email like:
$delete = mysql_query("DELETE FROM reserveringen WHERE Email = '$email' ");
Note aside: Your query is vulnerable to SQL Injection. You may consider using prepared statement.

First of all, don't use mysql_query, it is deprecated. PDO::Mysql is the new standard to use, it is also much safer to use because of the prepare statement (and bindParam). This will safeguard you against SQL injections. It will also automatically place your string correctly into the sql-query.
$pdo = new PDO('mysql:host=localhost;dbname=DATABASENAME', "USERNAME", "PASSWORD");
if(isset($_POST["verwijderen"])){
$sql = "DELETE FROM reserveringen WHERE Email = :email";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->execute();
}

Related

Is this the right way to parameterize query? Is there any other way?

Well i learned how to parameterize queries in php but i just wanted to ask that is it now totally secure from sql injection or any other type of attacks and if it isnt what betternment can i do to secure it even more?
<?php
include 'db.php';
$name = "";
$pass = "";
if(isset($_POST['send'])) {
$name = $_POST['name'];
$sql_u = "SELECT * FROM users WHERE username='$name'";
$res_u = $connection->query($sql_u);
if (mysqli_num_rows($res_u) > 0) {
echo "Sorry Username already taken";
}
else {
$password = $_POST['pass'];
$hpass = password_hash($password, PASSWORD_DEFAULT);
$query=$connection->prepare("insert into users (username,password) values (?,?)");
$query->bind_param('ss',$name,$hpass);
if ($query->execute()) {
$query->close();
header('location:index.php');
} else {
header('location:not.php');
}
}
}
I want to know if their is a even more secure way than only parameterizing queries?
You're using parameters for the INSERT statement, but you skipped using parameters for the SELECT statement. Without parameterizing the SELECT, you still have an SQL injection vulnerability. You need to use parameters in all cases when you combine untrusted content with your SQL.
Parameters are a good way to prevent SQL injection when combining dynamic content as values in your SQL queries.
You asked if there were another way, so I will recommend that you use PDO if you're starting out with a new PHP project. It's a little bit easier than Mysqli. In my opinion, there's no reason to use Mysqli unless you're porting a legacy PHP application that had used the deprecated Mysql PHP extension.
Here's what it would look like using PDO:
$name = $_POST['name'];
$sql = "SELECT COUNT(*) FROM users WHERE username = ?";
$query = $connection->prepare($sql);
$query->execute([$name]);
$count = $query->fetchColumn();
if ($count > 0) {
echo "Sorry Username already taken";
}
else {
$password = $_POST['pass'];
$hpass = password_hash($password, PASSWORD_DEFAULT);
$sql = "insert into users (username, password) values (?, ?)";
$query = $connection->prepare($sql);
if ($query->execute([$name, $hpass])) {
header('location:index.php');
} else {
header('location:not.php');
}
}
I'm assuming that the PDO connection was made previously, and that it had been enabled with exceptions. If you don't enable exceptions, you should check return values from every prepare() and execute() call to make sure there are no errors.
The same is true for Mysqli, you can enable exceptions so you don't have to check for errors manually.
I also show in the example my preference to use SELECT COUNT(*) instead of SELECT *. It's probably a trivial optimization in this case, but if * refers to many columns or there are many rows matching username = $name then the fetch will need to transfer less data from the database.

Password verification php form

Here I have some php code which allows me to update User information in my students table.
I am trying to figure out how am I able to check if the password for the user that is currently logged in matches the password stored in the database before allowing information can be updated.
As the others say, your script has bunch of holes.
I assume you are developing for local area only.
if you host it at this stage, surely you will get security problems.
Alright, back to your question.
There are several ways to validate user before commit update.
For example:
Put sql condition when updating the change
if(isset($_POST['Update'])){
$UpdateFName = $_POST['FirstName'];
$UpdateLName = $_POST['LastName'];
$UpdateEmail = $_POST['Email'];
$UpdateFPassword = $_POST['Password'];
$SQL = $conn->query("UPDATE students
SET FName='{$UpdateFName}',LName='{$UpdateLName}',Email='{$UpdateEmail}',Password='{$UpdateFPassword}'
WHERE UserID = $User and Password = '$_SESSION["PW"]' ");
header('Location:updateinfo.php');
}
if you use this method, if the current password is different with password that stored in db, those edit sql won't run, since where condition is invalid
validate the user first.
if(isset($_POST['Update'])){
$UpdateFName = $_POST['FirstName'];
$UpdateLName = $_POST['LastName'];
$UpdateEmail = $_POST['Email'];
$UpdateFPassword = $_POST['Password'];
$sqlValidate = $conn->query("SELECT * FROM students WHERE UserID ='$User' and Password='$_SESSION["PW"]' ");
$getUser = $sqlValidate -> fetch_array(MYSQLI_BOTH);
if($getUser['UserID'] != ''){
$SQL = $conn->query("UPDATE students SET FName='{$UpdateFName}', LName='{$UpdateLName}', Email='{$UpdateEmail}', Password ='{$UpdateFPassword}' WHERE UserID = $User ");
}// end if
header('Location:updateinfo.php');
}
you can read http://php.net/manual/en/function.crypt.php for password encryption.
your form basically has no validations. Also, there are opportunities for SQL injections.
validate your email field before posting it. try:
if(!filter_var($email_variable,FILTER_VALIDATE_EMAIL){
//throw some kind of exceptions or kill the process
}
I also advise that you use PDO as it supports the use of prepared statements. There is an amazing function there can bindParam() which binds your parameters.
TRy:
$DBH = new PDO("mysql:host=localhost;dbname=test", 'root', '');
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$STH = $DBH->prepare("SELECT * FROM student_table WHERE studentID= :id");
$id = 1; // here you should keep it as variable and pass it to param
$STH->bindParam(':id', $id, PDO::PARAM_STR);
$STH->execute();
$STH->setFetchMode(PDO::FETCH_ASSOC);
Also, do not post raw passwords directly to your database. Either use the inbuilt php hashing algorithm or use some kind of encryption function to secure them.

PDO DELETE also creates a new INSERT

I have a strange problem where every time I do a simple DELETE query to delete WHERE email =. For some reason after deletion it also does a new INSERT with the same email? There is no INSERT anywhere and there are no triggers... Does anybody know why this happens? The table has a email and a nr with auto_increment.
$check_email = $_POST['email'];
$query = "SELECT `email` FROM `newsletter` WHERE email = '$check_email';";
$sth = $dbh->prepare($query);
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
$check_users_email = $row['email'];
if($check_users_email != ''){
$query_update = "DELETE FROM `newsletter` WHERE email = '$check_users_email';";
}
$sth = $dbh->prepare($query_update);
$sth->execute();
Before deletion: email=test#email.com | nr=1
After deletion: email=test#email.com | nr=2
it might be in your sql string, since you're using prepared statements.
in PDO you should use named or unnamed placeholders. then after preparing the query, you pass the prams as an array when you execute the statement.
If you're using PDO, no need to use single quotes. just the column name and for the search value just use placeholders and then pass on the values on execution as an array.
NOTE: i renamed the PDO object $sth inside the 'if' statement, just to avoid name clash. also i moved the last 2 lines inside the 'if' statement, because you need the value of the sql string '$query_update' which will not be available if that statement returned false.
also to check if the variable $check_users_email is empty, you can use empty() or strlen().
try this:
$check_email = $_POST['email'];
$query = "SELECT email FROM newsletter WHERE email = :check_email";
$sth = $dbh->prepare($query);
$sth->execute(array(':check_email' => $check_email));
$row = $sth->fetch(PDO::FETCH_ASSOC);
$check_users_email = $row['email'];
if($check_users_email != ''){
$query_update = "DELETE FROM newsletter WHERE email = :check_users_email";
$sth2 = $dbh->prepare($query_update);
$sth2->execute(array(':check_users_email' => $check_users_email));
}

Trouble with MYSQL update column for one selection

I'm having trouble getting this to update when needed. This is an optout script intended to updated the selected email row with the value of 1 in the removed column. I can't seem to get it to update and I'm thinking its an issue with my sql. Any help in understanding this is much appreciated.
As a note:
I'm making it to Sorry there seems to be an issue with.........
Here is the script.
<?php
if (isset($_GET['e'])) {
include_once "../storescripts/connect_to_mysql.php";
$email = $_GET['e'];
$sql_delete = mysql_query("UPDATE test WHERE email='$email' SET removed = '1'");
if (!$sql_delete) {
echo "Sorry there seems to be and issue when trying to remove your listing. Please email Admin directly using this email address: chris#.com";
} else {
echo "Sorry to see you go! You will not receive our newsletter ever again unless you relist. To gain access to our newsletter again simply let us know by email at chris#.com";
}
}
?>
Try:
$sql_delete = mysql_query("UPDATE test SET removed = '1' WHERE email='$email'");
The problem is your syntax, have a look at the mysql update syntax, where the where clause should go and where set should go http://dev.mysql.com/doc/refman/5.0/en/update.html.
You would have seen this problem had you used proper error handling, like follows:
$sql_delete = mysql_query("UPDATE test SET removed = '1' WHERE email='$email'") or die(mysql_error());
Have a look at mysql_real_escape_string http://www.php.net/manual/en/function.mysql-real-escape-string.php, to prevent SQL injection. Example:
$email = mysql_real_escape_string($email);
$sql_delete = mysql_query("UPDATE test SET removed = '1' WHERE email='$email'") or die(mysql_error());
Also note that mysql_ extension are deprecated, you want to start using mysqli or PDO.
Use SET before your WHERE clause.
UPDATE test
SET removed = '1'
WHERE email = '$email'
The update syntax is
UPDATE
table
SET
column = value
WHERE
condition = met
On another note, I see you're using a very unsafe method of dynamic entries ($_GET) and Mysql_* function are deprecated in new version of php >= 5.5. I'd highly recommend researching PDO for the use of bind variables otherwise you can easily get "hacked" if
$_GET['e'] = "fake' OR '1'='1" // known as sql injection
Good Read
How to prevent SQL injection in PHP?
Why shouldn't I use mysql_* functions in PHP?
You are right, your UPDATE syntax is incorrect. This is the correct form:
UPDATE test
SET removed = '1'
WHERE email = '$email'
Your query should be
mysql_query("UPDATE test SET removed = '1' WHERE email='$email'");
But please notice that this extension is deprecated.
Use MySQLi or PDO_MySQ instead.
the solution in both extensions are as follows.
MySQLi:
$mysqli = new mysqli(GDB_HOST, GDB_USERNAME, GDB_PASSWORD, GDB_NAME);
$cmd = $mysqli->prepare("UPDATE test SET removed = '1' WHERE email= ? ");
$cmd->bind_param('s', $email);
$cmd->execute();
PDO
$dbh = Database::connect();
$query = "UPDATE test SET removed = '1' WHERE email= ? ";
$sth = $dbh->prepare($query);
$sth->execute(array($email));
One of the big importances of using one of these 2 extensions is the fact that you avoid any attempt of SQL injection

mysql_real_escape_string not letting string through

I'm trying to sanitize a string going into my database. But with the code below, I don't get the update to my db.
First page posts this in an input form:
$note="Here is some example text";
Receiving page:
$note = $_POST['note'];
$note = mysql_real_escape_string($note);
$sql="UPDATE some_table SET notes='$note' WHERE id='$some_id'";
$result=mysql_query($sql);
When I take out the mysql_real_escape_string line it works, but not with it in there.
What am I missing?
Thanks!
I strongly recommend using Prepared Statement, mysql_real_escape_string() won't full protect you from SQL Injection.
Example for your update:
<?php
// connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// query
$sql = "UPDATE some_table
SET notes=?
WHERE id=?";
$q = $conn->prepare($sql);
$q->execute(array($$_POST['note'], $some_id));
?>
More details: http://www.php.net/manual/en/intro.pdo.php

Categories