我想使用多个'?'运行带有PHP的select语句。我怎么做? 我认为以下代码应该这样做,出了什么问题?
$con = mysql_connect("database","login","password");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("posdictionary", $con);
$stmt = $con->prepare("SELECT * FROM WordPOS WHERE WORD LIKE '?%' AND pos LIKE BINARY '%?%'");
$stmt->bind_param('ss', $pattern, $pos);
$pattern = $_POST["pattern"];
$pos = $_POST["pos"];
$value = "";
if ($stmt->execute()) {
while ($row = $stmt->fetch()) {
$value = $value . $row['word'] . " " . $row['pos'] . "<br />";
}
}
更新:
以下答案很棒。我的PHP中出现错误,'?%'在php sql语句中不合法。查询应如下所示:
$pattern = $_POST["pattern"] ."%";
$pos = "%". $_POST["pos"] ."%";
$stmt = $con->prepare("SELECT word, pos FROM WordPOS WHERE word LIKE ? AND pos LIKE BINARY ?");
然后按照其余的答案。
答案 0 :(得分:2)
与new MySQLi()
联系,而不是mysql_connect()
,这与MySQLi API不兼容。
$con = new MySQLi("database","login","password","posdictionary");
您的prepare()
和execute()
来电正确,两个参数绑定正确。但是,您的fetch()
不会起作用,因为MySQLi希望结果列通过bind_result()
,而不是绑定到变量中,如同$row = $stmt->fetch())
一样。使用旧的mysql_*()
API或PDO完成。
$pattern = $_POST["pattern"];
$pos = $_POST["pos"];
// Substituting explicit columns in the SELECT list
$stmt = $con->prepare("SELECT word, pos FROM WordPOS WHERE WORD LIKE '?%' AND pos LIKE BINARY '%?%'");
$stmt->bind_param('ss', $pattern, $pos);
// Bind result columns into vars $word, $pos
$stmt->bind_result($word, $pos);
// Then execute and fetch
$value = "";
if ($stmt->execute()) {
while ($row = $stmt->fetch()) {
// Using the bound variables...
$value .= $word . " " . $pos . "<br />";
}
}
答案 1 :(得分:2)
您正在使用已弃用的mysql_*
函数进行连接,然后切换到mysqli语法。这不会起作用,你需要改变:
$con = mysql_connect("database","login","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("posdictionary", $con);
为:
$con = mysqli_connect("database","login","password");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
mysqli_select_db("posdictionary", $con);
答案 2 :(得分:0)
我先分配,然后绑定
$pattern = $_POST["pattern"];
$pos = $_POST["pos"];
$stmt->bind_param('ss', $pattern, $pos);