Writing a query that contains variable WHERE based on user input

后端 未结 2 850
隐瞒了意图╮
隐瞒了意图╮ 2021-01-22 05:40

I\'m having trouble with a query. What I would like it to do is check that each variable exists, and ignore them if they don\'t. I also want to display the results in a table. A

2条回答
  •  野性不改
    2021-01-22 06:22

    Try changing

    $sth = $db->prepare("SELECT * FROM customer WHERE First_name LIKE '%$First_name%' OR Surname LIKE '%$Surname%' OR DOB LIKE '$DOB' OR Street LIKE '%$Street%' OR Suburb LIKE '$Suburb' OR State LIKE '$State' OR Postcode LIKE '$Postcode' OR Phone LIKE '$Phone'");
    

    to

    $sth = $db->prepare("SELECT * FROM customer WHERE First_name LIKE '%'".$First_name."'%' OR ...
    

    Take $First_name out of the literal string, and concatenate it with the literal string. What you were doing was literally searching for "$First_name", not the value of the $First_Name variable. It's a bit messy from an appearance perspective, but I have found it safer to concatenate text with variables rather than expand variables within quotes.

    Darryl

提交回复
热议问题