php foreach循环搜索mysql表有几个单词

时间:2014-12-24 20:13:12

标签: php mysql forms foreach while-loop

我有一个名为食物的mysql表,列有" id,name,addinfo,picname,mg1cup,mg100g"。我有一个表格,用户可以提交1-20个食品名称。 php文件将提交的食物名称放在名为$ terms []的数组中。我需要在sql表中搜索所有术语,并返回每个术语的所有列的结果。

然而,结果仅显示提交的第一个术语,重复次数与输入一样多次(例如,如果输入两个单词,则第一个术语在结果中输出两次 - 而不是第一个单词结果,然后第二个词结果)。

我不知道自己做错了什么。这是我的代码(我还没有添加清除字符串的功能):

<?php

error_reporting(E_ALL);

ini_set('display_errors', '1');

//connect to the wordpress (bluehost)DB 

require_once '../../../wp-config.php';

$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die('Could not connect to mysql');

$Db = mysql_select_db(DB_NAME, $link) or die('Could not select database.');   

//check to see if the search term has a value, matches "name" column in DB, and if so, put it into an array called terms
if (isset($_POST['terms'])) {     

    $terms = ($_POST['terms']);

        if (count($terms) > 0 ) { 

            $results=array();

            foreach($terms as $term) {

                $sql = 'SELECT * from `wpqr_foods` WHERE `name` like  "%'. $term .'%" ORDER BY name ASC';


                $Q1 = mysql_query($sql);

                if(mysql_num_rows($Q1)) {

                    while ($Res = mysql_fetch_assoc($Q1)) {

                        $results[] = $Res; 

                    }

                }

                //$results = mysql_query($sql);


                $sql = 'SELECT * from wpqr_foods WHERE name LIKE "%'. $term .'%" ORDER BY name ASC';

                $Q2 = mysql_query($sql);

                //get results

                if(mysql_num_rows($Q2)) {

                    while ($Res = mysql_fetch_assoc($Q2)) {

                        $results[] = $Res; 

                    }

                }

            }

            if (count($results) > 0 ) {

                foreach ($results as $CurRes ) {

                    echo $CurRes['name']. "<br/>"; 
                    echo $CurRes['addinfo']. "<hr/>"; 

                    /* 

                    [id] => 5
                    [name] => Apples
                    [value] => Yes
                    [addinfo] => They can eat apples.  They can also eat the skin of the apple and the leaves of the apple tree, but the tree leaves are high in calcium, so limit their intake.  They can also chew on the apple tree branches.
                    [picname] => apple
                    [mgc1cup] => 5.8
                    [mgc100g] => 4.6

                    */
                }

            }

            else {

                echo "(nothing entered)";//MEANS $TERM IS EMPTY

            }


        }
        else {

            echo "(nothing entered)";//means $_POST IS NOT SET (end of if(isset($_POST['term'])) { )

        }             
}

//function to sanitize array values from form
function sanitizeString($var) {
         if (is_array($val))
           {
           foreach ($val as $k => $v)
               {
               $val[$k] = htmlentities(strip_tags($v),ENT_QUOTES);
               }
           }
         else
           {
             $val = htmlentities(strip_tags($terms),ENT_QUOTES);
           }
        return $val;
}
?>

HTML

<div class="my-form">
        <form role="form" id="step1" method="post" action="/wp-content/themes/mia/vitcdata.php">
            <p class="text-box"><label for="box1">Food <span class="box-number">1&nbsp;</span></label><input type="text" name="terms[]" value="" placeholder="apples" id="box1" />&nbsp;<a class="add-box" href="#">Add More</a></p>
            <p><input type="submit" value="Submit" /></p>
        </form>

表单包含动态表单字段,用户可以通过javascript添加,并且最多可以添加20个文本输入,其中所有输入的术语都会添加到$ terms []数组中。

所以,如果我测试它,使用两个字段,并输入&#34; apples&#34;和&#34;香蕉&#34;,结果显示&#34; apple&#34;的所有数据。重复两次。

2 个答案:

答案 0 :(得分:1)

选中此项,您可以在此处查看相关问题: Using OR in LIKE Query in MySQL to compare multiple fields

您可能需要在查询中执行此类操作。

$sql = 'SELECT * from wpqr_foods WHERE name LIKE "%'. $term .'%" OR addinfo LIKE "%'. $term .'%" ORDER BY name ASC';

OR,

$sql = 'SELECT * FROM `wpqr_foods` WHERE CONCAT(name, addinfo ) LIKE "%'. $term .'%" ORDER BY name ASC';

答案 1 :(得分:0)

我建议采用以下两种方式:

  1. 看起来像查询数据库并将结果推送到$results的代码块是重复的。您可能希望摆脱欺骗块,因为这将为每个不同的术语创建2x结果。
  2. 我怀疑通过表单实际传递给服务器的是一个字符串,其中包含空格分隔(或逗号,或用户选择输入的分隔符)条款。即使你选择将它作为一个数组传递(并在服务器端接收它),它实际上是一个字符串,你必须将explode它(或其他一些方法)自己放入一个数组中。要检查是否属于这种情况(如果您还没有这样做),请在foreach ($terms as $term)循环内的某个位置检查$term以查看它是否符合您的预期。