Reputation: 13
i have multiple POST data fields in a form and want to query to mysql database, if just one POST data field is entered every thing is working, but if theres two or more fields i get error because i need to enter AND between my questions.
$sql ="SELECT * FROM `medlem` WHERE";
if(!empty($_POST[fnamn])){
$a=mysql_real_escape_string($_POST['fnamn']);
$sql .= " `Fornamn` LIKE '%$a%'";
}
if(!empty($_POST[enamn])){
$a=mysql_real_escape_string($_POST['enamn']);
$sql .= " `Efternamn` LIKE '%$a%'";
}
if(!empty($_POST[adress])){
$a=mysql_real_escape_string($_POST['adress']);
$sql .= " `adress` LIKE '%$a%'";
}
if(!empty($_POST[postnr])){
$a=mysql_real_escape_string($_POST['postnr']);
$sql .= " `postnr` LIKE '%$a%'";
}
if(!empty($_POST[stad])){
$a=mysql_real_escape_string($_POST['stad']);
$sql .= " `stad` LIKE '%$a%'";
}
if(!empty($_POST[pnr])){
$a=mysql_real_escape_string($_POST['pnr']);
$sql .= " `pnr` LIKE '%$a%'";
}
if(!empty($_POST[tfn])){
$a=mysql_real_escape_string($_POST['tfn']);
$sql .= " `tfn` LIKE '%$a%'";
}
if(!empty($_POST[mobil])){
$a=mysql_real_escape_string($_POST['mobil']);
$sql .= " `mobil` LIKE '%$a%'";
}
if(!empty($_POST[epost])){
$a=mysql_real_escape_string($_POST['epost']);
$sql .= " `epost` LIKE '%$a%'";
}
If a user have filled two post fields the sql i get "SELECT * FROM medlem
WHERE FornamnLIKE 'foo' Efternamn
LIKE 'bar', and there is a missing AND between them.
Is there an easy solution to this problem ?
Arash
Upvotes: 0
Views: 562
Reputation: 174967
Welcome to Stack Overflow! Please, don't use mysql_*
functions in new code. They are no longer maintained and the deprecation process has begun on it. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
The reason you're seeing this, is because you are building your queries without OR
or AND
. (Which are needed to seperate logical statements).
The best solution would be to add all of the query parts into an array, and implode with the a delimiter of " AND "
.
Upvotes: 2
Reputation: 5207
You can do it in cycle
$params = array(
'fnamn' => 'Fornamn',
'enamn' => 'Efternamn',
'adress' => 'adress',
'postnr' => 'postnr',
'stad' => 'stad',
'pnr' => 'pnr',
'tfn' => 'tfn',
'mobil' => 'mobil',
'epost' => 'epost'
);
$condition = array();
foreach ($params as $key => $field) {
if (isset($_POST[$key]) && !empty($_POST[$key])) {
$a = mysql_real_escape_string($_POST[$key]);
$condition[] = "`{$field}` LIKE '%{$a}%'";
}
}
$slq = 'select * from `medlem` where '.implode(' and ', $condition);
Upvotes: 2