从表中选择id = name? ...查询失败

时间:2012-04-01 18:08:49

标签: php mysql

我有一个名为Users的MySQL表。行有4个字段,如下所示:

  INT(10) |  serialized php array    |    CHAR(24) |  CHAR(254)
   id     |   profile                | name        |  email
   1      | ..ybl4JFtmhQEQVwQOXjo... | TestName    |  testmail@test.com
   2      | ..hd+F2yZVYPlxmyalrQo... | NameTest    |  mailtest@test.com

我有一个用户名(TestName),并希望获得唯一的用户ID(1)。 为什么以下代码不起作用?

function dataBase() {
    $dataBase = @new MySQLi("localhost", "name", "password", "databasename");
    if (mysqli_connect_errno()) {
        safeExit("Failed to establish connection to MySQL database, error: ".mysqli_connect_error(), 'msgError');
    } else {
        return $dataBase;
    }
}

// connect to database
$db = dataBase();

$sql = 'SELECT
            id
        FROM
            Users
        WHERE
            name = ?
        LIMIT
            1';
$stmt = $db->prepare($sql);
if (!$stmt) {
    safeExit($db->error, 'msgError');
}

$name = 'TestName';

$stmt->bind_param('s', $name);
if (!$stmt->execute()) {
    safeExit($stmt->error, 'msgError');
}
    $stmt->bind_result($uid);
    $stmt->close();
echo $uid;

此代码输出zer0。我可以排除语法错误。查询肯定有问题。

1 个答案:

答案 0 :(得分:0)

您尚未从$stmt获取该行。查看mysqli::bind_result() documentation上的示例,了解如何通过在预期一行或$stmt->fetch()循环时单独调用while来完成此操作。

$stmt->bind_param('s', $name);
if (!$stmt->execute()) {
    safeExit($stmt->error, 'msgError');
}

$stmt->bind_result($uid);

// Fetch the row so it populates the result variable
$stmt->fetch();
echo $uid;

$stmt->close();