gpt4 book ai didi

PHP:根据 id 为正方形着色并从 db 获取数据

转载 作者:太空宇宙 更新时间:2023-11-04 10:17:26 26 4
gpt4 key购买 nike

我必须创建一个由 n 个正方形填充的页面,这些正方形将使用颜色选择器着色,然后当数据存储在 db 上时,我必须获取这些值并填写背景颜色属性:

我正在使用这段代码:

<?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>';
}
}
?>

因此它在数据库中搜索行,(例如:第 1 行包含颜色 #000000)并输入 style="background-color:x"属性,问题是使用此代码,所有正方形都将背景颜色设置为无,即使它们不能没有。 (例如 = 必须是 <div class="square" id="n"> 并得到 <div class="square" id="n" style="background-color:"> ),除此之外,与数据库中 ID 0 相关的第一个方 block 没有任何颜色,即使必须是 #000000。

感谢所有能提供帮助的人。

最佳答案

您自己重置$color:

if (isset($exist[1])) { $color=$exist[1]; } { $color=''; }

这里少了一个'else':

if (isset($exist[1])) {
$color = $exist[1];
} else {
$color='';
}

请查看我关于 SELECT * 和指示查询结果的评论 - 糟糕的做法。

问题 2 的更新:

接下来的两行看起来也很奇怪:

    if (null !== $exist) {

$exist 可以变成null吗?好吧,取决于您的连接驱动程序,但是 PDOStatement::fetch() 返回 false,一个简单的 if ($exist) 就足够了。最好将其他 if/else 颜色分配放在该 block 内。

下一行是作业!这只会在 $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>';
}

关于PHP:根据 id 为正方形着色并从 db 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37125736/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com