I'm trying to select multiple rows from one table, depending on the ID given from another table.
I've got it half working with the code below, however it echo's out each blog multiple times depending on how many different tags are assigned to it, how would I go about so it displays multiple tag's on one copy of the blog post?
$sqlCommand = "SELECT blogid, blogtitle, content, blogtime, category, blogseourl, author FROM blog ORDER BY blogtime DESC";
$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error());
$blogDisplay = '';
while ($row = mysqli_fetch_array($query)) {
$blogid = $row["blogid"];
$blogtitle = $row["blogtitle"];
$content = $row["content"];
$blogtime = $row["blogtime"];
$category = $row["category"];
$blogseourl = $row["blogseourl"];
$author = $row["author"];
$contentshort = substr($content, 0, 250);
$sqlCommand2 = "SELECT tag FROM blogtags WHERE blogid='$blogid'";
$query2 = mysqli_query($myConnection, $sqlCommand2) or die (mysqli_error());
while ($row = mysqli_fetch_array($query2)) {
$tag = $row['tag'];
$blogDisplay .= '<h1> ' . $blogtitle . ' </h1> ' . $contentshort . '... Read More...<br /><br /> ' . $author . ' posted on ' . $blogtime . ' | Category: ' . $category . ' | Tags: ' . $tag . ' | ';
}
}
mysqli_free_result($query);
So everything is working correctly apart from it echoing multiple $blogDisplay's for each tag.
Anyone got any ideas?
You have to divide the blogDisplay into two sections, and list the tabs in between.
Or you have to buffer up the taglist and insert it as a parameter into $blogDisplay
The first one is easiest:
$sqlCommand = "SELECT blogid, blogtitle, content, blogtime, category, blogseourl, author FROM blog ORDER BY blogtime DESC";
$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error());
$blogDisplay = '';
while ($row = mysqli_fetch_array($query)) {
$blogid = $row["blogid"];
$blogtitle = $row["blogtitle"];
$content = $row["content"];
$blogtime = $row["blogtime"];
$category = $row["category"];
$blogseourl = $row["blogseourl"];
$author = $row["author"];
$contentshort = substr($content, 0, 250);
$sqlCommand2 = "SELECT tag FROM blogtags WHERE blogid='$blogid'";
$query2 = mysqli_query($myConnection, $sqlCommand2) or die (mysqli_error());
/*first part, all the html before the taglist */
$blogDisplay .= '<h1> ' . $blogtitle . ' </h1> ' . $contentshort . '... Read More...<br /><br /> ' . $author . ' posted on ' . $blogtime . ' | Category: ' . $category . ' | Tags: ';
while ($row = mysqli_fetch_array($query2)) {
$tag = $row['tag'];
/**add the taglist*/
$blogDisplay .= $tag.' ';
}
/**last part, all the html after the taglist*/
$blogDisplay .= ' | ';
}
mysqli_free_result($query);
Related
I have a specific query which is reading the 5 latest articles out of my database for category (mysql column) "sport"
I would like to run mulitiple queries, one for sport, one for cars, one for books, etc. Instead of rewriting the full query multiple times and replace the category sport by cars/books etc I would like to know if it possible to rebuild it to a function in which I input the category (like sports in line 2) and it outputs a string $sports (like in line 10/11) with all retrieves from the database as defined in the query.
// Build feed source for the latest News of Sport
$sqlCommand = "SELECT * FROM feeds where category like 'Sport' ORDER BY id DESC LIMIT 5";
$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error());
$sport = '';
while ($row = mysqli_fetch_array($query)) {
$fid1 = $row["id"];
$title1 = $row["title"];
$description1 = $row["description"];
$sport .= '<h2><b>' . $title1 . '</b></h2>';
$sport .= '' . $description1 . '<br/>';
}
mysqli_free_result($query);
This is how I finally resolved it:
function nieuws ($category,$color) {
global $myConnection;
$sqlCommand = "SELECT * FROM feeds where category like '$category' ORDER BY id DESC LIMIT 1";
$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error());
$output = '';
$output = "<div class=headlines style=background:$color><a class=newslink href='$category'>$category</a></div>";
while ($row = mysqli_fetch_array($query)) {
$fid1 = $row["id"];
$title1 = $row["title"];
$titleseo1 = seofy($title1);
$description1 = $row["description"];
$photo1 = $row["photo"];
if ('' == $photo1) {$photo1='images/pic1.jpg';};
$output .= "<div class=news2 style=background:#F0F8FF><img src='$photo1' alt='photo' style='width:200px;height:150px;object-fit:cover;border:0;margin:0px 5px 0px 0px;float:left'>"; //object-fit: cover zorgt dat het origineel het plaatje vult zonder distortion, is in principe cropping
$output .= '<b>' . $title1 . '</b></br>';
$output .= '' . $description1 . '<br/>';
$output .= "</div>";
}
mysqli_free_result($query);
}
I am running a query on 2 tables, to return information from a blog. The nested query selects the tags that are associated with that blog, which is a separate table.
I want to be able to get the 'tag' row from the 'tags' table and display these on the page. My code is below and I have commented where I would like the rows to be selected.
<?php
include("inc/dbconnection.php");
$id = $_GET['tag'];
$id = trim($id);
$result = mysqli_query($conn, "
SELECT *
FROM blog
WHERE blog_id IN (SELECT blog_id FROM tags WHERE tag = '$id')
");
if (!$result) {
die("Database query failed: " . mysqli_error($conn));
} //!$result
else {
$rows = mysqli_num_rows($result);
if ($rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$content = $row['content'];
$content2 = substr($content, 0, 100);
/* Below is where I would like to pull the row 'tag' from the nested query */
$rawTag = $row['tag'];
$tag = str_replace(" ", "", $rawTag);
$tagArray = explode(",", $tag);
$tag = "";
for ($i = 0; $i < count($tagArray); $i++) {
$tag .= "<a href='tag-" . $tagArray[$i] . ".php'>" . $tagArray[$i] . "</a> ";
} //$i = 0; $i < count($tagArray); $i++
echo "
<table>
<tr>
<th>
<a href='blog-" . $row['blog_id'] . ".php'>
<h2>" . $row['title'] . "</h2>
</a>
</th>
</tr>
<tr>
<td>
<p>" . date("d/m/Y", strtotime($row['createdDate'])) . "</p><br />
<span>" . $content2 . "...</span><br />
<span><small>Tags: " . $tag . "</small></span>
</td>
</tr>
</table>";
} //$row = mysqli_fetch_array($result, MYSQLi_ASSOC)
} //$rows > 0
else { //$rows > 0
echo "<br /><h1>There are currently no blogs with the selected tag (" . $_GET['tag'] . ")</h1><br /><h2>Please check back later.</h2>";
}
}
?>
Sorry if this is a stupid question and thanks in advance for your help :)
There are two part one is Query and second is data display.So Data display is total based
on your business call (how to display tag data in HTML.. )
but here you can optimize first part
(query for fetching data) as below:
$result = mysqli_query($conn, "SELECT b.*, t.* FROM blog b inner join tags t on
b.blog_id= t.blog_id WHERE t.blog_id '" . $id . "')");
Please use this.
Trying to display six of the latest posts from my PhpBB installation. I'm happy with how it's all working, however it's showing six copies of the same (most recent) post, and not size unique latest posts.
Just to confirm, I have seven total posts on the forums.
<?php
$con = mysqli_connect("localhost", "dbuser", "dbpass", "dbname");
$users = mysqli_query($con, "SELECT * FROM phpbb_user_group WHERE group_id='8'");
while($row = mysqli_fetch_array($users)) {
$developers[] = $row["user_id"];
}
$post = mysqli_query($con, "SELECT * FROM phpbb_posts");
while($row = mysqli_fetch_array($post)) {
$topic_id = $row["topic_id"];
$forum_id = $row["forum_id"];
$post_id = $row["post_id"];
$post_text = $row["post_text"];
$post_time = $row["post_time"];
}
$username = mysqli_query($con, "SELECT * FROM phpbb_users WHERE user_id='2'");
while($row = mysqli_fetch_array($username)) {
$postauthor = $row["username"];
if (strlen($post_text) > 10)
$post_text = wordwrap($post_text, 120);
$post_text = explode("\n", $post_text);
$post_text = $post_text[0] . '...';
$result = mysqli_query($con, "SELECT * FROM phpbb_posts WHERE poster_id='2' LIMIT 6");
while($row = mysqli_fetch_array($result)) {
$content = '<div onclick="location.href=\'http://test.mythros.net/forum/viewtopic.php?f=' . $forum_id . '&p=' . $topic_id . '#p' . $post_id . '\';" class="forum-latest-box">';
$content .= '<div class="forum-latest-userbar">';
$content .= '<div class="forum-latest-avatar">';
$content .= '<img src="https://minotar.net/helm/' . $postauthor . '/40.png">';
$content .= '</div>';
$content .= '<h1>' . $postauthor . '</h1>';
$content .= '</div>';
$content .= '<div class="forum-latest-content">';
$content .= '<div class="forum-latest-text">';
$content .= '"' . $post_text . '"';
$content .= '</div>';
$content .= '<div class="forum-latest-meta">';
$content .= gmdate("F j, Y, g:i a", $post_time);
$content .= '</div>';
$content .= '</div>';
$content .= '</div>';
echo $content;
}
?>
You can solve this problem by using a single loop and getting your post data and user information at the same time using combined query to the phpbb_posts table and phpbb_users table:
## Line break added to the query for legibility
$result = mysqli_query($con,
"SELECT
p.post_id AS post_id,
p.topic_id AS topic_id,
p.forum_id AS forum_id,
p.post_time AS post_time,
p.post_subject AS subject,
p.post_text AS post_text
IFNULL(m.username, 'Guest') AS username,
FROM phpbb_posts AS p
LEFT JOIN phpbb_users AS m ON (m.user_id = p.poster_id)
ORDER BY phpbb_posts.post_time DESC LIMIT 6");
while($row = mysqli_fetch_array($result)) {
# $row now contains the post information and the user info, so you can grab all your data,
# process the post text, and print it out at the same time.
$post_text = $row["post_text"];
# do your text transformation
if (strlen($post_text) > 10)
... (etc.)
# now set up your content
$content = '<div onclick="location.href=\'http://test.mythros.net/forum/viewtopic.php?f=' . $row["forum_id"] .'&p=' . $row["topic_id"] . '#p' . $row["post_id"] . '\';" class="forum-latest-box">';
... (etc.)
}
Is there an appropriate way to get input forms based on how many results there are from your SELECT? I have this, but when it gets posted to the next page only the last result appears.
<?php
$query = sprintf("SELECT promocost FROM Items, Promotions, Vendor_Prices, Vendors
WHERE Items.itemid = Promotions.itemid AND
Vendors.vendorid = Promotions.vendorid AND
Vendor_Prices.vendorid = Vendors.vendorid AND
Vendor_Prices.itemid = Items.itemid AND
promoid = '$promoid'");
$result =mysql_query($query);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while($row = mysql_fetch_assoc($result)) {
$models = $row['promocost'];
echo "<input type='text' name='promocost[]'/>";
}
?>
EDIT:
Took out unnecessary variable.
<?php
$query = sprintf("SELECT promocost FROM Items, Promotions, Vendor_Prices, Vendors
WHERE Items.itemid = Promotions.itemid AND
Vendors.vendorid = Promotions.vendorid AND
Vendor_Prices.vendorid = Vendors.vendorid AND
Vendor_Prices.itemid = Items.itemid AND
promoid = '$promoid'");
$result =mysql_query($query);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while($row = mysql_fetch_assoc($result)) {
echo "<input type='text' name='promocost[]'/>";
}
?>
I have an attendance page which outputs a list of students in a class through the following loop:
$sql10 = "SELECT class.name, student_to_class.class_id, student_to_class.student_id
FROM
student_to_class
INNER JOIN
class
ON class.id=student_to_class.class_id
WHERE
class.name = '$classid'";
$result10 = mysql_query($sql10) or die(mysql_error());
while ($row = mysql_fetch_array($result10)) {
$student = $row['student_id'];
$classid = $row['class_id'];
$sql3 = "select * from student where id = '$student'";
$result3 = mysql_query($sql3) or die(mysql_error());
$row3 = mysql_fetch_assoc($result3);
$studentfname = $row3['first_name'];
$studentlname = $row3['last_name'];
$sql4 = "select * from student where first_name = '$studentfname' AND last_name = '$studentlname'";
$result4 = mysql_query($sql4) or die(mysql_error());
$row4 = mysql_fetch_assoc($result4);
$studentrfid = $row4['rfid'];
$sql5 = "select * from class where id = '$classid'";
$result5 = mysql_query($sql5) or die(mysql_error());
$row5 = mysql_fetch_assoc($result5);
$class_name = $row5['name'];
//Define the default variables assuming attendance hasn't been taken.
$david = "select * from student where rfid='$studentrfid'";
$davidresult = mysql_query($david) or die(mysql_error());
$drow = mysql_fetch_assoc($davidresult);
if (($drow['excused'] == '1') && ($drow['excuseddate'] == $date)) {
//if($drow['excuseddate'] == $date;
$excusedabsense = '<option value="Excused Absense" label="Excused Absense" selected="selected">Excused Absense</option>';
} else {
$excusedabsense = '';
}
$presentpunctual = '<option value="Present" label="Present">Present</option>';
$presenttardy = '<option value="Tardy" label="Tardy">Tardy</option>';
$unexcusedabsense = '<option value="Absent" label="Absent">Absent</option>';
if (isset($_POST['editdate'])) {
$date = $_POST['date'];
}
$realfname = $studentfname;
$reallname = $studentlname;
$sql4 = "select * from attendance_main where StudentID = '$studentrfid' AND date = '$date' AND classID = '$class_name'";
$result4 = mysql_query($sql4) or die(mysql_error());
$row4 = mysql_fetch_assoc($result4);
if ($row4['status'] == "Present") {
$presentpunctual = '<option value="Present" label="Present" selected="selected">Present</option>';
} else {
$presentpunctual = '<option value="Present" label="Present">Present</option>';
}
if ($row4['status'] == "Tardy") {
$presenttardy = '<option value="Tardy" label="Tardy" selected="selected">Tardy</option>';
} else {
$presenttardy = '<option value="Tardy" label="Tardy">Tardy</option>';
}
if ($row4['status'] == "Absent") {
$unexcusedabsense = '<option value="Absent" label="Absent" selected="selected">Absent</option>';
} else {
$unexcusedabsense = '<option value="Absent" label="Absent">Absent</option>';
}
$b++;
echo "<tr>";
if (!isset($dateform)) {
$dateform = date('m/d/Y');
}
$date = date('m/d/Y');
echo '<td><iframe src="flag.php?&flagdate=' . $dateform . '&curdate=' . $date . '&class=' . $classid . '&flag=1&user=' . $studentrfid . '&curflag=' . $realrfid['flag'] . '&flagclass=' . $classname . '" width="50" height="30" frameborder="0" scrolling="no"> </iframe></td>';
//Yesterday
$sql8 = "select * from attendance_main where StudentID = '$studentrfid' AND date='$yesterdaysql' AND classID = '$class_name'";
$result8 = mysql_query($sql8) or die(mysql_error());
$tooltiprow = mysql_fetch_assoc($result8);
if (mysql_num_rows($result8) == 0) {
$tooltipresult_yesterday = "N/A";
} else {
$tooltipresult_yesterday = $tooltiprow['status'];
}
//2 days
$sql8 = "select * from attendance_main where StudentID = '$studentrfid' AND date='$days2sql' AND classID = '$classid'";
$result8 = mysql_query($sql8) or die(mysql_error());
$tooltiprow = mysql_fetch_assoc($result8);
if (mysql_num_rows($result8) == 0) {
$tooltipresult_2days = "N/A";
} else {
$tooltipresult_2days = $tooltiprow['status'];
}
//3 days
$sql8 = "select * from attendance_main where StudentID = '$studentrfid' AND date='$days3sql' AND classID = '$class_name'";
$result8 = mysql_query($sql8) or die(mysql_error());
$tooltiprow = mysql_fetch_assoc($result8);
if (mysql_num_rows($result8) == 0) {
$tooltipresult_3days = "N/A";
} else {
$tooltipresult_3days = $tooltiprow['status'];
}
$tooltip = "<b>" . $yesterday . ":</b> " . $tooltipresult_yesterday . " - <b>" . $days2 . ":</b> " . $tooltipresult_2days . " - <b>" . $days3 . ":</b> " . $tooltipresult_3days;
echo "
<!-- Loop #" . $b . " --> <td><a href='#'";
?> onMouseover="ddrivetip('<?php
echo $tooltip;
?>')"; onMouseout="hideddrivetip()"> <?php
echo $realfname . " " . $reallname . "</a></td>";
echo '<td>
<select name="status' . $b . '">
' . $presentpunctual . '
' . $presenttardy . '
' . $excusedabsense . '
' . $unexcusedabsense . '
</select>
' . $hiddenfield . '
<input type="hidden" name="i" value="' . $b . '" />
<input type="hidden" name="studentid' . $b . '" value="' . $studentrfid . '">
<input type="hidden" name="classid" value="' . $class_name . '"></td>
<td><input type="text" name="comments' . $b . '" size="40" /></td></tr>
<!-- End Loop -->';
}
}
}
It essentially prints out student name and a drop down of statuses (if attendance was taken that day, the status will be whatever is set in the database). The date, flag, and tooltip functions are extra additions. (Date is for previous days, tooltip shows previous attendance on hover)
This data is being executed through the following loop:
if (isset($_GET['update'])) {
mysql_query("UPDATE teacher_accounts SET attendance = '1' WHERE username = '$username'") or die(mysql_error());
$error = 0;
$limit = $_GET['i'];
$starter = 0;
$num = 0;
while ($starter < $limit) {
$num++;
$statusinc = "status" . $num;
$studentinc = "studentid" . $num;
$commentsinc = "comments" . $num;
$starter++;
$studentID = $_GET[$studentinc];
$status = $_GET[$statusinc];
$comments = $_GET[$commentsinc];
$date = date("m/d/Y");
$sql = "select * from student where id = '$studentID'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
$classid = $_GET['classid'];
if (isset($_GET['dateedit'])) {
$date = $_GET['dateedit'];
$count = "select * from attendance_main where StudentID = '$studentID' AND date = '$date' AND classID='$classid'";
$cresult = mysql_query($count) or die(mysql_error());
if (mysql_num_rows($cresult) > 0) {
$sql = "UPDATE attendance_main SET status='$status',comments='$comments',date='$date',classID='$classid' where StudentID = '$studentID'";
} else {
$sql = "INSERT INTO attendance_main (StudentID,status,comments,date,classID) VALUES ('$studentID','$status','$comments','$date','$classid')";
}
if (mysql_query($sql)) {
$return = "<h3>Successfully updated the attendance.</h3>";
}
} else {
$count = "select * from attendance_main where StudentID = '$studentID' AND date = '$date' AND classID='$classid'";
$cresult = mysql_query($count) or die(mysql_error());
if (mysql_num_rows($cresult) > 0) {
$sql = "UPDATE attendance_main SET status='$status',comments='$comments',date='$date',classID='$classid' where StudentID = '$studentID'";
if (mysql_query($sql)) {
$return = "<h3>Successfully updated the attendance for " . $num . " students.</h3>";
}
} else {
$sql = "INSERT INTO attendance_main (StudentID,status,comments,date,classID) VALUES ('$studentID','$status','$comments','$date','$classid')";
if (mysql_query($sql)) {
$return = "<h3>Successfully inserted today's attendance for " . $num . " students.";
}
}
}
}
echo $return;
For some reason, data is sometimes not being inserted properly. For example, a teacher might submit attendance on 02/08/2011, for a specific class, and certain students might appear twice under that attendance. This shouldn't be the case according to the code, because it should first check if they exist and, if they do, update the record rather than insert.
I've also seen cases where records are randomly deleted altogether. When a teacher takes attendance, all statuses are automatically set to Present. However, when I searched records on a certain date in the database, 2 students were missing records (which isn't even possible unless its being deleted)
Anyone have any idea why this might happen? I've tried replicating it myself (by repeatedly submitting the form, refreshing the page after it's processed, etc, to no avail.)
Thank you for the help!
Your query that check if a record exists is looking for all 3. 1) $studentID, 2) $classid and 3) $classid However the UPDATE statement is just looking for $studentID.
I would suggest you create a PRIMARY KEY (or UNIQUE INDEX) on StudentID,date,classID, then use the MySql INSERT ON DUPLICATE KEY UPDATE...
INSERT INTO attendance_main (StudentID,status,comments,date,classID)
VALUES ('$studentID','$status','$comments','$date','$classid')
ON DUPLICATE KEY UPDATE
status = VALUES(status),
comments = VALUES(comments)
Don't forget to sanitize the database input by using mysql_real_escape_string for example $status = mysql_real_escape_string($_GET[$statusinc]);.