这是我学习 PHP 的第三天,我遇到了一个问题。我的 UPDATE 和 INSERT PDO 查询运行良好,但是让 SELECT 查询动态工作时遇到了麻烦。
这是我的搜索表单:
<h1>Search</h1>
<form action="otsingu_tulemused.php" method="post">
Aadress:<br />
<input type="text" name="aadress" value="" />
<br /><br />
Hind:<br />
<input type="text" name="hind" value="" /><br />
<br /><br />
<input type="submit" value="Otsi" />
</form>
这是我的搜索结果页面:
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// This if statement checks to determine whether the edit form has been submitted
// If it has, then the account updating code is run, otherwise the form is displayed
// Vaatame, kas aadressi väli on täidetud
if(!empty($_POST['aadress']))
{
$aadress = $_POST['aadress'];
}
else {
$aadress = null;
}
// Vaatame, kas hinna väli on täidetud
if(!empty($_POST['hind']))
{
$hind = $_POST['hind'];
}
else {
$hind = null;
}
// Kui aadressi väli on täidetud, siis anname parameetrile väärtuse
if($aadress !== null)
{
$query_params[':addr'] = $aadress;
}
// Kui hinna väli on täidetud, siis anname parameetrile väärtuse
if($hind !== null)
{
$query_params[':price'] = $hind;
}
// Note how this is only first half of the necessary update query. We will dynamically
// construct the rest of it depending on whether or not the user is changing
// their password.
$query = "
SELECT
*
FROM kuulutused
WHERE
";
// If the user is changing their password, then we extend the SQL query
// to include the password and salt columns and parameter tokens too.
if($address !== null)
{
$query .= "
addr LIKE :addr
";
}
if($price !== null)
{
$query .= "
AND
price = :price
";
}
try
{
// Execute the query
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
?>
<table class="table">
<?php foreach( $result as $row ){
echo "<tr><td>";
echo $row['addr'];
echo "</td><td>";
echo $row['price'];
echo "</td>";
echo "</tr>";
}
?>
</table>
这个查询给了我一个错误:
无法运行查询:SQLSTATE [42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取正确的语法,以便在第 4 行的 '' 附近使用。