So I'm trying to build a kind of update email function, and the part that should put it into the db looks like this
<?php $emailfrom = $_POST['emailfrom'];
$emailto = $_POST['emailto'];
$query = sprintf('UPDATE `users` SET `email`="%s" WHERE `email`="%s"`',
mysqli_real_escape_string($db, $emailfrom),
mysqli_real_escape_string($db, $emailto));
mysqli_query($db, $query);
The problem is that the row don't update... And I need help in knowing why, as I'm not so well experienced with mysql, used other dbs mainly earlier
You've got syntax error in your query.
\/
$query = sprintf('UPDATE `users` SET `email`= "%s" WHERE `email`= "%s"`',
mysqli_real_escape_string($db, $emailfrom),
mysqli_real_escape_string($db, $emailto));
mysqli_query($db, $query);
Also, you probably want to change emails from emailFrom to emailTo, now you are doing it the other way around. After edit:
$query = sprintf('UPDATE `users` SET `email`= "%s" WHERE `email`= "%s"`',
mysqli_real_escape_string($db, $emailto),
mysqli_real_escape_string($db, $emailfrom));
mysqli_query($db, $query);
The accepted answer will work, but a prepared statement would be much safer
$query="UPDATE `users` SET `email`= ? WHERE `email`= ?";
$stmt = $db->prepare($query);
$stmt->bind_param('ss',$_POST['emailfrom'],$_POST['emailto']);
$stmt->execute();
$stmt->close();
With a prepared statement you don't have to worry about escaping your variables to prevent SQL injection.
Related
I did 3 queries (SELECT, INSERT, UPDATE) it works but at the current state looks ugly and not safe.
Is there any way to make these SELECT, INSERT, UPDATE queries more readable and safer than this with the prepared statement?
$email = $_SESSION['email'];
$query = "SELECT username FROM users WHERE email='$email'";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_assoc($result);
$username = $row['username'];
if(!empty($_POST["comment"])){
$id = $_GET['id'];
$sql = "INSERT INTO user_comments (parent_id, comment, username, custom_id) VALUES ('".$_POST["commentID"]."', '".$_POST["comment"]."', '$username', '$id')";
mysqli_query($connect, $sql) or die("ERROR: ". mysqli_error($connect));
/// I need this update query to make every inserted comment's ID +1 or can I do this more simple?
$sql1 = "UPDATE user_comments SET id = id +1 WHERE custom_id = '$id'";
mysqli_query($connect, $sql1) or die("ERROR: ". mysqli_error($connect));
Give this a try. You can use $ex->insert_id to get the last entered ID. This may come in handy when mass inserting into a DB. I generally use PDO as I find the code looks cleaner but it's all preference I suppose. Keep in mind for the ->bind_param line that "isii" is referring to the type(s) of data which you are entering. So, in this case, its Integer, String, Integer, Integer (I may have got this wrong).
$email = $_SESSION['email'];
$query = "SELECT username FROM users WHERE email='$email'";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_assoc($result);
$username = $row['username'];
if(!empty($_POST["comment"])){
$id = $_GET['id'];
$commentID = $_POST["commentID"];
$comment = $_POST["comment"];
$sql = "INSERT INTO user_comments (parent_id, comment, username, custom_id) VALUES (?, ?, ?, ?)";
$ex = $connect->prepare($sql);
$ex->bind_param("isii", $commentID, $comment, $username, $id);
if($ex->execute()){
// query success
// I need this update query to make every inserted comment's ID +1 or can I do this more simple?
$lastInsertID = $ex->insert_id;
$sql1 = "UPDATE user_comments SET id = id + 1 WHERE custom_id = ?";
$ex1 = $connect->prepare($sql1);
$ex1->bind_param("i",$lastInsertID);
if($ex1->execute()){
// query success
}else{
// query failed
error_log($connect->error);
}
}else{
//query failed
error_log($connect->error);
}
I have a sql statement to update confirm code and code in the database. I'm using bind param to bind the variables. It worked fine for my select and insert sql statements. However, it keeps giving me this error:
Fatal error: Uncaught Error: Call to a member function bind_param() on boolean
when I tried to execute the update query. I tried to search on every forums possible but found no answers and I hope someone could maybe spot my mistake. I'm having issues with $query1. Both code and confirmcode are varchar and not integer.
$username = $_GET['username'];
$code = $_GET['code'];
$confirmcode = "1";
$updatecode ="0";
$query=$con->prepare("SELECT username, code FROM customer_detail WHERE username ='$username'");
$query->execute();
$query->bind_result($checkusername, $checkcode);
$query->fetch();
$query1=$con->prepare("UPDATE customer_detail SET code=?, confirmcode=? WHERE username = ?"); //error
$query1->bind_param('sss',$username, $updatecode, $confirmcode); //error
$query1->execute();
The problem is that MySQLi can't run multiple queries at once, because it uses ubuffered queries. You'll need to close the first statement before you can run another. Add the following line after $query->fetch();.
$query->close();
This being said, your first query isn't guarded against SQL injection, because you use the variable directly in the query. Adding proper placeholders for your query, the final code would look like this
$query = $con->prepare("SELECT username, code FROM customer_detail WHERE username =?");
$query->bind_param('s', $username);
$query->execute();
$query->bind_result($checkusername, $checkcode);
$query->fetch();
$query->close();
$query1 = $con->prepare("UPDATE customer_detail SET code=?, confirmcode=? WHERE username = ?");
$query1->bind_param('sss',$username, $updatecode, $confirmcode);
$query1->execute();
$query1->close();
Try below code. Basically, you need to bind the params in the same order in which the placeholders (?) appear in the sql.
$query=$con->prepare("SELECT username, code FROM customer_detail WHERE username = ?");
$query->bind_param('s', $username);
$query->execute();
$query->bind_result($checkusername, $checkcode);
$query->fetch();
$query1=$con->prepare("UPDATE customer_detail SET code=?, confirmcode=? WHERE username = ?");
$query1->bind_param('sss', $updatecode, $confirmcode, $username);
$query1->execute();
Have you tried tis?
$query1->bind_param('iis', $updatecode, $confirmcode, $username);
Simple question. How do i make the query work? I know you can't directly use $_POST in a query. But i do not know how to get this to work.
$sql = 'SELECT * FROM users WHERE `password` = $_POST[password] AND `username` = $_POST[username]';
$result = mysqli_query($link, $sql);
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysqli_error($link);
exit;
I have also tried using the mysqli_real_escape_string like this :
$username_sql = mysqli_real_escape_string($link, $_POST['username']);
$password_sql = mysqli_real_escape_string($link, $_POST['password']);
This did not work as planned. As it did still not work.
Thanks,
Mike
use '' with string comparison of MySQL
$username_sql = mysqli_real_escape_string($link, $_POST['username']);
$password_sql = mysqli_real_escape_string($link, $_POST['password']);
$sql = "SELECT * FROM users
WHERE `password` = '$username_sql' AND `username` = '$password_sql'";
Use prepared statements to avoid sql injection and syntax errors with commas .
$sql = 'SELECT * FROM users WHERE `password` = ? AND `username` = ?';
$stmt = mysqli_stmt_init($link);
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, "ss", $_POST['password'], $_POST['username']);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while($row = mysqli_fetch_assoc($result){
echo $row['username'] .'<br>';
}
I think it is necessary to add at least one example of prepared statements, just to show that it is not more difficult and it makes your application safer (SQL-injection).
$stmt = $mysqli->prepare('SELECT * FROM users WHERE `password` = ? AND `username` = ?');
$stmt->bind_param("ss", $_POST[password], $_POST[username]);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
// read the result...
$stmt->close();
Be aware that passwords should not be stored plain text, instead one should use the functions password_hash() and password_verify().
You answered your question yourself.
mysqli_real_escape_string() is the way to go.
$sql = 'SELECT * FROM users WHERE `password` = "' . mysqli_real_escape_string($_POST[password]) . '" AND `username` = "' . mysqli_real_escape_string($_POST[username]') . '"';
This is the code that makes the error:
$sql = 'INSERT INTO pedidos (pagado, instalado) VALUES ("'.$_POST['email'].'", "'.$_POST['b'].'") WHERE email="'.$_POST['2'].'"';
$stm = $conn->prepare($sql);
$conn->exec($stm);
That's not the proper way to use prepare and execute. The reason this was created was so that you wouldn't need to put logic and data together and put yourself at risk of an SQL injection attack.
$sql = 'INSERT INTO pedidos (pagado, instalado) VALUES (:pagado, :instalado)';
$stm = $conn->prepare($sql);
$stm->bindParam(':pagado', $_POST['email']);
$stm->bindParam(':instalado', $_POST['b']);
$stm->execute();
It also doesn't make sense to put a WHERE in an INSERT query. You're inserting into your table, you're not getting data.
However, if you're updating data based on other data, then you should use an UPDATE query.
UPDATE pedidos SET pagado=?, instalado=? WHERE email=?
An example of this would be:
$sql = 'UPDATE pedidos SET pagado=:padago, instalado=:instalado WHERE email=:email';
$stm = $conn->prepare($sql);
$stm->bindParam(':pagado', $_POST['email']);
$stm->bindParam(':instalado', $_POST['b']);
$stm->bindParam(':email', $_POST['2']);
$stm->execute();
UPDATE - 2:
$sql = 'INSERT INTO pedidos SET pagado = ?, instalado = ? WHERE email = ?';
$stm = $conn->prepare($sql);
$stm->bindParam(1,$_POST['email']);
$stm->bindParam(2,$_POST['b'] );
$stm->bindParam(3,$_POST['2'] );
$stm->execute(); // here your code generate error
Reason: You put $stm in execute() , which makes an error.
I have this code to select all the fields from the 'jobseeker' table and with it it's supposed to update the 'user' table by setting the userType to 'admin' where the userID = $userID (this userID is of a user in my database). The statement is then supposed to INSERT these values form the 'jobseeker' table into the 'admin' table and then delete that user from the 'jobseeker table. The sql tables are fine and my statements are changing the userType to admin and taking the user from the 'jobseeker' table...however, when I go into the database (via phpmyadmin) the admin has been added by none of the details have. Please can anyone shed any light onto this to why the $userData is not passing the user's details from 'jobseeker' table and inserting them into 'admin' table?
Here is the code:
<?php
include ('../database_conn.php');
$userID = $_GET['userID'];
$query = "SELECT * FROM jobseeker WHERE userID = '$userID'";
$result = mysql_query($query);
$userData = mysql_fetch_array ($result, MYSQL_ASSOC);
$forename = $userData ['forename'];
$surname = $userData ['surname'];
$salt = $userData ['salt'];
$password = $userData ['password'];
$profilePicture = $userData ['profilePicture'];
$sQuery = "UPDATE user SET userType = 'admin' WHERE userID = '$userID'";
$rQuery = "INSERT INTO admin (userID, forename, surname, salt, password, profilePicture) VALUES ('$userID', '$forename', '$surname', '$salt', '$password', '$profilePicture')";
$pQuery = "DELETE FROM jobseeker WHERE userID = '$userID'";
mysql_query($sQuery) or die (mysql_error());
$queryresult = mysql_query($sQuery) or die(mysql_error());
mysql_query($rQuery) or die (mysql_error());
$queryresult = mysql_query($rQuery) or die(mysql_error());
mysql_query($pQuery) or die (mysql_error());
$queryresult = mysql_query($pQuery) or die(mysql_error());
mysql_close($conn);
header ('location: http://www.numyspace.co.uk/~unn_v002018/webCaseProject/index.php');
?>
Firstly, never use SELECT * in some code: it will bite you (or whoever has to maintain this application) if the table structure changes (never say never).
You could consider using an INSERT that takes its values from a SELECT directly:
"INSERT INTO admin(userID, forename, ..., `password`, ...)
SELECT userID, forename, ..., `password`, ...
FROM jobseeker WHERE userID = ..."
You don't have to go via PHP to do this.
(Apologies for using an example above that relied on mysql_real_escape_string in an earlier version of this answer. Using mysql_real_escape_string is not a good idea, although it's probably marginally better than putting the parameter directly into the query string.)
I'm not sure which MySQL engine you're using, but your should consider doing those statements within a single transaction too (you would need InnoDB instead of MyISAM).
In addition, I would suggest using mysqli and prepared statements to be able to bind parameters: this is a much cleaner way not to have to escape the input values (so as to avoid SQL injection attacks).
EDIT 2:
(You might want to turn off the magic quotes if they're on.)
$userID = $_GET['userID'];
// Put the right connection parameters
$mysqli = new mysqli("localhost", "user", "password", "db");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Use InnoDB for your MySQL DB for this, not MyISAM.
$mysqli->autocommit(FALSE);
$query = "INSERT INTO admin(`userID`, `forename`, `surname`, `salt`, `password`, `profilePicture`)"
." SELECT `userID`, `forename`, `surname`, `salt`, `password`, `profilePicture` "
." FROM jobseeker WHERE userID=?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param('i', (int) $userID);
$stmt->execute();
$stmt->close();
} else {
die($mysqli->error);
}
$query = "UPDATE user SET userType = 'admin' WHERE userID=?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param('i', (int) $userID);
$stmt->execute();
$stmt->close();
} else {
die($mysqli->error);
}
$query = "DELETE FROM jobseeker WHERE userID=?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param('i', (int) $userID);
$stmt->execute();
$stmt->close();
} else {
die($mysqli->error);
}
$mysqli->commit();
$mysqli->close();
EDIT 3: I hadn't realised your userID was an int (but that's probably what it is since you've said it's auto-incremented in a comment): cast it to an int and/or don't use it as a string (i.e. with quotes) in WHERE userID = '$userID' (but again, don't ever insert your variable directly in a query, whether read from the DB or a request parameter).
There's nothing obviously wrong with your code (apart from it being insecure with using non-escaped values directly from $_GET).
I'd suggest you try the following in order to debug:
var_dump $userData to check that the values are as you expect
var_dump $rQuery and copy and paste it into phpMyAdmin to see if your query is not as you expect
If you don't find your problem then please post back your findings along with the structure of the tables you're dealing with