Selecting values from MySQL with PHP

Discussion in 'PHP' started by Silvers, Mar 13, 2009.

  1. #1
    So I have a php file called extract_values.php .
    In it I have the next codes :
    <?php
    require_once('config.php');
    
    $requestSQL = 'SELECT * FROM database WHERE username=$user';
    $result = mysql_query($requestSQL);
    while ($rand = mysql_fetch_array($result)) {
    echo $rand['specificrow'];
    }
    ?>
    Code (markup):
    Now here's the catch , I want $user to be setted from outside , something like this :
    
    $user = $_GET['user'];
    
    Code (markup):
    and ofcourse , I will set the user from the url :
    website.com/extract_values.php?user=batman
    Code (markup):
    so that the php will extract FROM database WHERE username=batman .

    So what's the problem ? I don't know ( well .. it doesn't work :( ) how to format the $user in that php code to select from Mysql .
    The next code doesn't work :
    $requestSQL = 'SELECT * FROM database WHERE username=$user';
    Code (markup):
    it could be because I need something like .$name. or what ?
     
    Silvers, Mar 13, 2009 IP
  2. SmallPotatoes

    SmallPotatoes Peon

    Messages:
    1,321
    Likes Received:
    41
    Best Answers:
    0
    Trophy Points:
    0
    #2
    $requestSQL = "select * from database where username = '" . mysql_real_escape_string($_GET['user']) . "'";
     
    SmallPotatoes, Mar 13, 2009 IP
  3. ActiveFrost

    ActiveFrost Notable Member

    Messages:
    2,072
    Likes Received:
    63
    Best Answers:
    3
    Trophy Points:
    245
    #3
    $requestSQL = "SELECT * FROM database WHERE username='$user'";
    PHP:
     
    ActiveFrost, Mar 13, 2009 IP
  4. Silvers

    Silvers Well-Known Member

    Messages:
    675
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    108
    #4
    Thanks ! It worked with SmallPotatoes code :)
    @ActiveFrost : I think I tryed that one but it didn't work ... :( thank you also.
     
    Silvers, Mar 13, 2009 IP
  5. ActiveFrost

    ActiveFrost Notable Member

    Messages:
    2,072
    Likes Received:
    63
    Best Answers:
    3
    Trophy Points:
    245
    #5
    What I wrote is exactly how PHP/MySQL works ! It can't fail ( in case if it does, your server is too old to handle it :D ).
     
    ActiveFrost, Mar 13, 2009 IP
  6. SmallPotatoes

    SmallPotatoes Peon

    Messages:
    1,321
    Likes Received:
    41
    Best Answers:
    0
    Trophy Points:
    0
    #6
    ActiveFrost: You didn't guard the string literal in the query ($user) against special characters. Will fail with some values of $user, and also it's bad security practice.
     
    SmallPotatoes, Mar 13, 2009 IP