为什么我得到这个错误类mysqli的对象无法转换为字符串

时间:2016-10-10 11:02:24

标签: php mysql mysqli

这是我的完整代码:

<?php
$query = $_GET['query']; 
// gets value sent over search form

$min_length = 3;
// you can set minimum length of the query if you want

if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then

    $query = htmlspecialchars($query); 
    // changes characters used in html to their equivalents, for example: < to &gt;

    $query = mysqli_real_escape_string($con, $query);
    // makes sure nobody uses SQL injection

    $raw_results = mysqli_query("$con, SELECT * FROM vendor1
        WHERE (title LIKE '%".$query."%') OR (publisher LIKE '%".$query."%')") or die(mysql_error());

    // * means that it selects all fields, you can also write: `id`, `title`, `text`
    // articles is the name of our table

    // '%$query%' is what we're looking for, % means anything, for example if $query is Hello
    // it will match "hello", "Hello man", "gogohello", if you want exact match use `title`='$query'
    // or if you want to match just full word so "gogohello" is out use '% $query %' ...OR ... '$query %' ... OR ... '% $query'

    if(mysqli_num_rows($raw_results) > 0){ // if one or more rows are returned do following

        while($results = mysqli_fetch_array($raw_results)){
        // $results = mysqli_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop

            echo "<p><h3>".$results['title']."</h3>".$results['full_set']." ".$results['issn']." ".$results['publisher']."</p>";
            // posts results gotten from database(title and text) you can also show id ($results['id'])
        }

    }
    else{ // if there is no matching rows do following
        echo "No results";
    }

}
else{ // if query length is less than minimum
    echo "Minimum length is ".$min_length;
}
?>

这是我得到的错误: 可捕获的致命错误:第29行的C:\ wamp \ www \ hari \ journalkart \ search.php中无法将类mysqli的对象转换为字符串

1 个答案:

答案 0 :(得分:0)

是的,这是真的“类mysqli的对象无法转换为字符串”:

修改后的查询:

<?php
$raw_results = mysqli_query($con,"SELECT * FROM vendor1
        WHERE (title LIKE '%".$query."%') OR (publisher LIKE '%".$query."%')");
?>

您的代码有什么问题?

您在字符串中使用整个查询和连接:

mysqli_query("$con,"SELECT QUERY");

还有一件事,如果您使用mysqli_*扩展名而不是使用mysql_error()的原因,则不能将这两种扩展名混合使用。

如果要检查mysqli错误,可以使用mysqli_error()函数:

mysqli_error($con);

建议使用Prepared Statement,这将使用SQL注入保存代码。