I ever see some article that use this { ... } brackets to insert their variable
EX:
$query = $this->pdo->prepare("SELECT * FROM administrator WHERE username = '{$ins}'");
Is it doesn't matter? or what is the difference with this one ?
$query = $this->pdo->prepare("SELECT * FROM administrator WHERE username = '$ins'");
Which is the best way to write the PDO SQL queries?
Neither.
Your SQL code should never contain variable input. You should use parameter binding.
$query = $this->pdo->prepare('SELECT * FROM administrator WHERE username = ?');
$query->execute([$ins]);
To be safe I recommend using single quotes ' ', because string interpolation works only with double quotes.
There might be situations when you would like to use a PHP constant as part of the SQL. In this case you can use simple concatenation.
define('ADMIN_TABLE', 'administrator');
$query = $this->pdo->prepare('SELECT * FROM '.ADMIN_TABLE.' WHERE username = ?');
$query->execute([$ins]);
Related
I have 2 values that I'm suppling my script - I want to search for any one of those datas. How do I write my query like this:
SELECT * FROM table WHERE id = '".$id."' or "name='".$name."';
my problem is escaping the quotes in the query.
Any help will be appreciated.
There are a few ways to do it, a lot of them frowned on but generally I would stick to using MySQLi and using the
mysqli_real_escape_string($id)
function or in OOP
$mysqli = new mysqli('host', 'user', 'pass', 'database');
$id = $mysqli -> real_escape_string($id);
$name = $mysqli -> real_escape_string($name);
$results = $mysqli -> query("SELECT * FROM table WHERE id = '{$id}' or "name='{$name}'");
You may use curly brackets to avoid confusion with escaping characters as follows:
$query = "SELECT * FROM table WHERE id = '{$id}' or name = '{$name}' ";
You may also consider using wildcards such as %$letter% to search for word anywhere in the name field as:
$query = "SELECT * FROM table WHERE id = '{$id}' or name LIKE '%{$name}%' ";
SUGGESTTION:
You should always use id fields as integer for better performance.
Use this fancy function, mayhaps? The examples have what you're looking for.
You've got an extra quote; if you want to stick with your original code (not recommended), try something like this:
$query = "SELECT * FROM table WHERE id = '".$id."' or name='".$name."'";
But really you should be using parameterised queries so that you avoid possible SQL injection security issues!
Write it as:
$name = mysql_real_escape_string($name);
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM table WHERE id = '$id' or name= '$name' ";
Because you started with double quotes the single quotes are part of the query and the $vars are expanded.
Example: The follwing query give me Quotes error in the field -> GET['email']
mysql_query(" select * from user_info where user_mail = '$_GET['email']' ")
You might want to escape the string first:
$_GET['email'] = mysql_real_escape_string($_GET['email']);
And then:
mysql_query(" select * from user_info where user_mail = '" . $_GET['email'] . "' ");
The dots put the strings together.
Use accolades like this.
mysql_query(" select * from user_info where user_mail = '{$_GET['email']}' ")
Also, make sure to escape your user input. Your current setup looks like it is vulnerable to SQL injection. Use http://php.net/manual/en/function.mysql-real-escape-string.php to clean up your user input (like $_GET values)
It's not really an answer to your question, but I'd strongly advise you to use PDO or mysqli prepared statements. Thus, your original problem -- the escaping parameter strings -- will be automatically taken care of.
If you do not want to follow this advice, do this:
$email = mysql_real_escape_string($_GET['email']);
mysql_query("select * from user_info where user_mail = '$email';");
You don't need quotation marks for associative array field names if you are already inside a doubly-quoted string:
$str = "Hello $_GET[email].";
Use it this way:
$SQL = "SELECT * FROM user_info WHERE user_mail = '".$_GET['email']."'";
mysql_query($SQL);
But I strongly advice to take some security actions with $_GET['email'], like this:
$email = mysql_real_escape_string($_GET['email']);
$SQL = "SELECT * FROM user_info WHERE user_mail = '".$email."'";
mysql_query($SQL);
Is this the right way to use mysql_real_escape_string? I was using $GET but a friend told me to make it safer with real_escape_string:
$id = intval($_GET['id']);
$result = mysql_query("SELECT *
FROM products
WHERE id = $id") or die("err0r");
if(!$result) mysql_real_escape_string($id); {
No, you normally use mysql_real_escape_string to prepare variables for use in a query, but in your case:
you already use intval;
you use it in the wrong place.
You don't need it in your example.
No. That is entirely wrong, and I can't quite understand what you're intending the call to do.
The purpose of mysql_real_escape_string is to avoid SQL injection, which is one of the biggest security risks in a website. It stops your users giving input that manipulates the SQL in evil ways. For instance:
$sql = "SELECT FROM users WHERE username = '" . $_GET['username'] . "'";
If I put lonesomeday' or 'a' = 'a into $_GET['username'], your query becomes
SELECT FROM users WHERE username = 'lonesomeday' or 'a' = 'a'
and obviously arbitrary SQL could then be executed. mysql_real_escape_string escapes unsafe characters (such as ' in that example), so that they can't be used in this way.
$sql = "SELECT FROM users WHERE username = '" . mysql_real_escape_string($_GET['username']) . "'";
// SELECT FROM users WHERE username = 'lonesomeday\' or \'a\' = \'a'
The quotes are now escaped. so the query can't be manipulated into doing evil things.
With all that said, in this case, intval does all you need. It also ensures that nothing that is not an integer can be in $id, so your code is safe here from SQL injection.
NO, you need to escape before quering
$id = intval($_GET['id']);
$result = mysql_query("SELECT *
FROM products
WHERE id = '" . mysql_real_escape_string($id) . "'") or die("err0r");
if(!$result) {
}
Use:
$query = sprintf("SELECT *
FROM products
WHERE id = %d",
intval($_GET['id']));
$result = mysql_query($query) or die("err0r");
You use mysql_real_escape_string before the value is used in the query, otherwise you're not handling the SQL injection attack.
you want to escape it before you stick it in a query (Before it interacts with DB so you don't get injections).
// check if your $_GET is not empty otherwise you
// will run into "undefined variable"
if(!empty($_GET['id'])){
$id = intval($_GET['id']);
// to simplify you can escape here,
// or to be a bit more complex, you can escape in the query line.
$id = mysql_real_escape_string($id);
$result = mysql_query("SELECT *
FROM products
WHERE id = '$id'") or die("err0r");
}
else
print 'No ID';
Whenever I try a query like:
mysql_query("SELECT * FROM data WHERE `user`=$_SESSION['valid_user'] LIMIT 1");
it doesn't work. Why? I escaped the variable, then tried it without, and tried putting quotes around the variable. I know i can do:
$user = $_SESSION['valid_user'];
but shouldn't it work without? Thanks.
THE ANSWER:
PHP can't recognize $_SESSION['valid_user'] due to the single quotes. So either
use curly braces {} or take our the single quotes.
Thanks for helping me everyone.
PHP can't recognise variables inside a string that have square brackets and so on, you have to wrap it in curly brackets to get it to recognise it.
mysql_query("SELECT * FROM data WHERE user={$_SESSION['valid_user']} LIMIT 1");
However - You should always escape any data going into a SQL query, try the example below.
$validUser = mysql_real_escape_string($_SESSION['valid_user']);
mysql_query("SELECT * FROM data WHERE user='$validUser' LIMIT 1");
Arrays/objects must be included in strings slightly differently:
mysql_query("SELECT * FROM data WHERE `user`={$_SESSION['valid_user']} LIMIT 1");
or, you can drop out of the string and concatenate it in:
mysql_query("SELECT * FROM data WHERE `user`=" . $_SESSION['valid_user'] . " LIMIT 1");
Same but with PDO and bound parameters
$stmt = $pdo->prepare('SELECT * FROM data WHERE `user`=:user LIMIT 1');
$stmt->execute(array(':user'=>$_SESSION['valid_user']));
$row = $stmt->fetch();
Note: you can't make LIMIT 1 into a bound parameter because LIMIT is not part of the standard sql and PDO has issues with it, so it has to be bound like this
$stmt = $pdo->prepare('SELECT * FROM data WHERE `user`=:user LIMIT :limit');
$limit = 1;
$user = $_SESSION['valid_user'];
$stmt->bindParam(':user', $user, PDO::PARAM_STR);
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch();
or like this
$limit = 1;
$stmt = $pdo->prepare('SELECT * FROM data WHERE `user`=:user LIMIT '.(int)$limit);
$stmt->execute(array(':user'=>$_SESSION['valid_user']));
$row = $stmt->fetch();
this is the way that I was taught to do it, so I wanted to point it out
try this:
mysql_query("SELECT * FROM data WHERE `user`={$_SESSION['valid_user']} LIMIT 1");
also remember to put session_start on the top of the page
your array is in this context just part of a string and nothing else. To mark an expression as what it is you have to embrace it curly ;-) works only with double quoted strings, though.
mysql_query("SELECT * FROM data WHERE user={$_SESSION['valid_user']} LIMIT 1");
You need to use the string concatenation operator '.' before and after the variable.
mysql_query("SELECT * FROM data WHERE `user`=".$_SESSION['valid_user']." LIMIT 1");
Since you are using a double quoted string, you can also use {} around the variable instead of string concatenation:
mysql_query("SELECT * FROM data WHERE `user`={$_SESSION['valid_user']} LIMIT 1");
By the way, you probably should look into the mysqli (http://php.net/manual/en/book.mysqli.php) library, and be using mysqli::real_escape_string (http://www.php.net/manual/en/mysqli.real-escape-string.php) to ensure that any non-literal variable values are properly escaped.
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING is the message. It came up from this line of code:
$query = ("SELECT *
FROM users
WHERE user_name = $_POST['user_name']
& password = $_POST['password']
& user_type = $_POST['user_type']");
Does anyone out there know the meaning of all this? If so, does anyone know how to deal with this?
Use:
$query = sprintf("SELECT u.*
FROM USERS u
WHERE u.user_name = '%s'
AND u.password = '%s'
AND u.user_type = '%s' ",
mysql_real_escape_string($_POST['user_name']),
mysql_real_escape_string($_POST['password']),
mysql_real_escape_string($_POST['user_type']) );
$result = mysql_query($query);
Reference
sprintf
You can't interpolate a $_POST like that. You need to wrap them with braces ({ and }). You also don't need to quote the key names when already in a string like that.
You should also quote those values, and swap & with AND.
You also need a ; at the end.
You also don't need to wrap it in parenthesis.
$query = "SELECT *
FROM users
WHERE user_name = '{$_POST[user_name]}'
AND password = '{$_POST[password]}'
AND user_type = '{$_POST[user_type]}'";
But...
...don't interpolate user input directly like that. Use a escaping mechanism.
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$user_type = mysql_real_escape_string($_POST['user_type']);
$query = "SELECT *
FROM users
WHERE user_name = '$username'
AND password = '$password'
AND user_type = '$user_type'";
I would recommend using PDO and binding parameters instead of building the SQL yourself.
Also, it would appear you your passwords that are user inputted are being directly used to compare in the database. Use some form of one way message digest, such as bcrypt.
For interpolation of one-dimensional array values into strings, use this syntax:
"foo = $_POST[bar]"
Notice no quotes.
For interpolating nested arrays or generally using the normal syntax, use braces:
"foo = {$_POST['bar']}"
In no case though do any of this with SQL queries, you need to escape values before plugging them into queries. So, do this:
$query = sprintf('SELECT foo FROM bar WHERE baz = "%s"',
mysql_real_escape_string($_POST['baz']));
Make sure to account for SQL injection.
Try:
$username = mysql_real_escape_string($_POST["user_username"]);
$password = mysql_real_escape_string($_POST["user_password"]);
$type = mysql_real_escape_string($_POST["uesr_type"]);
$query = "SELECT * FROM users WHERE user_name='$username' AND password='$password' AND
user_type='$type'";
$result = mysql_query($query);
I'd also suggesting reading the manual a bit: http://us.php.net/manual/de/language.types.string.php#language.types.string.parsing. That link will explain to you how PHP parses variables in strings.
$username = mysql_real_escape_string($_POST["user_username"]);
$password = mysql_real_escape_string($_POST["user_password"]);
$type = mysql_real_escape_string($_POST["user_type"]);
mysql_query("SELECT * FROM users WHERE user_name='$username' AND user_password='$password' AND user_type='$type' LIMIT 1");