dynamic SQL built in a PHP form - problem with character values

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jej1216
    New Member
    • Aug 2006
    • 40

    #1

    dynamic SQL built in a PHP form - problem with character values

    I have a multi-field search PHP page, and the resulting PHP page builds dynamic WHERE statements to do the database search. The first field is numeric, and works:
    [code=php]
    $facility = $_REQUEST['fac_id'];
    if ($facility != '') {
    echo "Facility: ".$facility."&n bsp;";
    $where .= ' AND fac_id='.$facil ity.'';
    }
    [/code]
    This code builds SQL that looks like this:
    SELECT fac_id, room_descr, person_type, severity FROM incidents WHERE 1=1 AND fac_id=000852 ORDER BY fac_id, room_descr, person_type, severity.
    But when the field is character, this same code does not work:
    [code=php]
    $persontype = $_REQUEST['person_type'];
    if ($persontype != '') {
    echo "Persontype : ".$personty pe. " ";
    $where .= ' AND person_type ='.$persontype. '';
    }
    [/code]
    This produces the following SQL:
    SELECT fac_id, room_descr, person_type, severity FROM incidents WHERE 1=1 AND person_type =Outpatient ORDER BY fac_id, room_descr, person_type, severity
    And gives the error:
    Error: Unknown column 'Outpatient' in 'where clause'.
    If I copy the SQL produced and add quotes around Outpatient it runs fine in phpmyadmin.

    How do I add single quotes to the person_type field?

    TIA,

    jej1216
  • jej1216
    New Member
    • Aug 2006
    • 40

    #2
    I got it.

    [code=php]
    $persontype = $_REQUEST['person_type'];
    if ($persontype != '') {
    echo "Persontype : ".$personty pe. " ";
    $where .= " AND person_type ='".$persontype ."'";
    }
    [/code]
    I knew it was a small thing.

    jej1216

    Comment

    • pbmods
      Recognized Expert Expert
      • Apr 2007
      • 5821

      #3
      Good thinking.

      One thing I must caution you about, though: What if $_REQUEST['person_type'] were "'\cDROP TABLE `incidents`"?

      Comment

      Working...