Properly escaping mysqli query in PHP - php

Uggh, I've had a few beers and I just can't seem to progress.
I'm teaching myself a bit of PHP with MySQL (just because) and this one line just has me stumped:
$user = $mysqli->query ("SELECT id FROM members WHERE username = " . $_SESSION['user_name'] . " LIMIT 1");
I'm sure it's something completely stupid but I need to have the '$_SESSION['user_name']' passed with quotes around it.
Look, I know its a stupid question, apologies in advanced but I can't even get the right Google terms to find what I'm after... sad I know!\
I've tried all combinations of slash escaping and single / double quotes... please help!

You should use prepared statements :)
$stmt = $mysqli->prepare("SELECT id FROM members WHERE username = ? LIMIT 1");
$stmt->bind_param('s', $_SESSION['user_name']);
http://es1.php.net/manual/en/mysqli-stmt.bind-param.php

You're missing the unescaped quotes, and concatenate operators. Try this:
$user = $mysqli->query ("SELECT id FROM members WHERE username = '" . $_SESSION['user_name'] . "' LIMIT 1");
Note the '" . $_SESSION['user_name'] . "' is changed.

$user = $mysqli->query ("SELECT id FROM members WHERE username = '" . $_SESSION['user_name'] . "' LIMIT 1");

As everybody stated before, the following would be a working (but not perfect!) query:
$user = $mysqli->query("SELECT `id` FROM `members` WHERE `username` = '" . $_SESSION['user_name'] . "' LIMIT 1");
But please note: Inserting strings in SQL queries this way is a security risk, since $_SESSION['user_name'] may contain quotes itself, so that somebody attacking your site could execute arbitrary SQL statements! (Search for SQL Injection if you want to get more information on this.)
Using prepared statements as suggested by naoxink is a safer way, but I just want to mention another safe way to insert strings into SQL queries: Use the mysqli::real_escape_string() method:
$user = $mysqli->query("SELECT `id` FROM `members` WHERE `username` = '" . $mysqli->real_escape_string($_SESSION['user_name']) . "' LIMIT 1");

Use this instead
$user = $mysqli->query ("SELECT `id` FROM `embers` WHERE username = '".$_SESSION['user_name']."' LIMIT 0,1");

Related

Single Quote Causes Update SQL to Fail

If I have a user's email address as d'anthony.fredrick#hotmail.com and I use addslashes to make it d\'anthony.fredrick#hotmail.com, the following SQL statement fails.
"UPDATE subscriptions SET sent = '1' WHERE email ='" . $email . "' Limit 1";
The database as the email address is d\'anthony.fredrick#hotmail.com. Why does the UPDATE fail?
Always, always, always escape strings before adding them to queries.
"UPDATE subscriptions SET sent = '1' WHERE email ='" . $dbconn->real_escape_string($email) . "' Limit 1";
If you're using the original mysql API then you'd use mysql_real_escape_string in place of $dbconn->real_escape_string
use mysql_real_escape_string()
UPDATE `subscriptions` SET `sent` = '1' WHERE `email` ='" . mysql_real_escape_string($email) . "' Limit 1";
note: mysql_* has been depreciated. use MySQLi

What is the proper syntax for inserting variables into a SELECT statement?

I believe I have a simple syntax problem in my SQL statement. If I run this code, I get an error in the database query.
$user = $_GET['linevar'];
echo $user; // testing - url variable echos correctly
$sql = "SELECT * FROM `userAccounts` WHERE `name` = $user";
$result = mysql_query($sql) or die("Error in db query");
If I replace $user in the $sql string with 'actualName' or a known record in my table, the code works fine. Am I using the $ variable incorrectly in the SQL string?
You need to surround the value that you're getting from $user with quotes, since it's probably not a number:
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '$user'";
Just as a note, you should also read up on SQL injection, since this code is susceptible to it. A fix would be to pass it through mysql_real_escape_string():
$user = mysql_real_escape_string( $_GET['linevar']);
You can also replace your or die(); logic with something a bit more informative to get an error message when something bad happens, like:
or die("Error in db query" . mysql_error());
You need escape the get input, then quote it.
// this is important to prevent sql injection.
$user = mysql_real_escape_string($_GET['linevar']);
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '$user'";
This should work:
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '" . $user . "'";

Am I using mysql_real_escape_string right?

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';

MySQL Query using $_GET

Ok, maybe I'm a bit overtired, but I can't understand why this isn't working! I have a comments box on my website, with profiles for people who post. I want to show just their posts in the profile. Their profile page is userinfo.php?user=(whatever)
This query is failing:
$query = "SELECT message,`date`,ip,name,website,id
FROM `guestbook_message`
WHERE name=" . intval($_GET['user']) . "
AND deleted=0
ORDER BY `date` DESC";
You are getting the name of the user and casting it directly to integer and then comparing it with name. This does not make sense.
If the $_GET['user'] is the ID of the user, then compare it with the ID and not with the name.
If $_GET['user'] is the username of the user, then you have to put the quotes around the username value. As UserName value is a string, you need to encapsulate it in quotes and remove the intval. Do it like this:
$query = "SELECT message,`date`,ip,name,website,id
FROM `guestbook_message`
WHERE name='" . mysql_real_escape_string($_GET['user']) . "'
AND deleted=0
ORDER BY `date` DESC";
try this:
$name = intval($_GET['user']);
$query = "SELECT message,date,ip,name,website,id
FROM guestbook_message
WHERE name='" .$name. "'
AND deleted=0
ORDER BY date DESC";
$result = mysql_query($query) or die(mysql_error());
Assuming you're using mysql_query() to execute the query, have you checked if the query succeeded?
$query = "SELECT ...";
$result = mysql_query($query) or die(mysql_error());
Doing this will force the script to abort if the query fails and tell you why the query failed.
One thing to note that using $_GET directly in your query leaves you open to SQL injection attacks.
Consider cleaning your input prior to building your SQL statement, or use PDO / Prepared statements.

a very simple query is not working PHP

i have a little problem with a very simple query ,
when i hard code the values in the query its working , but when i use a PHP variable nothing is retrieved , i over check a lot of things including the query , the database
it worth saying that i'm getting the variable from a form by POST and also checked that i'm getting them but when i use them in a query they jst dont work :S
here's my code ..PLZ what am i doing wrong ?!!!!!!!!!!!
<?php
$email = $_POST ['emailEnter'] ;
$password = $_POST ['passwordEnter'];
$connection = mysql_connect('localhost','root','') ;
$db_selected = mysql_select_db("lab5" , $connection) ;
$query = 'select * From user where email="$email" and password="$password" ' ;
$result = mysql_query ($query , $connection);
while($row=mysql_fetch_array($result))
{
echo $row['name'];
}
mysql_close($connection);
?>
You use single quotes in the query variable. Single quotes does not substitute variables - so it looks for literal string $email not the variable email. Either use double quotes or even better use something like PDO which would do the work for you.
You should also sanitize your inputs from SQL/XSS vulnerabilities.
The basic debugging steps are 1. adding
if (!$result) echo "Error: ".mysql_error();
to see any errors from the SQL query and 2. outputting
echo "Query: $query";
to see what the variables contain. One of these will point you to the problem.
Also, your query is vulnerable to SQL injection. You should add a
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password );
after fetching the values from the POST array.
Your error probably resides in the fact that you don’t escape your parameters.
While you are at it, use MySQLi or PDO (maybe even some prepared statements)
Someone mentioned your use of single-quotes, that’s the real error, my bad.
But my advice still stands. Having used prepared statements, you wouldn’t have fell for that mistake
try
$query = 'select * From user where email="' . $email . '" and password="'. $password . '" ' ;
or
$query = "select * From user where email='$email' and password='$password'" ;
Try this instead:
$query = "select * From user where email='" . $email . "' and password='" . $password . "';
Then immediately change that to this instead:
$query = "select * From user where email='" . mysql_real_escape_string($email) . "' and password='" . mysql_real_escape_string($password) . "';
Try
$query = "SELECT * FROM user WHERE email = '".$email."' AND password = '".$password."'";
You've confused the single and double quotes
You have:
$query = 'select * From user where email="$email" and password="$password" ' ;
You want:
$query = "select * From user where email='$email' and password='$password' " ;
Single quotes evaluate to whats literally inside. Double quotes will parse for variables inside. Theres also a curly brace {$variable} syntax you can use.
Suggestions from other posters for using mysql_real_escape or using newer mysqli or PDO are important as well. At the very least use mysql_real_escape on parameters that come from user input.
the problem is the way you are quoting the variables. Suppose that $email= 'some#gmail.com' and $password= 'securenot'.
what we want is the final interpreted string to be the following
select * from user where email='some#gmail.com' and password='securenot'
to achieve this we simply replace the some#gmail.com for $email and securenot for $password and get the following:
select * from user where email='$email' and password='$password'.
and then in php code ...
$query = "select * from user where email='$email' and password='$password'";
hope that is of some help
mysql_fetch_assoc() for associative array. You cannot use normal array as assoc array.
while($row=mysql_fetch_assoc($result))
{
echo $row['name'];
}

Categories