How should I write PHP $_POST variable in a mysql_query function? - php

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]') . '"';

Related

Prepared Statements Mysql not working

I am trying to use prepared statements to select data from a table as the following. This method does not work.
$sql = "SELECT * FROM `usrs` WHERE `username` = ? ";
$statement = $this->conn->prepare($sql);
if (!statement)
{
throw new Exception($statement->error);
}
$statement->bind_param("s",$username);
$returnValue = $statement->execute();
return $returnValue;
$sql should be in the following format.
$sql = "SELECT * FROM `usrs` WHERE `username` = 'username' ";
however the above code does not place single quotes ' ' around username
I need to place username between two single quotes ' ' as shown. if I use just
$sql = "SELECT * FROM `usrs` WHERE `username` = username "
it does not work.
any suggesstions how to do that.
Read this carefully:
bool mysqli_stmt::execute ( void )
it means it returns boolean - that is not a usable object or an array.
You've to fetch the statement.
Here's the fix:
$sql = "SELECT * FROM `usrs` WHERE `username` = ? LIMIT 1";
$statement = $this->conn->prepare($sql);
$statement->bind_param("s",$username);
if ($statement->execute()) {
$result = $statement->get_result();
return $result->fetch_assoc();
}
return null;
P.S. Thank You #Phil for fixing my mistakes in my answer

Using prepared MySQLi statements to produce associative array

I've read a few related questions to this, but in each case I've been unable to get their code to work in my context.
Following some injection attempts, I am trying to implement prepared statements into my site, while changing as little code as possible. Importantly, I want the responses to my SELECT queries to by outputted as associative arrays: e.g. $row['name'].
Here is an example of code that I have right now (without preprepared statements):
// Create connection
$db = new mysqli('localhost', 'username', 'password', 'seatingplan');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
// Get class name
$sql = <<<SQL
SELECT *
FROM `class`
WHERE `userid` = '$userid'
AND `classid` = '$classid'
SQL;
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
$classname = $row['classname'] ;
}
Is there a straightforward way of adapting this for prepared statements? Based on other questions, this is as far as I've got (but it doesn't work - it only returns 1 for each row, rather than the actual variable):
$stmt = $db->prepare("SELECT *
FROM `class`
WHERE `userid` = ?
AND `classid` = ?");
$stmt->bind_param("ss", $userid, $classid);
$result = $stmt->execute();
$stmt->store_result();
while($data = $stmt->fetch()){
echo $data ;
}
Just define the array and use it for example in your code:
$stmt = $db->prepare("SELECT *
FROM `class`
WHERE `userid` = ?
AND `classid` = ?");
$stmt->bind_param("ss", $userid, $classid);
$stmt->execute();
$result=$stmt->get_result();
$row= array();
$i=0;
while ($data = $result->fetch_assoc())
{
$row[$i]['name']=$data['name'];
$i++;
}
echo $row;

Mysqli update query doesn't work

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.

Returning a Boolean Value via PDO Query

I am attempting with no success to return a Boolean Value from the following PHP/PDO call back to jQuery/AJAX:
$db = new PDO('mysql:host=' . $dbhost . ';dbname=' . $dbname, $dbuser, $dbpass);
$sql = "SELECT COUNT(*)" .
"FROM bu_users" .
"WHERE user_email = :email";
$stmt = $db->prepare($sql);
$stmt->execute(array(':email' => $_GET[reg_email]));
if(!$stmt){
$result = $stmt->errorInfo();
} else {
$result = $stmt->fetchColumn();
}
print_r($result);
I am outputting my results via console.log but am only receiving empty responses whether the email matches a database row or not. Any help would be appreciated. Thanks.
SQL syntax problems:
$sql = "SELECT COUNT(*)" .
"FROM bu_users" .
^---
"WHERE user_email = :email";
^---
You're lacking spaces at the indicated spots, and your query ends up looking like:
SELECT COUNT(*)FROM bu_usersWHERE user_email = :email;
^^-- ^^--
Don't generate multiline strings like that. It's far too easy to make silly mistakes like this. At least use a HEREDOC:
$sql = <<<EOL
SELECT COUNT(*)
FROM bu_users
WHERE user_email = :email
EOL;
No need for concatentation, automatic multi-line usage, and you can nicely format your SQL as well.
$stmt = $db->prepare("SELECT 1 FROM bu_users WHERE user_email = ?");
$stmt->execute(array($_GET['reg_email']));
echo json_encode((bool)$stmt->fetchColumn());

PHP: PDO bindValue() causes 0 results to be returned

I've having some troubles with the PDO bindValue() function. Whenever I seem to use it, my queries always return 0 results. However it works fine if I put $user and $pass straight into the sql without the use of bindValue()
$user is a string
$password is a sha1() hash
public function login($user, $pass) {
global $CMS;
$sql = "SELECT `username,`password` FROM `" . TB_PREFIX . "users` WHERE `username` = ':user' AND `password` = ':pass'";
$query = $CMS->prepare_query($sql);
$query->bindValue(':user', $user, PDO::PARAM_STR);
$query->bindValue(':pass', $pass, PDO::PARAM_STR);
$query->execute();
# User successfully authenticated
if ($query->rowCount() == 1) {
# Get all data from DB and populate class variables
self::populate_user_data($user);
session_register($user . "-" . base64_encode($_SERVER['REMOTE_ADDR']));
return true;
}
# User failed authentication
return false;
}
You should not put the quotes around the values yourself, they will be added (if needed, such as in the case of strings - this case):
$sql = "SELECT `username,`password` FROM `" . TB_PREFIX . "users`
WHERE `username` = :user AND `password` = :pass";
The placeholders in a prepared statement must not be quoted; PDO is already doing all the quoting. You want:
$sql = "SELECT `username,`password` FROM `" . TB_PREFIX . "users` " .
"WHERE `username` = :user AND `password` = :pass";
When using prepared statements, the values get escaped automagically.
This means, that you don't have to set quotes around the arguments.
try:
$sql = "SELECT `username,`password` ".
"FROM `" . TB_PREFIX . "users` ".
"WHERE `username` = :user AND `password` = :pass";
and you should be fine.
As a side note though: you should NEVER store user passwords literally. Check this excellent article: You're Probably Storing Passwords Incorrectly

Categories