为什么我的网站不了解我的MySQL和PHP代码?

时间:2016-01-22 22:08:35

标签: php mysql

我正在尝试制作搜索引擎但是当我将此代码上传到我的网站时,我得到了

  

错误003:发生未知错误。

我去了phpmyadmin并在SQL选项卡中键入了SQL,我得到了正确的结果但是当我将它上传到我的网站时它没有用。

<?PHP

    global $output;
    if(isset($_POST['submit'])){
            if(!empty($_POST)) {
            //Connect to DB
            $conn = new mysqli('localhost', 'username', 'password', 'search')or die('ERROR 001: Something went wrong while connecting to MySQL server.');

            if ($conn->connect_error) {
                die("Connection failed: " . $conn->connect_error);
            }

            $search = $_POST['searchBar'];

            $result = $conn->query('SELECT * FROM websites WHERE url LIKE "%$search%" OR title LIKE "%$search%"')or die('ERROR 002: Something is wrong with you SQL.');

            if(!$result->num_rows == 0) {
                while($row = $result->fetch_assoc()) {
                    $title = $row['title'];
                    $url = $row['url'];
                    $id = $row['id'];

                    $output .= '<a href="' . $url . '" target="_blank">' . $title . '</a><br><br>';
                }
            } else {
                $output = 'ERROR 003: An unknown error occurred.';
            }
        }
    }

?>
<?PHP 

    require('search.php');

 ?>

<!DOCTYPE HTML>
<HTML lang = "en">
    <head>
        <meta charset = "UTF-8">
        <meta name = "description" content = "null">
        <meta name = "author" content = "Adam Oates">
        <meta name = "title" content = "Search Engine">
        <title title = "Gigaboy Search Engine">
            Gigaboy Search Engine
        </title>
        <link rel = "apple-touch-icon" href = "">
        <link rel = "shortcut icon" href = "">
        <link rel = "stylesheet" type = "text/css" href = "main.css">
        <script type = "text/javascript" src = "http://code.jquery.com/jquery-2.1.4.js"></script>
        <script type = "text/javascript" src = "main.js"></script>
    </head>
    <body>
        <header>

        </header>

        <section id = "mainIndex">
            <div align = "center">
                <form action = "index.php" method = "post">
                    <input type = "text" name = "searchBar" placeholder = "Search the Web" autocomplete = "off">
                    <input type = "submit" name = "submit" value = "Search">
                </form><br><br>
                <?PHP echo $output; ?>
            </div>
        </section>

        <footer>

        </footer>
    </body>
</HTML>

1 个答案:

答案 0 :(得分:0)

执行 MYSQL 查询时,请使用架构前缀:

 SELECT * FROM [SCHEMA].websites WHERE url LIKE '%".$search."%' OR title LIKE '%".$search%."';

正确放置搜索变量,就像我放入查询一样。

我建议您使用预备语句以避免 SQL INJECTIONS