简体   繁体   中英

php searching in more than one column mysql

I am trying to make a code to search for data in more than one column , the code works only if I search in one column. when I tried to search in two columns it says that nothing is found in the database.

<form action="" method="post"> 
<input type="text" name="param" >
<input type="submit" name="submit" value="search"> 
</form>

if (isset($_POST['param'])) {
$param= trim ($_POST['param']);

$result = "SELECT * FROM table WHERE student_Name LIKE '%$param%' AND course_name LIKE '%$param%'";

I think you should use OR unless you want to check the 2 columns with the same parameter.

$result = "SELECT * FROM thecars WHERE student_Name LIKE '%$param%' OR course_name LIKE '%$param%'";

Also, this is very open to SQL injection. Sanitize your input before you pass it to the query.

您可以做一个concat并通过它进行搜索。

$result = "SELECT * FROM thecars WHERE CONCAT(`student_Name`, `course_name`) AS `search`LIKE '%$param%'";

Your using the same $param variable to search on both columns. If your searching for 2 separate values provide a form that supports inputting 2 values. And then handle such input properly in your query formation.

<form action="" method="post"> 
<input type="text" name="param1" >
<input type="text" name="param2" >
<input type="submit" name="submit" value="search"> 
</form>

if (isset($_POST['param1']) || isset($_POST['param2'])) {
$param1 = trim ($_POST['param1']);
$param2 = trim ($_POST['param2']);

$result = "SELECT * FROM thecars WHERE student_Name LIKE '%$param1%' AND course_name LIKE '%$param2%'";

Also change your column aggregation in where clause to OR as suggested by others if your searching for similar outcome.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM