Creating a database query based on the users input from a form? [duplicate]
I have an HTML form that lets the user write what they want to search for. In this case a Name.
The form works, but it's in the php. I don't know what I have to write to get MySQL to search the database for what the user has input.
Here is the line where I get stuck:
$result = mysql_query("SELECT * FROM {$table} WHERE name = 'What do i gonna write
here? (take away the ' ");
I'm using PHP 5.
This should get you on your way using mysqli. The manual can be found here.
This assumes you are POSTing your form, otherwise you can change $_POST to whatever request variable you'll be using. Some sanity checking on the form variable before or after calling mysqli_real_escape_string would also be very helpful (required) in a production environment.
$db = new mysqli("localhost","user","password","database");
if(mysqli_connect_error())
{
printf("Connection failed:%s \n",mysqli_connect_error());
exit();
}
$name = mysqli_real_escape_string($db, $_POST['search']);
$table = 'some_table';
if($result = $db->query("SELECT * FROM $table WHERE name = $name", MYSQLI_ASSOC))
{
while($row = $result->fetch_object())
{
// $row is an associative array
// Do something here
}
}
$db->close();
$sf = stripslashes($_REQUEST['search']);
$sf = mysql_real_escape_string($sf);
$result = mysql_query("SELECT * FROM {$table} WHERE name = '". $sf."'");
while($row = mysql_fetch_array($result)){
//do stuff
}
精彩评论