dongquanyu5816 2012-04-01 18:08
浏览 31
已采纳

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

I have a MySQL table called Users. The rows have 4 fields and look like:

  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

I have a name of a user (TestName) and want to get the unique user id (1). Why does following code not work?

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;

This code outputs a zer0. I can exclude syntax errors. Something must be wrong with the query.

  • 写回答

1条回答 默认 最新

  • dreamMyDream2014 2012-04-01 18:13
    关注

    You have not fetched the row from $stmt. Look over the examples on the mysqli::bind_result() documentation to see how this is usually done with a call to $stmt->fetch() either singly when expecting one row, or in a while loop.

    $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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据