dongluo8303 2014-03-04 16:27
浏览 67
已采纳

PHP检查数据库是否包含字符串

I have a Array with data, and I am looping through the data.

For each string, I want to check if it is present in the database (whole table). It might be there inside another string (so if the table contains heyredcat, and you check for red, it also returns true).

I've came up with this sample script, but I can't come up with a MySQL query, Googling resulted in many great suggestions for "if column equals string" but not for a string in the whole table.

<?php 
$colors = array("red","green","blue","yellow"); 
foreach ($colors as $value)
   {
      $result = mysql_query("SELECT * FROM products where $value ...... ") or die(mysql_error());
      if($result){
        echo "Color" .$value. "is present";
      else {
        echo "Color" .$value. "is not present";
      }
   }
?>   

What MySQL query should I use? Also, I'm wonding, is this an efficient way to do this? (time consuming)

  • 写回答

3条回答 默认 最新

  • dongpo7467 2014-03-04 16:31
    关注

    This is what the query can look like:

    $res = mysql_query("SELECT 1 FROM `products` WHERE
        `col1` LIKE '%" . $value . "%'
        OR `col2` LIKE '%" . $value . "%'
        OR `col3` LIKE '%" . $value . "%'
        .. etc
    ");
    $num = mysql_num_rows($res);
    if ($num === 0) { // not found
    

    But keep in mind that this is susceptible to SQL injection if the list of colors can be picked by a user.

    So you will want to do:

    $value = mysql_real_escape_string($value);
    mysql_query("SELECT 1 FROM `products` WHERE
        `col1` LIKE '%" . $value . "%'
        OR `col2` LIKE '%" . $value . "%'
        OR `col3` LIKE '%" . $value . "%'
        .. etc
    ");
    

    You can dynamically generate the column names by looking at the mysql schema. The cheaty way would be to do a SELECT * FROM table LIMIT 1 first to get all the column names.


    Even better is to use the PDO driver which has a better (less error prone) way of inserting parameters into queries.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决