Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用MySQL数据库搜索PHP网站脚本_Php_Mysqli - Fatal编程技术网

用MySQL数据库搜索PHP网站脚本

用MySQL数据库搜索PHP网站脚本,php,mysqli,Php,Mysqli,我有一个PHP网站来展示产品。我需要引入一个“搜索”功能,在众多产品中可以找到关键词或短语 我浏览了大量现有的脚本,并为我编写/修改了一个脚本,虽然它能够连接到数据库,但不会返回任何值。调试模式抛出一条警告“mysqli\u num\u rows()期望参数1为mysqli\u结果,给定布尔值”。似乎我没有正确收集查询值。PHP手册指出,mysqli\u query()在失败时返回FALSE,对于成功的选择、显示、描述或解释查询,mysqli\u query()将返回一个mysqli\u结果对象

我有一个PHP网站来展示产品。我需要引入一个“搜索”功能,在众多产品中可以找到关键词或短语

我浏览了大量现有的脚本,并为我编写/修改了一个脚本,虽然它能够连接到数据库,但不会返回任何值。调试模式抛出一条警告“
mysqli\u num\u rows()
期望参数1为mysqli\u结果,给定布尔值”。似乎我没有正确收集查询值。PHP手册指出,
mysqli\u query()
在失败时返回FALSE,对于成功的选择、显示、描述或解释查询,
mysqli\u query()
将返回一个
mysqli\u结果
对象,对于其他成功的查询,
mysqli\u query()
将返回TRUE”

有什么建议吗

<form name="search" method="post" action="search.php">
        <input type="text" name="searchterm" />
        <input type="hidden" name="searching" value="yes" />
        <input type="submit" name="submit" value="Search" />
    </form>

    <?php 
     $searchterm=trim($_POST['searchterm']);
     $searching = $_POST['searching'];
     $search = $_POST['search'];

     //This is only displayed if they have submitted the form 
     if ($searching =="yes") 
     {
        echo 'Results'; 

         //If they forget to enter a search term display an error 
         if (!$searchterm) 
         { 
            echo 'You forgot to enter a search term'; 
            exit; 
         } 

         //Filter the user input
         if (!get_magic_quotes_gpc())
            $searchterm = addslashes($searchterm);

         // Now connect to Database 
         @ $db = mysqli_connect('localhost','username','password','database' );

         if (mysqli_connect_errno()) {
            echo 'Error: Could not connect to the database. Please try again later.';
            exit;
         }
         else {
             echo "Database connection successful."; //Check to see whether we have connected to database at all!
         }
         //Query the database
         $query = "SELECT * FROM wp_posts WHERE post_title LIKE '%$searchterm%' OR post_excerpt LIKE '%$searchterm%' OR post_content LIKE '%$searchterm%'";
         $result = mysqli_query($db, $query);

         if (!$result)
            echo "No result found";

         $num_results = mysqli_num_rows($result);

         echo "<p>Number of match found: ".$num_results."</p>";

        foreach ($result as $searchResult) {
            print_r($searchResult);
        }

        echo "You searched for $searchterm";

        $result->free();
        $db->close();
     }


我认为在您的查询中应该类似于
'%$searchterm%'
,而不是
'%{searchterm}%
。在您的示例中,您没有搜索变量
$searchterm

谷歌的显示在查询中使用了
LIMIT
,因此一次只显示一定数量的结果(称为)

这是经过测试并有效的。您需要更改1)搜索引擎类中的db连接信息。2)如果您希望它位于单独的页面上,则必须将其拆分。如果不希望,请将整个代码复制到一个页面,它将在该页面上工作

<?php
    class DBEngine
        {
            protected   $con;
            // Create a default database element
            public  function __construct($host = '',$db = '',$user = '',$pass = '')
                {
                    try {
                            $this->con  =   new PDO("mysql:host=$host;dbname=$db",$user,$pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
                        }
                    catch (Exception $e) {
                          return 0;
                        }
                }

            // Simple fetch and return method
            public  function Fetch($_sql)
                {
                    $query  =   $this->con->prepare($_sql);
                    $query->execute();

                    if($query->rowCount() > 0) {
                            $rows   =   $query->fetchAll();
                        }

                    return (isset($rows) && $rows !== 0 && !empty($rows))? $rows: 0;
                }

            // Simple write to db method
            public  function Write($_sql)
                {
                    $query  =   $this->con->prepare($_sql);
                    $query->execute();
                }
        }

    class   SearchEngine
        {
            protected   $searchterm;
            public  function execute($searchword)
                {
                    $this->searchterm   =   htmlentities(trim($searchword), ENT_QUOTES);
                }

            public  function display()
                { ?>
                    <h1>Results</h1>
                <?php 

                    //If they forget to enter a search term display an error 
                    if(empty($this->searchterm)) { ?>
                    <h3>Search Empty</h3>
                    <p>You must fill out search field.</p>
                    <?php }
                    else {
                            $con        =    new DBEngine('localhost','database','username','password');
                            $results    =   $con->Fetch( "SELECT * FROM wp_posts WHERE post_title LIKE '%".$this->searchterm."%' OR post_excerpt LIKE '%".$this->searchterm."%' OR post_content LIKE '%".$this->searchterm."%'");

                            if($results !== 0 && !empty($results)) { ?>
                                    <p>Number of match found: <?php echo count($results); ?> on search:<br />
                                    <?php echo strip_tags(html_entity_decode($this->searchterm)); ?></p>
                                    <?php
                                    foreach($results as $rows) {
                                            echo '<pre>';
                                            print_r($rows);
                                            echo '</pre>';
                                        }
                                }
                            else { ?>
                                    <h3>No results found.</h3>
                                    <?php
                                }
                        }
                }
        }

    if(isset($_POST['submit'])) {
            $searcher   =   new SearchEngine();
            $searcher->execute($_POST['searchterm']);
            $searcher->display();
        } ?>
    <form name="search" method="post" action="">
        <input type="text" name="searchterm" />
        <input type="hidden" name="searching" value="yes" />
        <input type="submit" name="submit" value="Search" />
    </form>

后果
搜索空
您必须填写搜索字段


要按原样进行文字搜索,您需要将代码
'%{searchterm}%'
更改为
'%$searchterm%'
,因为您正在搜索短语“{searchterm}”。除此之外,您可能还需要查看一下,因为您正在使用当前方法进行文字搜索


要使输出看起来像Google的输出,您只需为每个搜索结果编写一个包装器,并使用CSS和HTML对其进行样式设置。

@Rascallat观察良好。将其更改为
'%$searchterm%'
。但没有帮助。查询结构正确吗?它看起来正确。它只是说返回了0行吗?否。对于找到的结果数,它会重新渲染rs为空。调试说明
mysqli_num_rows()
期望参数1为mysqli_result,给定布尔值。更正了@Rasclatt指出的错误代码。您当时让它工作了吗?不,没有。如上所述,我似乎无法在
mysqli_query()中正确收集返回对象/值
function。是的,我刚刚读过。有时间我会解决它,前提是在我能够看到它的时候没有其他人解决过。