PHP: prepared statement, IF statement help needed

前端 未结 2 1393
孤城傲影
孤城傲影 2021-01-22 13:48

I have the following code:

$sql = \"SELECT name, address, city FROM tableA, tableB WHERE tableA.id = tableB.id\";

if (isset($price) ) {
    $sql = $sql . \' AND         


        
相关标签:
2条回答
  • 2021-01-22 14:15

    Instead of if else just use PHP ternary operator

         if (isset($_POST['statusID']))
    {
      $statusID = $_POST['statusID'];
    }
    else
    {
      $statusID = 1;
    

    }

    instead of that you can do:

     $statusID =  (isset($_POST['statusID'])) ? $_POST['statusID'] : 1;
    

    The format of the ternary operator is: $variable = condition ? if true : if false

    The beauty of it is that you will shorten your if/else statements down to one line and if compiler ever gives you errors, you can always go back to that line instead of 3 lines.

    0 讨论(0)
  • 2021-01-22 14:16

    This is very similar to a question a user asked me recently the forum for my book SQL Antipatterns. I gave him an answer similar to this:

    $sql = "SELECT name, address, city FROM tableA JOIN tableB ON tableA.id = tableB.id";
    
    $params = array();
    $where = array();
    
    if (isset($price) ) {
        $where[] = '(price = :price)';
        $params[':price'] = $price;
    }
    if (isset($sqft) ) {
        $where[] = '(sqft >= :sqft)';
        $params[':sqft'] = $sqft;
    }
    if (isset($bedrooms) ) {
        $where[] = '(bedrooms >= :bedrooms)';
        $params[':bedrooms'] = $bedrooms;
    }
    
    if ($where) {
      $sql .= ' WHERE ' . implode(' AND ', $where);
    }
    
    $stmt = $dbh->prepare($sql);
    
    $stmt->execute($params);
    $result_set = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    0 讨论(0)
提交回复
热议问题