• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 266
  • Last Modified:

MySQL Query Using Quotes and Apostrophes

So I posted earlier and got help on running update and insert queries, but now I have a different problem. I want to know what the best way is to run a select query based on an input field.

So for example, I have a field which posts to a page and is included in the WHERE statement: "SELECT * FROM table WHERE UserID=$userID AND Field1='$input'

The $input variable is the field the user enters on the prior page. But if I use an apostrophe, it errors out. How can I do this??

Also..... Quotes work, but I really don't care about that. I'd rather be able to use an apostrophe if I had to choose...
0
brendan-amex
Asked:
brendan-amex
  • 2
2 Solutions
 
xtermCommented:
You will want to use the php function mysql_real_escape_string() to sanitize the data for your query.
0
 
xtermCommented:
I guess I could give an example:

$input=mysql_real_escape_string($input);

Then run your query again and see if it works.
0
 
maeltarCommented:
I use a handy function to sanitise and quote input as required for sql queries...

function check_input($value)
{
// Stripslashes
if (get_magic_quotes_gpc())
  {
  $value = stripslashes($value);
  }
// Quote if not a number
if (!is_numeric($value))
  {
  $value = "'" . mysql_real_escape_string($value) . "'";
  }
return $value;

Open in new window


To use this with your query :
// to prevent [url="http://en.wikipedia.org/wiki/SQL_injection"]SQL Injection[/url] sanitise ALL form input
$userID = check_input($_REQUES['userID']);
$input = check_input($_REQUEST['input']);

// note, quoting variables is no longer required in the sql statement.
$sql = "SELECT * FROM table WHERE UserID=$userID AND Field1=$input";

Open in new window

0
 
brendan-amexAuthor Commented:
I like both answers. Thank you
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now