在数据库php中查找特定值

时间:2012-06-22 10:55:29

标签: php mysqli

我尝试了不同的方法,但似乎都没有。当我在MySQL控制台中尝试该命令时,它工作正常,但是当我在这个PHP脚本中尝试它时,它会向我发回一个空字符串。

$search = $mysqli->prepare("SELECT item_path FROM items WHERE item_title = ?");

while (array_key_exists($i, $parts)) {
    // An array that contains (word1, word2, word3)
    $data = $parts[$i];

    // Wraps data in "" for mysqli query
    $data = "\"" . $data . "\"";

    // Binding here still doesn't work
    $search->bind_param("s", $data);

    // This should execute the above prepare and give me the data
    // from the way I think it work's this execute() should use the updated $data
    $search->execute();
    $search->bind_result($img_path);
    $search->fetch();

    // This returns an empty string
    echo $img_path;
    echo "<img src= \"", $img_path, "\" >";

    $i++;
}

如果我进入MySQL控制台并运行:

SELECT item_path FROM items WHERE item_title = "word1"

我得到了我期待的item_path但由于某种原因我的脚本返回一个空字符串。

提前感谢您的帮助(如果您这样做)!

编辑:

    // Wraps data in "" for mysqli query
    $data2 = "\"" . $data . "\"";

    // Binding here still doesn't work even after changing the var
    $search->bind_param("s", $data2);

我厌倦了将绑定更改为另一个变量,但我仍然得到一个空字符串。我不确定是不是因为我错误地包装数据或者是否有其他原因。我一直在寻找其他类似的事情发生,我什么也没想到。

1 个答案:

答案 0 :(得分:1)

您将语句绑定在子句之外,并且永远不会使用您更改的$data

$search = $mysqli->prepare("SELECT item_path FROM items WHERE item_title = ?");

while (array_key_exists($i, $parts)) {
    // An array that contains (word1, word2, word3)
    $data = $parts[$i];

    // Wraps data in "" for mysqli query
    $data = "\"" . $data . "\"";

    // Bind it here instead!
    $search->bind_param("s", $data);

    // This should execute the above prepare and give me the data
    $search->execute();
    $search->bind_result($img_path);
    $search->fetch();

    // This returns an empty string
    echo $img_path;
    echo "<img src= \"", $img_path, "\" >";

    $i++;
}