2

Below is my code...

I am trying to create search with multiple parameters in php pdo....with Multiple if else condition...in singlw query...

plz help ...to make this...how can i do this with php pdo...

  <?php
$db=new PDO('mysql:host=localhost;dbname=circulation_scheme_prepaid','root','');
if(isset($_POST['Submit']))
{   
$result=$db->prepare('SELECT * FROM receipt_entry WHERE');
    if($_POST['book']!='')
    {
         $result->bindParam(':book',$_POST['book']);
    }    
$result->execute(); 
$data = $result->fetchAll();
}
?>

I nned to make above code like this..

<?php
require_once("includes/config.php");
if(isset($_POST['search']))
{   
    $sql = "SELECT * FROM properties WHERE";

    if($_POST['location']!='')
    {
        $location = $_POST['location'];
        $sql .= " location = '$location' AND";
    }

    if($_POST['purpose']!='')
    {
        $purpose = $_POST['purpose'];
        $sql .= " purpose = '$purpose' AND";
    }
    $sql = substr($sql, 0 ,-3); 

$query = mysql_query($sql);
while($row = mysql_fetch_array($query,MYSQL_ASSOC))
        {
            $rows[] = $row;
        }

}
?>
2
  • 1
    I suspect what you actually want to know is whether to add ' where ' or ' and ' to the current sql before appending the new test to the current sql string. Commented Mar 11, 2015 at 16:29
  • yes sir,,exactly.... Commented Mar 11, 2015 at 16:46

1 Answer 1

1

You can try something like this :

if (isset($_POST['search'])) {
  $sql = 'SELECT * FROM properties';
  $where = array();
  $params = array();

  if (!empty($_POST['location'])) {
    $where[] = "location = :location";
    $params[':location'] = $_POST['location'];
  }

  if (!empty($_POST['purpose'])) {
    $where[] = "purpose = :purpose";
    $params[':purpose'] = $_POST['purpose'];
  }

  if(count($where) > 0)
      $sql .= ' WHERE ' . implode(' AND ', $where);

  $stmt = $db->prepare($sql);

  foreach($params as $param => $value) {
    $stmt->bindParam($param, $value);
  }

  $stmt->execute();
  $data = $stmt->fetchAll();

  print_r($data);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Using this method, I think you'll need bindValue instead of bindParam. Alternatively, you could use $stmt->bindParam(":".$param,$params[$param]) or generate the foreach value by reference. Incidentally, a little explanation of your solution would also be helpful.

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.