2

我想使用多个“?”运行一个带有 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 ?");

然后按照其余的答案。

4

3 回答 3

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 />";
    }
  }
于 2012-12-20T02:07:15.520 回答
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);
于 2012-12-20T02:11:39.093 回答
0

我会先分配,然后绑定

$pattern = $_POST["pattern"];
$pos = $_POST["pos"];
$stmt->bind_param('ss', $pattern, $pos);
于 2012-12-20T02:08:02.260 回答