How to convert mysql to mysqli?

后端 未结 3 1495
我寻月下人不归
我寻月下人不归 2021-01-29 12:50

I tired to convert my mysql to mysqli but seems to be getting a lot of errors and warnings i got no problem connecting to the data base but the rest of the code seems wrong what

相关标签:
3条回答
  • 2021-01-29 12:53

    you can try it by creating a mysqli object like described here: http://www.php.net/manual/en/class.mysqli.php

    or simply like this:

    $db = new mysqli($hostname, $username, $password, $database);

    and then query it like this:

    $result = $db->query('SQL HERE');

    in your case the code for mysqli would look like this

    $db = new mysqli("localhost","root","","searchengine");
    
    $result = $db->query(sprintf(
      "SELECT * FROM searchengine WHERE pagecontent LIKE '%s' LIMIT 0,%d",
      '%'. mysqli_real_escape_string($_GET['term']) .'%',
      $_GET['results'])
    );
    
    while($ser = mysqli_fetch_array($result)) {
        echo "<h2><a href='$ser[pageurl]'>$ser[pageurl]</a></h2>";
    }
    
    0 讨论(0)
  • 2021-01-29 13:06

    In mysql, we used mysql_real_escape_string because you couldn't prepare statement.

    Now with mysqli, you have the ability to prepare statements which is the preferred way.

    <?php
    $mysqli = new mysqli("localhost", "root", "password", "searchengine");
    if ($mysqli->connect_errno) {
        echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") ";
    }
    
    $query = "SELECT * FROM searchengine WHERE pagecontent LIKE ? LIMIT 0,?";
    $stmt = $mysqli->prepare($query);
    
    if (!$stmt) {
        echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
    }
    $term = '%'.$_GET['term'].'%';
    $result = $_GET['results'];
    
    $stmt->bind_param("si", $term, $result);
    
    $stmt->execute();
    
    while ($ser = $stmt->fetch_assoc()) {
        echo "<h2><a href='".$ser['pageurl']."'>".$ser['pageurl']."</a></h2>";
    }
    
    
    $mysqli->close();
    ?>
    
    0 讨论(0)
  • 2021-01-29 13:09

    Try using OOP style instead of procedural, it is much cleaner and more readable:

        $mysqli = new mysqli("localhost", "root", "", "searchengine");
    
        $result = mysqli->query(sprintf(
    "SELECT * FROM searchengine WHERE pagecontent LIKE '%s' LIMIT 0,%d",
        '%'. mysqli_real_escape_string($_GET['term']) .'%',
        $_GET['results']));
    

    May I also suggest you read some articles about how to use mysqli and preparted statements, instead of just hacking away and not reading the documentation. Using prepared statements removes the need for sprintf. Here are some useful links:

    PHP Website - http://www.php.net/manual/en/book.mysqli.php

    An article I found on google in about 5 seconds and looks quite good -http://mattbango.com/notebook/code/prepared-statements-in-php-and-mysqli/

    0 讨论(0)
提交回复
热议问题