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