1
http://localhost/?area=characters&name=Michal+Stroganof



$result = mysql_query("SELECT * from players WHERE name = '$_GET[name]'");

while ($row = mysql_fetch_assoc($result)) {

    echo "Name: " .$row['name']. "<br>";
    echo "Level: " .$row['level']. "<br>";

}

This is all code of my characters.php

If the get variable "name" is not included in the URL i want to show a search form that searches the table players. How would I do this?

4
  • 10
    Read on about SQL injections: unixwiz.net/techtips/sql-injection.html Commented Nov 16, 2009 at 23:01
  • 2
    It is probably the case that your example is just for simplicity's sake, but if it is live code please research SQL Injection and Prepared Statements. Commented Nov 16, 2009 at 23:01
  • use an input function to filter input and avoid sql injection type problems, as well as escaping the input when it gets put into the sql, as jheddings mentions above! never trust user data. Commented Nov 16, 2009 at 23:02
  • Err, as jheddings mentions below, that is. Commented Nov 16, 2009 at 23:04

3 Answers 3

9

Do you mean just to change your SQL string like so?

$sql = 'SELECT * from players';
if (isset($_GET['name'])) {
    $safename = mysql_real_escape_string($_GET['name']);
    $sql .= " WHERE name='$safename'";
}
$result = mysql_query($sql);

Be sure to sanitize your SQL!

Sign up to request clarification or add additional context in comments.

Comments

5

Use isset():

if (isset($_GET['name'])) {
    // your above code
} else {
    // display form        
}

Comments

1

Quick and dirty:

<?php
if (!isset($_GET['name']))
{
    echo  '<form action="'. $_SERVER['PHP_SELF'] .'" method="GET">'
         .'<input type="text" name="name" />'
         .'</form>';
}
else
{
    // your current code that queries your database here
}
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.