php用了mysqli_escape_string()函数后变量丢失(无法往后传了)

这个小问题困扰了一个周末啊,不过后来还是解决了。

先上代码

<?php
error_reporting(0);
 function query_db($qstring) {
    include('db_login.php');  //connection details
    require_once('DB.php');  //PEAR DB
    $connection = DB::connect("mysqli://$db_username:$db_password@$db_host/$db_database");

    if (DB::isError($connection)){  //check for connect errors
        die ("Could not connect to the database: <br />". DB::errorMessage($connection));
    }
    mysqli_query($connection , "set names utf8");
    if (get_magic_quotes_gpc()) {  //guard against SQL injection
        $qstring = stripslashes($qstring);
    }
    //$qstring = mysqli_escape_string($connection,$qstring);
    /*$query = "SELECT title, pages, author_id, author FROM books NATURAL JOIN authors
               WHERE books.title LIKE '%".$qstring."%'";  //build the query*/
    //echo $qstring;
    $query = 'SELECT title, pages, author_id, author FROM `books` NATURAL JOIN `authors`
               WHERE `books`.`title` LIKE "%'.$qstring.'%"';
    //echo $query;
    $result = $connection->query($query);
    if (DB::isError($result)){
        die("Could not query the database:<br />".$query." ".DB::errorMessage($result));
    }
    echo ('<table border="1">');
    echo "<tr><th>Title</th><th>Author</th><th>Pages</th></tr>";
    if ($result == NULL) {
    	echo "error!";
    }
    while ($result_row = $result->fetchRow()) {
        echo "<tr><td>";
        echo $result_row[0] . '</td><td>';
        echo $result_row[3] . '</td><td>';
        echo $result_row[1] . '</td></tr>';
    }
    echo ("</table>");
    $connection->disconnect();
}
?>
<html>
<head>
    <title>Building a Form</title>
</head>
<body>
<?php
$search = htmlentities($_GET["search"]);
$self = htmlentities($_SERVER['PHP_SELF']);
if ($search != NULL){
    echo "The search string is: <strong>$search</strong>.";
    query_db($search);
}
else {
    echo ('
    <form action="'.$self.'" method="get">
        <label>Search:
            <input type="text" name="search"/>
        </label>
        <input type="submit" value="Go!" />
    </form>
    ');
}

?>
</body>
</html>

这个小脚本是实现查询数据库中的books.title中包含$qstring变量的数据并输出(是《学习PHP和MySQL》书上的)。

初次运行后发现无论输入什么都会出现所有的结果,后来把$query echo出来后发现$qstring已经消失了

如图:


之后把单双引号互换之后LIKE 后面有$qstring了,

欣喜的继续尝试查询,结果却没有结果了,

接着又尝试echo $qstring,然后发现echo后什么都没显示,说明$qstring 根本就没往后传,

继续往前查错,直到把函数mysqli_escape_string()注释了才正常了,

如图:



至此,问题算是解决了,但是没有mysqli_escape_string()函数又会有安全隐患,目前还不知道怎么解决。


阅读更多
个人分类: PHP和MySQL
上一篇操作系统并行与并发的区别
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭