我希望有人能协助在PHP动态查询。下面的第一个页面显示了来自MySQL的许多项。一旦一个项目被点击,它就会转到另一个页面,查询数据库以显示所选产品的详细信息。显示用户可以从中选择的项目的页面工作得很好,但是显示单击的项目的页面只有在我删除WHERE子句时才能工作,但当然它不再是动态的。错误语句表明该版本的语法不正确,但它在另一个页面上工作。使用MySQL 5.6.17和PHP 5.5.12
有谁能看出我在哪里出错了吗?
---------------------------------
主页面(功能正常)
<?php
ini_set('display_errors', '0');
$message = '';
$db=new MySQLi('localhost', 'someone', 'xxx','abc');
if ($db->connect_error) {
$message = $db->connect_error;
} else {
$sql = 'SELECT * FROM items';
$result = $db->query($sql);
if ($db->error) {
$message = $db->error;
}
}
?>
<!--other parts of the site--->
<?php if ($message) { ?>
<h2 class="inline_block">Sorry, there seems to be a problem.</h2>
<?php } else { ?>
<div>
<?php
$i = 0;
while ($row = $result->fetch_assoc()) {
if ($i % 4 === 0) { ?>
<div>
<ul>
<?php } ?>
<li> <a href="includes/details.php?id=<?php echo $row['itemID']; ?>"> <img src="img/<?php echo $row['image']; ?>" alt="<?php echo $row['alt']; ?>" height="150" width="150">
<p><?php echo $row['product']; ?></p>
<p class="reset">From $<?php echo $row['water']; ?></p></a> </li>
<?php $i++;
if ($i % 4 === 0) { ?>
</ul>
</div>
<?php } // end if
} // end of loop ?>
</div>
</div>
<?php } // end of page ?>
</div>
<!--other parts of the site--->
-----------------------------------------------------------------
Dynamic Page(返回一个SQL错误"你的SQL语法有错误;检查与您的MySQL服务器版本对应的手册,以便在"at line 1"附近使用正确的语法。第1行与下面所示的第一行相同。这在前一页中也使用过,没有问题。当从SQL查询中删除WHERE子句时,它可以工作,但不再是动态的。)
<?php
ini_set('display_errors', '0');
$message = '';
$db=new MySQLi('localhost', 'someone', 'xxx','abc');
if ($db->connect_error) {
$message = $db->connect_error;
} else {
$sql = 'SELECT * FROM items WHERE xitemID=' . $db->real_escape_string($_GET['xitemID']);
$result = $db->query($sql);
if ($db->error) {
$message = $db->error;
} else {
$row = $result->fetch_assoc();
}
}
?>
<!--other parts of the site--->
<ul>
<li><a href="../index.php">Home</a></li>
<li><a href="../things.php">Things</a></li>
<li><a href="mixeda.php">Mixeda</a></li>
<li><?php echo $row['product']; ?></li>
</ul>
</div>
<div id="col_1" role="main">
<?php if ($message) { ?>
<p> ERROR</p>
<?php echo "<p>$message</p>";
} else { ?>
<h2 class="inline_block"><?php echo $row['product']; ?></h2>
<p class="figure"><img src="../img/<?php echo $row['image']; ?>" alt="<?php echo $row['alt']; ?>" width="200" height="200">Price from $<?php echo $row['product']; ?></p>
</div>
<div id="col_2">
<h3>Details</h3>
<p><?php echo $row['details']; ?></p>
</div>
<?php } ?>
<!--other parts of the site--->
注意xitemID='itemHere'
:
$sql = "SELECT * FROM items WHERE xitemID='" . $db->real_escape_string($_GET['xitemID']) . "'";
只要定义了$_GET['xitemID']
,就可以解决您的问题。
您正在连接一个转义的
$sql = 'SELECT * FROM items WHERE xitemID=' .
$db->real_escape_string($_GET['xitemID']);
这看起来是一个有效的操作,但是当xitemID是一个字符值时,您仍然需要将其括在引号中。
最好使用预处理语句:
你已经在使用MySQLi了,所以:
$sql="SELECT * FROM items WHERE xitemID=?";
$pstmt=$db->prepare_statement($sql);
$pstmt->bind_param("s",$_GET['xitemID']);
$results=$pstmt->execute();