Mysql到Mysqli很难转换代码

时间:2013-04-10 00:40:38

标签: php mysql mysqli

我正在看phpsademy.org的Alex几年的一些教程,他使用mysql而不是mysqli我知道mysqli更好,应该使用而不是似乎无法弄清楚如何制作这段代码与所有mysqli一起工作。有人可以转换吗?

<?php
$connect = mysql_connect('localhost', 'root', 'pass') or die (mysqli_error());
mysql_select_db('jquery');

if (isset($_POST['username'])) {
    $username = mysql_real_escape_string($_POST['username']);
    if (!empty($username)) {
        $username_query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username`='$username'");
        $username_result = mysql_result($username_query, 0);

        if ($username_result == 0) {
            echo 'Username is available!';
        } else if ($username_result == 1) {
            echo 'Sorry, that username is taken.';
        }
    }
}
?>

我试图做的是......但mysqli_result一直给我错误:

<?php
$connect = mysqli_connect('localhost', 'root', 'pass', 'jquery') or die (mysqli_error());

if (isset($_POST['username'])) {
    $username = mysqli_real_escape_string($connect, $_POST['username']);
    if (!empty($username)) {
        $username_query = mysqli_query($connect, "SELECT COUNT(`user_id`) FROM `users` WHERE `username`='$username'");
        $username_result = mysqli_result($username_query, 0);

        if ($username_result == 0) {
            echo 'Username is available!';
        } else if ($username_result == 1) {
            echo 'Sorry, that username is taken.';
        }
    }
}
?>

因此我唯一得到的错误来自mysqli_result说:

  

致命错误:在第8行的\ php \ username.php中调用未定义的函数mysqli_result()

我在网上查找了mysqli_result的使用情况,并没有找到很多结果来帮助我解决这个问题,希望有人可以帮助我。

2 个答案:

答案 0 :(得分:2)

当您使用面向对象的样式时,$username_query属于mysqli_result类; mysqli_result是一个类而不是函数。

要从结果集中获取一行,您可以执行(例如):

$username_result = mysqli_fetch_array($username_query);

你应该使用mysqli(或PDO)而不是mysql_*函数的原因不仅仅是后者被弃用了:PDO(和mysqli)提供了准备语句,并提供了更好的防止sql注入的保护。逃避功能。

答案 1 :(得分:1)

首先确保表中的用户名列为unique,以便不会出现重复的用户名,因此$count将完全为0或1,然后尝试:

if (isset($_POST['username']) && $_POST['username'] != '') {

    $connect = new mysqli('localhost', 'root', 'pass', 'jquery') or die (mysqli_error());
    $username       = $_POST['username'];
    $query          = "SELECT COUNT(`user_id`) AS count FROM `users` WHERE `username`=?";
    $username_query = $connect->prepare($query);
    $username_query->bind_param('s', $username);
    $username_query->execute();
    $username_query->bind_result($count);
    $username_query->fetch();
    $username_query->close();
    $connect->close();

    if ($count == 0) {
        echo 'Username is available!';
    } else if ($count == 1) {
        echo 'Sorry, that username is taken.';
    }
}