micky micky - 4 months ago 14
PHP Question

Ignoring the where condition if null

$name=Yii::$app->request->post('name');
$address=Yii::$app->request->post('address');

if($name || $address)
{
$sql="SELECT * FROM studentrecords WHERE name=$name AND address=$address" ;
$display=Yii::$app->db->createCommand($sql)->queryAll();
}


What i need is if i donot input address in address field ignore
WHERE address=$address
. Currently, if
$address
is null, it gives sql error.

Answer

Hi You can simply do this. use concatnation of $sql. If $name and $address exist

$name=Yii::$app->request->post('name');
$address=Yii::$app->request->post('address');
$sql = "SELECT * FROM studentrecords where 1 = 1 ";        
if($name)
{
    $sql.=" AND name='$name'" ;

}
if($address) {
     $sql.= " AND address= '$address'";
    }

$display=Yii::$app->db->createCommand($sql)->queryAll();
Comments