PHP爆炸并使用MySQL查询在多个列中进行搜索 [英] PHP explode and MySQL query to search in multiple columns

查看:64
本文介绍了PHP爆炸并使用MySQL查询在多个列中进行搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格,希望用户输入一个或多个单词.然后,这些词应与MySQL数据库中的多个列匹配.

I have a form where I want a user to enter one or more words. These words should then match mutiple columns in a MySQL database.

我已经开始构建一些代码,但是我被卡住了.

I have started to build some code but I'm stuck.

<?php
  $term = $_SESSION['session_searchstring']; //Let's say that session is John Doe
  $searchterm = explode(' ',$term);

  $searchFieldName = "name";
  $searchCondition = "$searchFieldName LIKE '%" . implode("%' OR $searchFieldName LIKE '%", $searchterm) . "%'";

  $sql = "SELECT * FROM students WHERE $searchCondition;";

  echo $sql; //Echo to test what mysql_query would look like

?>

上面的代码将输出:

SELECT * FROM students WHERE name LIKE '%John%' OR name LIKE '%Doe%'; 

问题是我想在多列( $ searchFieldName )中进行搜索.例如,我有

The problem is that I want to search in multiple columns ($searchFieldName). I have for example

customer_firstname
customer_lastname

我想将我的搜索字符串与两列的内容进行匹配.我将如何继续?

And I want to match my searchstring against the content of both columns.. How would I continue?

推荐答案

也许

  $term = $_SESSION['session_searchstring']; //Let's say that session is John Doe
  $searchterm = explode(' ',$term);

  $searchColumns = array("customer_firstname","customer_lastname");

  for($i = 0; $i < count($searchColumns); $i++)
    {
        $searchFieldName = $searchColumns[$i];
        $searchCondition .= "($searchFieldName LIKE '%" . implode("%' OR $searchFieldName LIKE '%", $searchterm) . "%')";
        if($i+1 < count($searchColumns)) $searchCondition .= " OR ";
     }

  $sql = "SELECT * FROM students WHERE $searchCondition;";

  echo $sql; //Echo to test what mysql_query would look like

生产

SELECT *从学生那里(customer_firstname LIKE'%John%'或customer_firstname LIKE'%Doe%')或(customer_lastname LIKE'%John%'或customer_lastname LIKE'%Doe%');

这篇关于PHP爆炸并使用MySQL查询在多个列中进行搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆