通常我会帮助别人,无论他们需要什么,这次我都在寻求你的帮助。
我正在尝试从预先形成多个复选框后从我的数据库中获取特定行我选择花费50个小时,我无法做到这一点。 每次我在我的代码中更改某些内容时,我都会遇到不同的错误。 我正在寻找互联网上存在的每个HTML页面的答案!
请告诉我光明......这是我的表格的一部分....价值意味着玩具的“大小”
<div class=""><input type="checkbox" name="toys[]" value="6X2" /><label></label></div>
<div class=""><input type="checkbox" name="toys[]" value="4X3" /><label></label></div>
<div class=""><input type="checkbox" name="toys[]" value="8X2.5" /><label></label></div></strike>
这是PHP代码......
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
}
}
$query = $db->query = 'SELECT * FROM `toys` WHERE SIZE = '.$each_check;
echo "<table>";
echo "<tr>
<th>ratio</th>
<th>size</th>
<th>built</th>
<th>description</th>
</tr>";
while ($row = $query->fetch(PDO::FETCH_ASSOC))
echo "<tr><td>" . $row['ratio'] .
"</td><td>" . $row['size'] .
"</td><td>" . $row['built'] .
"</td><td>" . $row['description'] .
"</td></tr>";
echo "</table>";
答案 0 :(得分:2)
这远非有效:
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
}
}
$query = $db->query = 'SELECT * FROM `toys` WHERE SIZE = '.$each_check;
更像是:
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
$query = $db->query("SELECT * FROM `toys` WHERE SIZE = '".$each_check."'");
}
}
但应更像:
if (isset($_POST['toys'])) {
$query = 'SELECT * FROM `toys` WHERE SIZE = ?';
$sth = $db->prepare($query);
foreach($_POST['toys'] as $each_check) {
if( ! $sth->execute(array($each_check)) ) {
die('MySQL Error: ' . var_export($sth->error_info(), TRUE);
}
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
// code here
}
}
}
答案 1 :(得分:0)
您指定$db->query
而不是将其用作功能。将您的查询行更改为:
$query = $db->prepare('SELECT * FROM `toys` WHERE SIZE = :size');
$query->bindValue(':size',$each_check);
$query->execute();
此外,您正在浏览$ _POST ['toys'],但不会将其分配给任何值。我猜你想要在foreach中添加所有的查询和表格代码。
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
// put everything else here
}
}
答案 2 :(得分:0)
我想建议你在WHERE条件中使用MySQL的IN(...)子句来检索只有1个查询中匹配'size'的所有行:
SELECT * FROM toys WHERE size IN ( $chosenSizes )
要获取大小列表,请使用PHP的implode函数:
$chosenSizes = implode(', ', $_POST['toys']);
然后,您可以使用PDO的fetchAll将所有行提取到结果数组中。
$resultRows = $sth->fetchAll();
注意:只有在您确定结果数组不是太大时才使用此方法!
答案 3 :(得分:0)
Hagay,以下内容适合您:
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'my_name', 'my_pass');
if (isset($_POST['toys'])) {
$sizes = implode(', ', array_map(array($pdo, 'quote'), $_POST['toys']));
$sql = "SELECT * FROM toys WHERE size IN (" . $sizes . ")";
echo '<table>', PHP_EOL;
echo '<tr><th>ratio</th><th>size</th></tr>', PHP_EOL;
foreach( $pdo->query($sql) as $row ) {
echo '<tr><td>', $row['ratio'], '</td><td?', $row['size'], '</td></tr>', PHP_EOL;
}
echo '</table>', PHP_EOL;
}