简体   繁体   中英

MySQL query based on user input

I have a DB table. I want to make a text input where the user can input the "uid" and the query will return the row associated with that uid.

So let's say I have something like this:

$query = "SELECT name,age FROM people WHERE uid = '2' LIMIT 0,1";
$result = mysql_query($query);
$res = mysql_fetch_assoc($result);

echo $res["age"];

how would I modify that query to something like..

SELECT name, age 
  FROM people 
 WHERE uid = $_POST['blahblah'] LIMIT 0,1

Thanks in advance for your help!

In reality...

// Read input from $_POST
$uid = (isset($_POST['uid']) ? $_POST['uid'] : '');

// Build query.  Properly escape input data.
$query = 
  "SELECT name,age " .
  "FROM people " .
  "WHERE uid = '" . mysql_real_escape_string($uid) . "' " . 
  "LIMIT 0,1";

Its advisable to escape characters in the variable for security reasons. Take a look at this document for some of the reasons:

http://en.wikipedia.org/wiki/SQL_injection

To save from SQL injection attack, use:

$search_query = mysql_real_escape_string($_POST['blahblah']);

$query  = "SELECT name, age FROM people WHERE uid = '".$search_query."' LIMIT 0 , 1";

There are so many ways to do the same But first escape it and store it in one variable

$blahblah = mysql_real_escape_string($_POST['blahblah']);

And then There are

First: As @Mett Lo mentioned:

$query = "SELECT name,age FROM people WHERE uid = '" . $blahblah . "' LIMIT 0,1";

Second:

$query = "SELECT name,age FROM people WHERE uid = '{$blahblah}' LIMIT 0,1";

Third:

$query = "SELECT name,age FROM people WHERE uid = '$blahblah' LIMIT 0,1";

and if blahblah is an int value in db table then Fourth:

$query = "SELECT name,age FROM people WHERE uid = $blahblah LIMIT 0,1";

You may use the sprintf function to create the query.

$query = sprintf("SELECT name,age FROM people WHERE uid = '%s' LIMIT 0,1",
         $_POST['blahblah'] );

The rest will be the same. It is highly recommended that you escape the $_POST data before running the query to prevent SQL attacks. You may re phrase the query as follows.

$query = sprintf("SELECT name,age FROM people WHERE uid = '%s' LIMIT 0,1",
         mysql_escape_string($_POST['blahblah']) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM