1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Select query using four text boxes

Discussion in 'PHP' started by sunilgeorge, May 13, 2008.

  1. #1
    hello everybody,

    pls help me.
    I've got four text boxes for searching result from mysql database using php select query. User may leave any one or all text boxes empty or enter values in all text boxes. Initially all text boxes are empty. How to write the select query.

    Thnx in advance
     
    sunilgeorge, May 13, 2008 IP
  2. crath

    crath Well-Known Member

    Messages:
    661
    Likes Received:
    33
    Best Answers:
    0
    Trophy Points:
    100
    #2
    SELECT * FROM `tableName` WHERE `fieldName` = '$userVariable';

    ??
     
    crath, May 13, 2008 IP
  3. daboss

    daboss Guest

    Messages:
    2,249
    Likes Received:
    151
    Best Answers:
    0
    Trophy Points:
    0
    #3
    try this:

    
    $table = "TABLE"; // enter your database table here
    $field1 = "FIELD1"; // enter the name of criteria field 1 in your table here
    $field2 = "FIELD2"; // enter the name of criteria field 2 in your table here
    $field3 = "FIELD3"; // enter the name of criteria field 3 in your table here
    $field4 = "FIELD4"; // enter the name of criteria field 4 in your table here
    
    $sql = "SELECT * FROM " . $table;
    
    if($_POST[['textbox1'] != "" || $_POST[['textbox2'] != "" || $_POST[['textbox3'] != "" || $_POST[['textbox4'] != "") {
      $sql = $sql . " WHERE "
    }
    
    if($_POST[['textbox1'] != "") {
      $sql = $sql . $field1 . " = '" . $_POST[['textbox1'] . "' AND ";
    }
    
    if($_POST[['textbox2'] != "") {
      $sql = $sql . $field2 . " = '" . $_POST[['textbox2'] . "' AND ";
    }
    
    if($_POST[['textbox3'] != "") {
      $sql = $sql . $field3 . " = '" . $_POST[['textbox3'] . "' AND ";
    }
    
    if($_POST[['textbox4'] != "") {
      $sql = $sql . $field4 . " = '" . $_POST[['textbox4'] . "' AND" ;
    }
    
    $sql = substr($sql, 0, strlen($sql) - 5);
    
    Code (markup):
     
    daboss, May 13, 2008 IP
    wisdomtool likes this.
  4. crath

    crath Well-Known Member

    Messages:
    661
    Likes Received:
    33
    Best Answers:
    0
    Trophy Points:
    100
    #4
    You have an extra [ after each $_POST[, and, this is open to sql injection.

    htmlspecialchars($var);
     
    crath, May 13, 2008 IP
  5. sunilgeorge

    sunilgeorge Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Thanks daboss
    Your code is working.
    Excellent
    Thank you so much
     
    sunilgeorge, May 14, 2008 IP