dsaf415212 2014-02-20 02:36
浏览 60
已采纳

使用MySQLi动态绑定准备语句中的参数

So like the title says, i've search here and tried almost everything, with no success.

I've try to test something very simple before going more deep, to make sure it works. But even at its simplest, i always get 0 results and i know there are 67 results.

What's wrong with my code?

Thanks

$conn = connect(); // connect to the db

$a_bind_params = array('love', 'circle');
$a_param_type = array('s', 's');

$totalKeywords = count($a_bind_params);

$q = 'SELECT id, name
    FROM album
    WHERE name LIKE ?';

for ($i = 1; $i < $totalKeywords; $i++) {
    $q .= ' AND name LIKE ?';
}

echo $q; // for testing purposes: verify that query is OK

// bind parameters.
$param_type = '';
$n = count($a_param_type);

for($i = 0; $i < $n; $i++) {
    $param_type .= $a_param_type[$i];
}

/* with call_user_func_array, array params must be passed by reference */
$a_params = array();
$a_params[] = & $param_type;

for($i = 0; $i < $n; $i++) {
  /* with call_user_func_array, array params must be passed by reference */
  $a_params[] = & $a_bind_params[$i];
}

$stmt = $conn->prepare($q);

/* use call_user_func_array, as $stmt->bind_param('s', $param); does not accept params array */
call_user_func_array(array($stmt, 'bind_param'), $a_params);


$stmt->execute();
$stmt->store_result();
$num_rows = $stmt->num_rows;

echo $num_rows; // how many found ?

$stmt->bind_result($id, $name);

while($stmt->fetch()) {
    echo $name;
}

$stmt->free_result();
$stmt->close();
$conn->close(); 
  • 写回答

1条回答 默认 最新

  • dongyou4411 2014-02-20 02:52
    关注

    There are not 67 rows with query

    SELECT id, name
    FROM album
    WHERE name LIKE 'love' AND name LIKE 'circle'
    

    There should be OR instead of AND in WHERE clause.

    Possibly, you may also need %love% and %circle%?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line