我是 PDO 的新手,目前正在尝试重写我的所有查询。我在重写时遇到问题的一个查询是这个,因为它是在循环中编写的:
$search = $_GET['search'];
$code = explode(" ", $search);
$code_count = count($code);
$query = "SELECT * FROM table";
if($search != "")
{
if($code_count == 1)
{
$query .= " WHERE team LIKE '%".mysql_real_escape_string($search)."%'";
} elseif($code_count > 1)
{
for($j=0;$j<$code_count;$j++)
{
if($j != 0)
{
$query .= " OR ";
} else
{
$query .= " WHERE team LIKE '%".mysql_real_escape_string($code[$j])."%' OR ";
}
$query .= " team LIKE '%".mysql_real_escape_string($code[$j])."%'";
}
$query .= "ORDER BY team ASC";
}
} else
{
$query = "SELECT * FROM table ORDER BY team ASC";
}
$result = mysql_query($query)or die(mysql_error());
使用 PDO,我尝试了以下方法。
$query = "SELECT * FROM table";
if($search != "")
{
if($code_count == 1)
{
$query .= " WHERE team LIKE ?";
$stmt = $db->prepare($query);
$stmt->bindValue(1, "%$search%", PDO::PARAM_STR);
$stmt->execute();
} elseif($code_count > 1)
{
for($j=0;$j<$code_count;$j++)
{
if($j != 0)
{
$query .= " OR ";
} else
{
$query .= " WHERE team LIKE ? OR ";
}
$query .= " team LIKE ?";
$stmt = $db->prepare($query);
$stmt->bindValue(1, "%$code[$j]%", PDO::PARAM_STR);
$stmt->execute();
}
$query .= "ORDER BY team ASC";
}
} else
{
$query = "SELECT * FROM table ORDER BY team ASC";
}
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
这种方法运气不好。我不断收到一条错误消息:“nvalid parameter number: number of bound variables does not match number of tokens”
有任何想法吗?
谢谢,
槊