MySQL Select statement - php

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.

Related

Reading String from Variable for SQL Query

SQL newb here...
$db_result = mysql_query("SELECT first_name FROM gamers WHERE comp_id = 'myid'"); works the way I want.
$compid1 = 'myid';
$db_result = mysql_query("SELECT first_name FROM gamers WHERE comp_id = #compid1");
does not yield the same results.
I have also tried $compid1 and various other things, but without success.
Sorry for the simple question, but the answer is still eluding me. Thanks!
UPDATE: Oh yea...the question. How can I use a prestored variable for my WHERE check?
You need to use $ before a variable, not #. And you need to put quotes around it since it's a string:
$db_result = mysql_query("SELECT first_name FROM gamers WHERE comp_id = '$compid1'");
However, it would be best if you stopped using the mysql extension. Use PDO or mysqli, and use prepared statements with parameters. E.g. in PDO it would be:
$stmt = $conn->prepare("SELECT first_name FROM gamers WHERE comp_id = :compid");
$stmt->bindParam(':compid', $compid1);
$stmt->execute();
Enclose the string variable inside a pair of quotes.
$compid1 = 'myid';
$db_result = mysql_query("SELECT first_name FROM gamers WHERE comp_id = '$compid1'");

PHP Query failing, show error?

I have a query on my page that uses a GET variable to pull data from my table...
If I echo my GET var the data is there so im doing something wrong with my query, instead of or die can I show an error in the browser?
// Get USER ID of person
$userID = $_GET['userID'];
// Get persons
$sql = 'SELECT * FROM persons WHERE id = $userID';
$q = $conn->query($sql) or die('failed!');
$sql = "SELECT * FROM persons WHERE id = $userID";
You must use double quotes to use variables inside the query string.
You can also do this:
$sql = "SELECT * FROM persons WHERE id = ".$userID;
What you should do is this (to protect yourself from sql injection):
$safeuid = $conn->prepare($userID);
$sql = "SELECT * FROM persons WHERE id = ".$safeuid;
You can always debug using this at the top of your php page:
ini_set('display_errors',1);
error_reporting(E_ALL);
Have you tried $q = $conn->query($sql) or die($conn->error()); ?
Yes you can, but you should only do it for debugging. Crackers can gain a lot of insight by purposefully feeding bad input and reading the error.
I'm assuming you're using MySQLi; the command is $conn->error(). So your line would be:
$q = $conn->query($sql) or die($conn->error());
Also, what you're doing wrong is you're using single quotes to define $sql. You need to use double quotes to write $userID into the string. So what you want is:
$sql = "SELECT * FROM persons WHERE id = $userID";
or
$sql = 'SELECT * FROM persons WHERE id = ' . $userID;
You need to use double quotes to evaluate variables within the string. That is,
$sql = 'SELECT * FROM persons WHERE id = $userID';
should be
$sql = "SELECT * FROM persons WHERE id = $userID";
Rather than removing the die you should make sure the query is always valid. In other words: validate the userID parameter. $_GET can contain anything the user wants to provide - it could be an array, it could be a string, it could be a string with a malicious payload that can drop your tables. So check it is an integer. If not, return a relevant message to the user.
Not a php expert but you might try:
// Get USER ID of person
$userID = $_GET['userID'];
// Get persons
$sql = 'SELECT * FROM persons WHERE id = $userID';
$q = $conn->query($sql) or die('failed!' . mysql_error());
The error should append to the end of your die message.

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

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 .

PHP json_encode losing my UTF-8 escapes?

I have an array with strings with international characters.
When I save this in the database I loose the backslashes? Why?
$descr_arr = array("héééllo","world");
$js_encoded = json_encode($descr_arr);
print $js_encoded; // "[\"h\u00e9\u00e9\u00e9llo\",\"world\"]"
$sql_query = "UPDATE test_table SET description = '$js_encoded' WHERE id = 0";
$sql_res = mysql_query($sql_query);
// in the description field in the database I find:
// ["hu00e9u00e9u00e9llo","world"]
You didn't escape your database inputs. Always escape!
Here's one way
$sql_query = "UPDATE test_table SET description = '".
mysql_real_escape_string($js_encoded).
"' WHERE id = 0";
Better yet, use a database wrapper like PDO or ADODb, which would take care of the escaping for you. It would look something like this:
$db->Execute("UPDATE test_table SET description =? where id=?",
array($js_encoded, $id));

Categories