while if loop not executing properly - php

Can someone help me with the following code? The output works fine starting with the "categories" tag but the if loop only returns the last row from the db.
$strXML = "<chart> \n";
$strQuery = "select inc_type, sum(num_of_occur) as cnt from inc_detail
group by inc_type";
$query2 = mysql_query($strQuery); //call string query
$strCategories = "<categories>\n"; //create categories
while ($cat = mysql_fetch_array($query2))
{
$strCategories .= "<category label='" . $cat['inc_type'] . "' /> \n"; //display categories
};
$strCategories .= "</categories> \n";
$strQuery2 = "select agency, inc_type, sum(num_of_occur) as cnt from inc_detail group by inc_type, agency order by agency";
$query3 = mysql_query($strQuery2); //call string query
$agency = null;
while ($ds = mysql_fetch_array($query3))
{
if( $ds['agency'] != $agency )
{
$K5 = "<dataset seriesName='" . $ds['agency'] . "' /> \n"; //create dataset
$agency = $ds['agency'];
}
$K5 .= "<set value='" . $ds['cnt'] . "' /> \n"; //display value of dataset
$K5 .= "</dataset> \n";
}
$strXML .= $strCategories . $K5 . "</chart>"; //end of XML
echo $strXML;

The problem is here:
$K5 = "<dataset seriesName ...
You rewrite the $K5 every cycle of the iteration.
Suggested solution:
$K5 = "";
while ( ...
...
$K5 .= "<dataset seriesName ...

I finally got it working. For anyone interested, this is a fusionchart php file grabbing mysql data for a multiseries bar chart. Below is my new code:
$strXML = "<chart labelDisplay='Rotate' slantLabels='1' caption='Test' subCaption='By Quantity' decimalPrecision='0' showValues='0' showNames='1' numberSuffix=' Incidents' formatNumberScale='10'>";
$strQuery = "select inc_type, sum(num_of_occur) as cnt from inc_detail
group by inc_type";
$query2 = mysql_query($strQuery); //call string query
$strCategories = "<categories>"; //create categories
while ($cat = mysql_fetch_array($query2))
{
$strCategories .= "<category label='" . $cat['inc_type'] . "' />"; //display categories
}
$strCategories .= "</categories>";
$strQuery2 = "select agency, inc_type, sum(num_of_occur) as cnt from inc_detail group by inc_type, agency order by agency";
$query2 = mysql_query($strQuery2); //call string query
$K5 = $blank;
while ($ds2 = mysql_fetch_array($query2))
{
$K5 .= "<dataset seriesName='" . $ds2['agency'] . "' />"; //create dataset
//create dataset values
$strQuery4 = "select inc_type, sum(num_of_occur) as cnt from inc_detail where agency = '$ds2[agency]' group by inc_type";
$query4 = mysql_query($strQuery4);
while ($ds4 = mysql_fetch_array($query4))
{
$K5 .= "<set value='" . $ds4['cnt'] . "' />"; //display value of dataset
}
$K5 .= "</dataset>";
}
$strXML .= $strCategories . $K5 . "</chart>"; //end of XML
echo renderChart("fc/MSColumn3D.swf", "", $strXML, "productSales", 900, 600);

Related

how can i get a php variable outside a while loop which is in a function

function getTowns($conn)
{
$sql = "SELECT towns.name, towns.id, regions.name AS region_name FROM towns INNER JOIN regions ON towns.region_id = regions.id ORDER BY name ASC";
$result = $conn->query($sql);
$town_opt = ''; //stands for town option
town_opt .= "<datalist id='townlist'>";
while ($row = $result->fetch_assoc()) {
$town_id = $row['id'];
$town_opt .= "<option>" . $row['name'] . ", " . $row['region_name'] . "</option>";
}
$town_opt .= "</datalist>";
return $town_opt;
};
echo $town_id;
echo getTowns($conn);
//how can I echo every town id?
This is the best I could think of, and yet it doesn't work. I tried setting a cookie but it still wasn't working the way I wanted.
function getTowns($conn)
{
$sql = "SELECT towns.name, towns.id, regions.name AS region_name FROM towns INNER JOIN regions ON towns.region_id = regions.id ORDER BY name ASC";
$result = $conn->query($sql);
$town_opt = ''; //stands for town option
// We first set the town_id placeholder
$town_id = array();
town_opt .= "<datalist id='townlist'>";
while ($row = $result->fetch_assoc())
{
// We add the ID into our array
$town_id[] = $row['id'];
$town_opt .= "<option>" . $row['name'] . ", " . $row['region_name'] . "</option>";
}
$town_opt .= "</datalist>";
// We return an array
return array($town_opt, $town_id);
/* Or you could use this
return array('town_opt' => $town_opt, 'town_id' => $town_id);
And then use them like so:
$towns = getTowns($conn);
// $town_opt
echo $towns['town_opt'];
// $town_id
print_r($towns['town_id]);
*/
};
$towns = getTowns($conn);
// $town_opt
echo $towns[0];
// $town_id
print_r($towns[1]);
return an array with the first value being one value you want and the second as the other

count the displayed data

I have a page that display the logs of student according to date, year, section and IN/OUT. My question, how to count the number of student who displayed by filtering.
screenshot:http://oi60.tinypic.com/2a5ejgg.jpg
This is the code.
//SET UP SQL STATEMENT
$WHERE='';
if ($year<>'0')
{
$WHERE = " student.year = $year ";
}
if ($section<>'0')
{
if ($WHERE=='')
{
$WHERE = " student.section = '" . $section . "'";
}
else
{
$WHERE = $WHERE . "and student.section = '" . $section . "'";
}
}
//SET UP SQL STATEMENT
if ($in_out<>'0')
{
if ($WHERE=='')
{
$WHERE = " `log`.status_log = '" . $in_out . "'";
}
else
{
$WHERE = $WHERE . "and `log`.status_log = '" . $in_out . "'";
}
}
//SET UP SQL STATEMENT
if ($datefilter<>'')
{
if ($WHERE=='')
{
$WHERE = " `log`.date_log = '" . $datefilter . "'";
}
else
{
$WHERE = $WHERE . "and `log`.date_log = '" . $datefilter . "'";
}
}
$start = ($page-1)*$per_page;
if ($WHERE=='')
{
//SET UP SQL STATEMENT
$sql = "SELECT `log`.id, (student.id) as ids, student.name,
student.`year`, student.section, `log`.date_log,
`log`.time_log, `log`.ampm, `log`.status_log,
section.sec_name
FROM `log`
Inner Join student ON student.cardcode = `log`.stud_id
Inner Join section ON section.id = student.section
order by `log`.id DESC
limit $start,$per_page";
}
else
{//SET UP SQL STATEMENT SELECT COUNT(*) AS totalin FROM log WHERE status_log='in'
$sql = "SELECT `log`.id, (student.id) as ids, student.name,
student.`year`, student.section, `log`.date_log,
`log`.time_log, `log`.ampm, `log`.status_log,
section.sec_name
FROM `log`
Inner Join student ON student.cardcode = `log`.stud_id
Inner Join section ON section.id = student.section
WHERE $WHERE
order by `log`.id DESC
limit $start,$per_page";
}
//EXECUTE SQL STATEMENT
$result = mysql_query($sql);
//OOP ALL QUERY DATA ON LOAD AS LIST
while($row = mysql_fetch_array($result))
{
echo '<tr style="font-size: 12px;" class="record">';
echo '<td ><a style="text-decoration:none; color:#4F6B72" href="studentlog.php?id='.$row['ids'].'"</a>' .$row['name']. '</td>';
if ($row['year']=='1')
{ echo '<td> 1st</td>';}
else if ($row['year']=='2')
{ echo '<td> 2nd</td>';}
else if ($row['year']=='3')
{ echo '<td> 3rd</td>';}
else if ($row['year']=='4')
{ echo '<td> 4th</td>';}
echo '<td >'. $row['sec_name']. '</td>';
echo '<td >'. $row['status_log'] .'</td>';
echo '<td>'.$row['date_log'].'</td>';
echo '<td>'.$row['time_log'] . ' ' . $row['ampm'] .'</td>';
}
Once you have executed the query you can us mysql_num_rows() which tells you the actual number of row return by the query
So
//EXECUTE SQL STATEMENT
$result = mysql_query($sql);
$rows_returned = mysql_num_rows($result);
As it seems obvious you are just learning PHP and MYSQL can I suggest that you do not use the mysql_ extension!
Instead learn mysqli_ or PDO see this document for why

Showing six latest PhpBB posts instead of six copies of latest post

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.)
}

Produce php variable while looping through query and in certain order

I have a while fetch_assoc that produces and xml file for me. It works fine but now i need to add another variable to it.
Here is the working query
$sql3 = "SELECT name, class FROM tbl_user_tmp where user = '$user' order by name";
if(!$result3 = $mysqli->query($sql3)){
die('There was an error running the query [' . $mysqli->error . ']');
}
while($row2 = $result2->fetch_assoc()){
if(!isset($previousRow2) || !isset($previousRow2["category"]) || $previousRow2["category"] != $row2["category"])
{
$xml2 .= "\r\n";
$xml2 .= "<category title=\"" . $row2["category"] . "\" />\r\n";
}
$xml2 .= " <item drawable=\"";
$xml2 .= $row2["name"];
$xml2 .= "\" />";
$xml2 .= "\r\n";
$previousRow2 = $row2;
}
Now, what i need to do is take a array, and based on it,order what titles get done first.
This is how the array looks
$cat_order[]
Games,Apps,Google,Misc,System
You can order this in the query:
<?php
//Dynamic solution, build the SQL with a loop:
$cat_order = array("Games", "Apps", "Google");
$caseStr = "";
foreach($cat_order as $index => $value)
$caseStr .= sprintf("WHEN '%s' THEN %d ", $value, $index+1);
$sql3 = "
SELECT name, class
FROM tbl_user_tmp where user = '$user'
ORDER BY CASE name" . $caseStr . " END";
?>
Sorry to ask then answer but here is how i did it
$cat_name = $_POST['cat'];
foreach($cat_name as $k=>$val)
{
$cat_order[] = $val;
}
debug_to_console($cat_order);
$sql2 = "SELECT distinct category, name FROM tbl_user_tmp where user = '$user' and category is not null and category <> '' order by field (category,";
$size = count($cat_name);
foreach($cat_name as $k=>$val)
{
$sql2 .= "'$val'";
if($size > $k+1) $sql2 .=',';
}
$sql2 .= ")";
debug_to_console($sql2);

Can't figure out duplicate entries for data in SQL field, and random cell deletion (PHP/MYSQL)

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]);.

Categories