gpt4 book ai didi

php - 连接 MySQL 表,然后将结果过滤为列名

转载 作者:行者123 更新时间:2023-11-29 14:31:08 25 4
gpt4 key购买 nike

这是我用来从 4 个不同表获取 mysql 结果的代码

SELECT DISTINCT c.title as CourseTitle, t.title as TopicTitle, l.title as LessonTitle,    r.title as ResourceTitle, r.location, r.type, r.duration
FROM j17_lessons l, j17_topics t, j17_courses c, j17_resources r
WHERE
CONCAT(c.title, t.title, l.title, r.title, r.type, r.location) LIKE '%Fatih%'
AND c.id = t.course_id
AND l.topic_id = t.id
AND r.lesson_id = l.id
ORDER BY c.title, t.id, l.id, r.id;

这是我的获取结果的屏幕截图 http://i40.tinypic.com/2v1w0ib.png

现在我需要为数据库中的每个“CourseTitle”创建一个 HTML 表。

使用 SQL 语句和 PHP 代码,我可以获得第一个查询的结果,但我需要第二个查询来拆分表 foreach 'CourseTitle'

/* connect to the db */
$connection = mysql_connect('localhost','root','123');
mysql_select_db('alhudapk',$connection);

/* show tables */
$result = mysql_query('SELECT DISTINCT c.title as CourseTitle, t.title as TopicTitle, l.title as LessonTitle, r.title as ResourceTitle, r.location, r.type, r.duration
FROM j17_lessons l, j17_topics t, j17_courses c, j17_resources r
WHERE
CONCAT(c.title, t.title, l.title, r.title, r.type, r.location) LIKE '%Taleem%'
AND c.id = t.course_id
AND l.topic_id = t.id
AND r.lesson_id = l.id
ORDER BY c.title, t.id, l.id, r.id',$connection) or die('cannot show tables');
while($tableName = mysql_fetch_row($result)) {

$table = $tableName[0];

echo '<h3>',$table,'</h3>';
$result2 = mysql_query('SELECT '.$table . 'AS' .$table);
if(mysql_num_rows($result2)) {

请指导我构建正确且更好的代码

最佳答案

我要做的是将数据库结果放入一个大数组结构中,其中数据按照应打印的顺序排列。这使得维护代码变得更加容易。

// run the query as you did in the question

$courses = array();

// use mysql_fetch_assoc as it makes the code clearer
while($row = mysql_fetch_assoc($result)) {
$ct = $row['CourseTitle'];
// Found a new Course Title? If so create an array to put the data rows in
if(!isset($courses[$ct]))
$courses[$ct] = array();

// add this row to the end of its course array
$courses[$ct][] = $row;
}

// now print the results out
foreach($courses as $title =>$course) {
echo "<h3>$title</h3>";
echo "<table>";
foreach($course as $line) {
echo "<tr><td>" . $line['TopicTitle'] . "</td><td>"
. $line['LessonTitle'] . "</td></tr>";
echo "</table>";
}

上面的代码只打印出前两列,但如果你能让它工作,你应该能够很容易地添加其余部分。

关于php - 连接 MySQL 表,然后将结果过滤为列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10016863/

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