how to write a php variable on a mysql query - php

I need to write my php variables correctly.
$query2 = mysqli_query($con,"SELECT * FROM palettes LIMIT '$starting_number, $palettes_per_page'");

I don't think you want single quotes on your LIMIT parameters. One way is to use . to concatenate strings.
Since $starting_number and $palettes_per_page are integers, you do not need to escape them. If they were strings, wrap them in mysqli_real_escape_string or mysqli_escape_string to escape special characters.
$query2 = mysqli_query( $con,
"SELECT * FROM palettes LIMIT " .
$starting_number .
"," .
$palettes_per_page );

Just remove the single quote, because double quote can read variable's value
$query2 = mysqli_query($con,"SELECT * FROM palettes LIMIT $starting_number, $palettes_per_page");
Hope this works for you

You could use parameterized queries which also prevent any need to use mysqli_real_escape_string
$stmt = $conn->prepare("SELECT * FROM palettes LIMIT ?, ?'");
$stmt->bind_param("ii", $starting_number, $palettes_per_page);
$stmt->execute();

Related

Using mysql_real_escape_string in IN clause

mysql_real_escape_string adds slashes to the values in IN clause and hence no values are returned. How can I send array values that are escaped using mysql_real_escape_string() in IN clause?
Here is my code:
$names_array = array('dave','smith');
$names = mysql_real_escape_string("'". implode("', '", $names_array) ."'");
$sql = "SELECT * FROM user WHERE user_name IN ($names)";
$results = mysql_query($sql);
Query after mysql_real_escape_string changes like this:
SELECT * FROM user WHERE user_name IN (\'dave\', \'smith\')
I don't want these slashes here in IN clause. Also I don't want the values directly substituted in IN clause.
Thanks in Advance.
This might do it.
$names = "'". implode("', '", array_map('mysql_real_escape_string', $names_array)). "'";
Don't use mysql_real_escape_string; don't use the mysql_* functions directly at all; use ADODB or somesuch; don't concatenate your queries in this way, use placeholders (?) and prepared statements. Your code should look similar to this:
include('/path/to/adodb.inc.php');
$DB = NewADOConnection('mysql');
$DB->Connect($server, $user, $pwd, $db);
# M'soft style data retrieval with binds
$rs = $DB->Execute("select * from user where user_names in ?",array(array('dave','smith')));
while (!$rs->EOF) {
print_r($rs->fields);
$rs->MoveNext();
}

How to escape quotes in a MYSQL query?

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

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

$_SESSION variable in mysql query?

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.

Adding variables in query the right way

Why do this..
$fruit_type = "banana";
mysql_real_escape_string($fruit_type);
$query = "SELECT * FROM posts WHERE fruit = " . $fruit_type . ";
when you can do this..
$fruit_type = "banana";
mysql_real_escape_string($fruit_type);
$query = "SELECT * FROM posts WHERE fruit = $fruit_type;
I know that integers should be encapsulated in single quotes but is it fine to add a variable that contains a string directly?
Adding a string directly, without quotes (and escaped quotes within the value) will not work if that is your question.
The following will work with integers, provided you are matching on an number field, but it will not work with strings:
$query = "SELECT * FROM posts WHERE fruit = $fruit_type";
To match strings, you must enclose them within single quotes, and escape single quotes occurring within the value. The following will not escape quotes contained within the passed variable:
$query = "SELECT * FROM posts WHERE fruit = '$fruit_type'";
At the very least, you should do this:
$query = "SELECT * FROM posts WHERE fruit = " . mysql_real_escape_string($fruit_type);
And at the first opportunity, read about these:
http://php.net/manual/en/pdo.prepared-statements.php
Typically, no. The reason is just this:
$fruit_type = "; DELETE FROM posts;";
There's nothing inherently wrong with the syntax, it's your approach in general. You want to make sure that all user input strings are escaped.
I think you missed the quotes for the string.
$query = "SELECT * FROM posts WHERE fruit = '$fruit_type';
Also, its a good practice to use bind variables in SQL in order to avoid DB query parsing
To late but it will help others
`
$table ="table_Name";
$idx="value";
$sql="SELECT * FROM $table WHERE row_name= '$idx'";
`
execute your query .

Categories