Eariler I wrote this topic: http://www.daniweb.com/web-development/php/threads/482142/searching-using-optional-parameters and I got ideas and got to this point with help of another guy:
<?php
$whereClause = "WHERE ";
foreach($_POST as $k => $v ){
if( $v != "" ){
$whereClause = $whereClause . $k . "='" . $v . "' AND ";
}
}
$db = new PDO('mysql:host=localhost;dbname=petrzilk_test;charset=utf8', 'petrzilk_dbAdmin', '***********'); // Connecting to Database
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Error statement
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$query = $db->prepare("'SELECT * FROM VolunDB " . $whereClause . " 1 = 1'");
$query->execute();
$result = $query->fetch(PDO::FETCH_OBJ);
?>
But I get an error that is:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''SELECT * FROM VolunDB WHERE fname='andy' AND 1 = 1'' at line 1' in /home/petrzilk/public_html/Database/testSearch.php:14 Stack trace: #0 /home/petrzilk/public_html/Database/testSearch.php(14): PDO->prepare(''SELECT * FROM ...') #1 {main} thrown in /home/petrzilk/public_html/Database/testSearch.php on line 14
Any help?
Also how would I go about securing this code from injection? I tried using a filtered input but I can't get it to work the way the foreach is set up.