带有占位符的 MySQL 查询不起作用 [英] MySQL query with placeholder does not work

查看:86
本文介绍了带有占位符的 MySQL 查询不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了下面的函数.此函数应该为一个 mySQL 查询处理不同数量的值.

I defined below function. This function supposed to work with different number of values for one mySQL query.

function queryMysql($query, $type, $arr)
{
    global $connection; // this is mysql connection

    $count = count($arr);
    $val = array();

    for ($i = 0; $i < $count; ++$i) {
        $val[] = $arr[$i];
    }

    $stmt = $connection->prepare($query);

    switch ($count) {
        case 1:
            $stmt->bind_param($type, $val[0]);
            break;
        case 2:
            $stmt->bind_param($type, $val[0], $val[1]);
            break;
        case 3:
            $stmt->bind_param($type, $val[0], $val[1], $val[2]);
            break;
    }

    $stmt->execute();

    printf("%d Row affected.\n", $stmt->num_rows);

    // rest of function
}

我这样称呼它:

$result = queryMysql("SELECT id FROM my_table WHERE my_value=?", 's', array('user'));

这一直向我展示:

0 Row affected.

我做错了什么?我阅读了 php.net 上的文档和 stackoverflow 上的相关问题,但我找不到问题所在.此外,我确定数据库包含一些与此查询匹配的行.

What am I doing wrong? I read documentation on php.net and related question on stackoverflow but I couldn't find the problem. Also I'm sure the database contains some rows which match this query.

推荐答案

您可能需要在获取行数之前存储结果.

You might need to store the result before getting row count.

$stmt->execute();
$stmt->store_result();
printf("%d Row affected.\n", $stmt->num_rows);

mysqli_stmt::$num_rows

这篇关于带有占位符的 MySQL 查询不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆