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

时间:2016-05-16 17:58:26

标签: php mysql database string checkbox

photo database

这是我的代码:

$test = 5;

        if (isset($_POST['zoek']))
        {       
            // Create connection
            $conn = new mysqli($servername, $username, $password, $dbname);
            // Check connection
            if ($conn->connect_error) {
                die("Connection failed: " . $conn->connect_error);
            } 

                if (isset($_POST['ingredienten']) && !empty($_POST['ingredienten'])) {

                    foreach ($_POST['ingredienten'] as $ingredienten) 
                    {

                    }
                    echo $fruitList = implode(',', $_POST['ingredienten']);
                }


                $sql = "SELECT * FROM keuzes, keuzes2, keuzes3, keuzes4, register, gerechten WHERE gerechten.IDpersoon = $test AND gerechten.ingredienten1 IN ($fruitList) AND gerechten.ingredienten1 = keuzes.ID AND gerechten.tijdsduren = keuzes2.ID AND gerechten.ratings = keuzes3.ID AND gerechten.maaltijden1 = keuzes4.ID AND gerechten.IDpersoon = register.ID";

                $result = $conn->query($sql);

                if ($result->num_rows > 0) {
                    // output data of each row
                    while($row = $result->fetch_assoc()) {

                        }
                    } else {

                    }
                    $conn->close();
        }

这是fruitList。这些都是表中的成分:'keuzes'。

        $selectAllPostsQuery = "SELECT * FROM keuzes";
        $resource = $conn->query($selectAllPostsQuery);
        /* When there's connection it will post the database information */
        if ($resource)
            {
                    while ($data = $resource->fetch_assoc())
                {
                    ?> 
                    <div style="padding: 2px; margin-left: 25px"><input type="checkbox" name="ingredienten[]" value="<?php echo $data['ID'] ?>"><?php echo $data['ingredienten'] ?><br></div>

我想检查字符串:“$ fruitList”,是否包含在数据库中,但它不起作用。

有人能帮助我吗?

1 个答案:

答案 0 :(得分:1)

给出以下代码:

echo $fruitList = implode('', $_POST['ingredienten']);

您有一个类似于&#39; 1245246&#39;的列表。在您的查询中(为清晰起见,删除了其他代码),它看起来像这样:

SELECT * FROM table WHERE gerechten.ingredienten1 LIKE "%1245246%"

正如您所知,这是行不通的。让我们做一两个改变。首先到了implode语句,让我们回到逗号分隔列表:

echo $fruitList = implode(',', $_POST['ingredienten']);

现在我们可以将查询更改为IN条件:

SELECT * FROM table WHERE gerechten.ingredienten1 IN (1,2,4,5,246)

您的成分表每个成分都有一行(OP提供的图像),因此您的LIKE语句只能找到一行,如果您有一个,其中包含的表像&#34; 1245872&#34;在专栏中。

enter image description here