Convert mysql to mysqli?

2019-03-06 15:52发布

问题:

I'm trying to change my code to mysqli, I heard mysql isn't recommended and I'm having trouble changing my code to mysqli.

I managed to connect to my database but the rest of the code doesn't seem to work, I tried changing all mysql to mysqli but it didn't work. What could I do so the code works the same but in mysqli?

Could someone rewrite it so I could see the difference. I haven't seen any good tutorials.

<?php
 $db = new mysqli('localhost','root', '', 'searchengine');

    if($db->connect_errno) {
        die('sorry we are having some problbems');
        }

$sql = mysql_query(sprintf(
    "SELECT * FROM searchengine WHERE pagecontent LIKE '%s' LIMIT 0,%d",
        '%'. mysql_real_escape_string($_GET['term']) .'%',
        mysql_real_escape_string($_GET['results']))
);

while($ser = mysql_fetch_array($sql)) {
    echo "<h2><a href='$ser[pageurl]'>$ser[pageurl]</a></h2>";
}

mysql_close();

回答1:

<?php
 $db = new mysqli('localhost','root', '', 'searchengine');

    if($db->connect_errno) {
        die('sorry we are having some problbems');
        }

$sql = $db->query(sprintf(
    "SELECT * FROM searchengine WHERE pagecontent LIKE '%s' LIMIT 0,%d",
        '%'. $db->real_escape_string($_GET['term']) .'%',
        $db->real_escape_string($_GET['results']))
);

while($ser = $sql->fetch_array()) {
    echo "<h2><a href='" . $ser['pageurl'] . "'>" . $ser['pageurl'] . "</a></h2>";
}

$db->close();


回答2:

Alternative to the answer of @Machavity who's using a object oriented style you can use a procedural style as well:

<?php
    $db = mysqli_connect('localhost','root', '', 'searchengine');

    if(!$db) {
        die('sorry we are having some problbems');
    }

    $sql = mysqli_query(
        $db,
        sprintf(
            "SELECT * FROM searchengine WHERE pagecontent LIKE '%s' LIMIT 0,%d",
            '%'. mysqli_real_escape_string($db,$_GET['term']) .'%',
            mysqli_real_escape_string($db,$_GET['results'])
        )
    );

    while($ser = mysqli_fetch_array($sql)) {
        echo "<h2><a href='$ser[pageurl]'>$ser[pageurl]</a></h2>";
    }

    mysqli_close($db);
?>


标签: php mysql mysqli