我在使用PHP从MySQL调用查询时遇到问题。
我已经在我的管理员PHP上使用SQL语法创建了表格并且它有效:
CREATE TABLE subjects(
id INT(11) NOT NULL AUTO_INCREMENT,
menu_name VARCHAR(30) NOT NULL,
position INT(3) NOT NULL,
visible TINYINT(1) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE pages(
id INT(11) NOT NULL AUTO_INCREMENT,
subject_id INT(11) NOT NULL,
menu_name VARCHAR(30) NOT NULL,
position INT(3) NOT NULL,
visible TINYINT(1) NOT NULL,
content TEXT,
PRIMARY KEY (id),
INDEX (subject_id)
);
然后在两个表上插入数据,并使用以下对应的颜色:
INSERT INTO subjects (menu_name, position, visible)
VALUES ('About', 1, 1);
INSERT INTO pages (subject_id, menu_name, position, visible, content)
VALUES (1, 'Our Mission', 1, 1, 'Our Mission has always been...');
继续在两个表中插入数据。
当我尝试对第二个表进行查询时,它只是忘记调用菜单主题内页面的第二个查询。我已经告诉变量$subject["id"]
没有定义,所以我无法在查询中使用变量,但我跟随的教程非常准确,我没有改变任何东西。这是代码:
这是de index.php文件:
!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<?php
$dbuser = 'root';
$dbpass = 'root';
$db = 'cms';
$dbhost = 'localhost';
$dbport = '3306';
$link = mysqli_connect($dbhost,$dbuser,$dbpass,$db) or die("Error " . mysqli_error($link));
$subject_set = "SELECT * FROM subjects WHERE visible = 1" or die("Error in the consult.." . mysqli_error($link));
$result = mysqli_query($link, $subject_set);
?>
<ul>
<?php
while($subject = mysqli_fetch_assoc($result)){ ?>
<li><?php echo $subject["menu_name"] ?>
<?php
$query = "SELECT * ";
$query .= "FROM pages ";
$query .= "WHERE visible = 1 ";
$query .= "AND subject_id = {$subject["id"]} "; // VARIABLE ON MYSQL NOT DECLARED
$query .= "ORDER BY position ASC";
$page_set = mysqli_query($connection, $query);
?>
<ul class="pages">
<?php
while($page = mysqli_fetch_assoc($page_set)){ ?>
<li><?php echo $page["menu_name"] ?></li>
<?php
}
?>
</ul>
</li>
<?php
}
?>
</ul>
<?php
mysqli_free_result($result);
mysqli_close($link);
?>
</body>
</html>
答案 0 :(得分:1)
$string = "..." or die();
完全没有意义。您没有执行查询。您只需定义 CONTAINS 查询字符串的字符串。因此,您无法在此时检测到数据库级错误。
您的代码应为:
$subject_set = "SELECT ...";
$result = mysqli_query(...) or die(mysqli_error($link));
您也无法检查内部查询中的错误。永远不要假设查询会成功。始终认为它会失败,检查失败,并将成功视为一个惊喜。
在宏观方案中,按原样运行嵌套查询效率非常低。您应该运行单个JOIN
ed查询。