我必须创建一个由n个正方形填充的页面,这些正方形将使用颜色选择器进行着色,然后当数据存储在数据库中时,我必须获得这些值并填充背景颜色属性:
我使用的是这个代码:
<?php
$square=0;
$sqid=0;
while ($square <= $numSquare) {
$square++;
$id = $sqid++;
$getExist = $DB_CON -> query("SELECT * FROM square WHERE SQUARE = " . $id);
$exist = $getExist->fetch();
if (isset($exist[2])) { $color=$exist[2]; } else { $color=''; }
if (null !== $exist) {
if ($exist[0] = $id) {
print '<div class="square" id="' . $exist[0] . '" style="background-color:' . $color . '"></div>';
}
} else {
print '<div class="square" id="' . $id .'"></div>';
}
}
?>
因此,它在DB中搜索该行(例如:第1行包含颜色#000000),并放入style="background-color:x"
属性,问题是使用此代码时,所有正方形的背景颜色都设置为无,即使它们不一定没有。(例如=必须是<div class="square" id="n">
并得到<div class="square" id="n" style="background-color:">
),除此之外,与数据库中ID 0相关的第一个正方形没有任何颜色,即使必须是#000000。
感谢所有能提供帮助的人。
您自己重置$color
:
if (isset($exist[1])) { $color=$exist[1]; } { $color=''; }
这里缺少一个"其他":
if (isset($exist[1])) {
$color = $exist[1];
} else {
$color='';
}
请参阅我对SELECT *
和标记查询结果的评论-不良做法
问题2:更新
接下来的两行看起来也很奇怪:
if (null !== $exist) {
$exist能成为null
吗?好吧,这取决于您的连接驱动程序,但PDOStatement::fetch()返回false
,一个简单的if ($exist)
就足够了。最好把其他if/else颜色分配放在这个块里。
下一行是赋值!只有当$id为0时,这才会变为false,这不可能是因为它在第一个循环中是1,并且一直变大。
if ($exist[0] = $id) {
这作为条件(因为它是WHERE子句的一部分)看起来毫无用处,作为赋值也毫无用处。
我通常在if或while条件中使用fetch()-方法。这是我从你的代码中读到的主要部分:
$getExist = $dbh->prepare('SELECT id, color FROM square WHERE square = ?');
for ($id = 0; $id < $numSquare; $i++) {
$getExist->execute([$id]);
$style = '';
// 1. fetch row, and check if there is one
// 2. check if a color is defined (if it is possible in db it is not)
if ($exist = $getExist->fetch() && isset($exist[1])) {
$style = 'background-color: '.$exist[1];
}
echo '<div class="square" id="'.$exist[0].'" style="'.$style.'"></div>';
}