Why isn't my MySQL data being displayed in my table? - php

Why is my MySQL data not being displayed in my table? Everything seems to work fine except that my data (which is a list of bird names and such) isn't showing up. I need some fresh eyes who can see where my mistake is, and yes I know that there are probably easier ways to do this, but this is what is required for my assignment, so please don't offer other ways to do this. All I need is help getting my data to populate in the HTML table. My PHP code is below:
PHP Code
<?php
$pageTitle = 'Mod06 Pagination| Jason McCoy ';
include('includes/header.inc.php');
include ('includes/db_connect.inc.php');
$display = 8;
// Determine how many pages there are...
if (isset($_GET['p']) && is_numeric($_GET['p'])) { // Already been determined.
$pages = $_GET['pages'];
} else {
$query = "SELECT COUNT(birdID) FROM birds";
$result = #mysqli_query($dbc, $query);
$row = #mysqli_fetch_array($result, MYSQLI_NUM);
$records = $row[0];
}
// Calculate the number of pages...
if ($records > $display) {
$pages = ceil($records/$display);
} else {
$pages = 1;
}
// Determine where in the database to start returning results...
if (isset($_GET['s']) && is_numeric($_GET['s'])) {
$start = $_GET['s'];
} else {
$start = 0;
}
// Sort the columns
// Default is birdID
$sortDefault = 'birdID';
// Create an array for the columns
$sortColumns = array('birdID', 'nameGeneral', 'nameSpecific', 'populationTrend');
// Define sortable query ASC DESC
$sort = (isset($_GET['sort'])) && in_array($_GET['sort'], $sortColumns) ? $_GET['sort']: $sortDefault;
$order = (isset($_GET['order']) && strcasecmp($_GET['order'], 'DESC') == 0) ? 'DESC' : 'ASC';
// Run the query
$query = "SELECT birdID, nameGeneral, nameSpecific, populationTrend FROM birds ORDER BY $order LIMIT $start, $display";
$result = #mysqli_query($dbc, $query);
?>
<!-- Table header: -->
<table align="center" cellspacing="0" cellpadding="5" width="80%">
<tr>
<th><a href='index.php?sort=birdID&order=<?php echo $order == 'DESC' ? 'ASC' : 'DESC' ?>'>Bird<?
if($_GET["order"]=="ASC" && $_GET["sort"]=="birdID"){
echo '<img src="images/downArrow.jpg" id="birdASC" name="birdASC" style="margin:-15px 0 0 13px;" width="18px" height="18px">';
} else {
echo '<img src="images/upArrow.jpg" id="birdDESC" name="birdDESC" style="margin:-15px 0 0 13px;" width="18px" height="18px">';
}?></a></th>
<th><a href='index.php?sort=nameGeneral&order=<?php echo $order == 'DESC' ? 'ASC' : 'DESC' ?>'>General Name<?
if($_GET["order"]=="ASC" && $_GET["sort"]=="nameGeneral"){
echo '<img src="images/downArrow.jpg" id="nameGeneralASC" name="nameGeneralASC" style="margin:-15px 0 0 13px;" width="18px" height="18px">';
} else {
echo '<img src="images/upArrow.jpg" id="nameGeneralDESC" name="birdDESC" style="margin:-15px 0 0 13px;" width="18px" height="18px">';
}?></a></th>
<th><a href='index.php?sort=nameSpecific&order=<?php echo $order == 'DESC' ? 'ASC' : 'DESC' ?>'>Name Specific<?
if($_GET["order"]=="ASC" && $_GET["sort"]=="nameSpecific"){
echo '<img src="images/downArrow.jpg" id="nameSpecificASC" name="nameSpecificASC" style="margin:-15px 0 0 13px;" width="18px" height="18px">';
} else {
echo '<img src="images/upArrow.jpg" id="nameSpecificDESC" name="birdDESC" style="margin:-15px 0 0 13px;" width="18px" height="18px">';
}?></a></th>
<th><a href='index.php?sort=populationTrend&order=<?php echo $order == 'DESC' ? 'ASC' : 'DESC' ?>'>Population Trend<?
if($_GET["order"]=="ASC" && $_GET["sort"]=="populationTrend"){
echo '<img src="images/downArrow.jpg" id="populationTrendASC" name="populationTrendASC" style="margin:-15px 0 0 13px;" width="18px" height="18px">';
} else {
echo '<img src="images/upArrow.jpg" id="populationTrendDESC" name="birdDESC" style="margin:-15px 0 0 13px;" width="18px" height="18px">';
}?></a></th>
</tr>
<?php
// Display the database results in the table...
while ($row = #mysqli_fetch_array($result, MYSQL_ASSOC)) {
echo '<tr>
<td align="left">$row[birdID]</td>
<td align="left">$row[nameGeneral]</td>
<td align="left">$row[nameSpecific]</td>
<td align="left">$row[populationTrend]</td>
<tr>';
}
echo '</table>';
mysqli_close($dbc);
// Make the links to other pages, if necessary.
if ($pages > 1) {
echo '<br /><p>';
$currentPage = ($start/$display) + 1;
// If it's not the first page, make a Previous button:
if ($currentPage != 1) {
echo 'Previous ';
}
// Make all the numbered pages:
for ($i = 1; $i <= $pages; $i++) {
if ($i != $currentPage) {
echo '' . $i . ' ';
} else {
echo $i . ' ';
}
} // End of FOR loop.
// If it's not the last page, make a Next button:
if ($currentPage != $pages) {
echo 'Next';
}
echo '</p>';
}
include('includes/footer.inc.php');
?>
</div>
</body>
</html>

Change this one $row[birdID] to $row['birdID'] for all, you missed ''.

use " inside echo like this, you have used ' because of that the value from database is not displayed.
while ($row = #mysqli_fetch_array($result, MYSQL_ASSOC)) {
echo "<tr>
<td align=\"left\">$row[birdID]</td>
<td align=\"left\">$row[nameGeneral]</td>
<td align=\"left\">$row[nameSpecific]</td>
<td align=\"left\">$row[populationTrend]</td>
<tr>";
}

Sorry, if a bit concise, typing from a phone...
'$row[birdID]'
and the other parts should be properly rewritten as:
'$row['birdID']'
as birdID is a string, not a variable name.
Though PHP uses this as a string, if there is no variable with that name in the current scope.
Always use quotes around a string literal array index. For example, $foo['bar'] is
correct, while $foo[bar] is not. But why? It is common to encounter this kind of
syntax in old scripts
from the PHP documentation: http://php.net/manual/en/language.types.array.php
EDIT somebody pointed out the single quotes used in echo too, that is a problem too. with single quotes, PHP will not interpret the content of the string, whereas with double quotes, PHP will parsde it, and use the values properly.

Related

get td values display as static in codeigniter

Hi guys i am trying to display the first td values as static so i have keep those values in one array and i try to increase the values and try to display but when i get it is displaying depending on foreach values if i have one record in foreach it is displaying one value and if i have 2 records it is displaying 2 values.
But i want to display all td value if i have values in foreach or not also.
Here is my code:
<tbody>
<?php
$arr = array(0=>'On Hold',1=>'Asset Incomplete',2=>'SME Discussion',3=>'a',4=>'b',5=>'c',6=>'d',7=>'e',8=>'f',9=>'g',10=>'h');
$i = 0;
foreach($getCourse as $report)
$status= $report->status;
{
?>
<tr>
<td><?php echo $arr[$i]; ?>
<?php $i++; ?></td>
<td><?php
if($status==1)
{
echo "On Hold";
}
elseif($status==2)
{
echo "Asset Incomplete";
}
elseif($status==3)
{
echo "Yet to Start";
}
elseif($status==4)
{
echo "SME Discussion";
}
elseif($status==5)
{
echo "Development";
}
elseif($status==6)
{
echo "PB Review";
}
elseif($status==7)
{
echo "PB Fixes";
}
elseif($status==8)
{
echo "PB2 Review";
}
elseif($status==9)
{
echo "PB2 Fixes";
}
elseif($status==10)
{
echo "Alpha Development";
}
elseif($status==11)
{
echo "Alpha Review";
}
elseif($status==12)
{
echo "Alpha Fixes";
}
elseif($status==13)
{
echo "Beta Review";
}
elseif($status==14)
{
echo "Beta Fixes";
}
elseif($status==15)
{
echo "Gamma";
}
?></td>
<td><?php echo $report->coursename; ?></td>
<td><?php echo $report->statuscount;?></td>
<td></td>
</tr>
<?php
}
?>
</tbody>
Here is my controller:
public function index()
{
if ($this->session->userdata('is_logged')) {
$data['getCourse']=$this->Report_model->getTopicReports();
$this->load->view('template/header');
$this->load->view('reports/report',$data);
$this->load->view('template/footer');
}
else {
redirect("Login");
}
}
Here is my model:
public function getTopicReports()
{
$this->db->select('count(t.status) as statuscount,t.topicName as topicname,c.coursename,t.status')
->from('topics t')
->join('course c', 't.courseId = c.id')
->where('t.courseid',1)
->where('t.status',5);
$query = $this->db->get();
return $query->result();
}
This is how i want to display here is my referrence image:
Can anyone help me how to do that thanks in advance.
FINAL UPDATED & WORKING VERSION
For me this was tricky. This turned out to be what I felt to be a awkward indexing issue.
The problem is that your data is not optimized very well to accommodate the task you are asking for. You have to make odd comparisons as you traverse the table. I was able to get it accomplished.
I would actually be very interested in seeing a more refined approach. But until that happens this code will dynamically generate a table that matches the output of the sample pictures that you posted in your question.
I have tested this code with some sample data that matches the array structure that you posted in your comments.
Here is the code:
//Create an array with your status values.
$rowName = array(
'On Hold',
'Asset Incomplete',
'Yet to Start',
'SME Discussion',
'Development',
'PB Review',
'PB Fixes',
'PB2 Review',
'PB2 Fixes',
'Alpha Development',
'Alpha Review',
'Alpha Fixes',
'Beta Review',
'Beta Fixes',
'Gamma'
);
//Generate a list of class names and get rid of any duplicates.
foreach($getCourse as $report){
$courseNames[] = $report->coursename;
}
$courseNames = array_unique($courseNames);
//Create the header.
echo
'<table>
<thead>
<tr>
<th>#</th>';
foreach($courseNames as $course){
echo '<th>' . $course . '</td>';
}
echo
'<th>Total</th>
</tr>
</thead>
<tbody>';
//Iterate across the array(list) of status values.
for($i = 0; $i < count($rowName); $i++){
echo
'<tr>';
echo '<td>' . $rowName[$i] . '</td>';
//Iterate through all combinations of class names and status values.
for($j = 0; $j < count($courseNames); $j++){
//Set flags and intial values.
$found = FALSE;
$total = 0;
$value = NULL;
for($k = 0; $k < count($getCourse); $k++){
//***Note - The ""$getCourse[$k]->status - 1" is because the status values in your data do not appear
//to start with an index of 0. Had to adjust for that.
//Sum up all the values for matching status values.
if(($getCourse[$k]->status - 1) == $i){
$total += $getCourse[$k]->statuscount;
}
//Here we are checking that status row and the status value match and that the class names match.
//If they do we set some values and generate a table cell value.
if(($getCourse[$k]->status - 1) == $i && $courseNames[$j] == $getCourse[$k]->coursename){
//Set flags and values for later.
$found = TRUE;
$value = $k;
}
}
//Use flags and values to generate your data onto the table.
if($found){
echo '<td>' . $getCourse[$value]->statuscount . '</td>';
}else{
echo '<td>' . '0' . '</td>';
}
}
echo '<td>' . $total . '</td>';
echo
'</tr>';
}
echo '</tbody>
</table>';
Try this. I am storing course status in $used_status then displaying the remaining status which are not displayed in foreach.
$arr = array ( '1' =>'On Hold', '2' => 'Asset Incomplete', '3' => 'SME Discussion', '4' => 'a', '5' => 'b', '6' => 'c', '7' =>'d', '8' => 'e', '9' => 'f', '10' => 'g', '11' => 'h' );
$used_status = array();
foreach($getCourse as $report) { ?>
<tr>
<td>
<?php $course_status = isset($arr[$report->status]) ? $arr[$report->status] : "-";
echo $course_status;
$used_status[] = $course_status; ?>
</td>
<td>
<?php echo $report->coursename; ?>
</td>
<td>
<?php echo $report->statuscount; ?>
</td>
</tr>
<?php }
foreach($arr as $status) {
if(!in_array($status, $used_status)) { ?>
<tr>
<td>
<?php echo $status; ?>
</td>
<td>
<?php echo "-"; ?>
</td>
<td>
<?php echo "-"; ?>
</td>
</tr>
<?php }
} ?>

Counting sessions in a foreach loop in not working PHP

I am trying to count all my products that is stored in a session called $_SESSION['product'.$id];.
But its not counting, its counting like this 1 1 1 1.
So its counting 1 of each product id separated.
My foreach loop...
foreach ($_SESSION as $name => $value) {
if($value > 0){
if(substr($name, 0, 8 ) == "product_"){
$length = strlen($name) -8;
$item_id = substr($name,8 , $length);
$query = "SELECT *
FROM gallery2
WHERE gallery2.id =".escape_string($item_id). "";
$run_item = mysqli_query($conn,$query);
while($rows = mysqli_fetch_assoc($run_item)){
$vari = $rows['variante'];
$num = $rows['title'];
$id = $rows['id'];
if(!isset($_SESSION['icms'.$id])) {
$_SESSION['icms'.$id]='0';
}else{
$_SESSION['icms'.$id];
}
//some code here
$subtotal=$value * $_SESSION['icms'.$id];
$cost=$_SESSION['icms'.$id];
$product = '
<tr>
<td style="width:100px; "><img src="../'.$rows['image'].'" style="width:90%;border: 1px solid black;"></td>
<td>'.$num.''.$vari.'</td>
//some code here
<td class="product'.$id.'">'.$value.'</td>
<td class="cost" data-id="'.$id.'" >R$:'.$cost.'</td>
<td class="subtotal" data-id="'.$id.'">R$:'.number_format($subtotal, 2, '.', '') .'</td>
<td>
'.$btn_add.' '.$btn_remove.' '.$btn_delete.'
</td>
</tr>';
echo $product;
//some closing brackets
Why this is happening?
What i tried:
print_r(count($_SESSION['product_'.$item_id])) ;
print_r(count($name)) ;
print_r(count($product)) ;
print_r(count($value)) ;
You can use this:
$product_count = count(array_filter(array_keys($_SESSION), function($x) {
return substr($x, 0, 8) == 'product_';
}));
But as I mentioned in a comment, it would probably be better if you redesigned your data. Instead of storing each product in a separate session variable, store them in an array. So instead of $_SESSION['product_'.$i] you would have $_SESSION['products'][$i]. Then you wouldn't need the code that checks whether the session variable beings with product_, you could just use
foreach ($_SESSION['products'] as $id => $value)
And to get the number of products, it would just be count($_SESSION['products']).

Foreach loops in PHP and Joomla

I'm currently managing the display of MySQL content in HTML with foreach loop like this :
<?php
echo "<table class=\"tableau\">
<tr bgcolor=\"#a72333\" class=\"first\">
<th>Repere</th>
<th>Niveau</th>
<th>Enseigne</th>
<th>Activités</th>
</tr>
<tbody>";
$db= JFactory::getDBO();
$query = 'SELECT baseData, sid, fid FROM XXXX_sobipro_field_data';
$db->setQuery($query);
$results = $db->loadObjectList();
foreach ($results as &$value) {
if ($value->sid == 55) {
if ($value->fid == 20) {
$repere = $value->baseData;
}
if ($value->fid == 16) {
$level = $value->baseData;
}
if ($value->fid == 22) {
$title = $value->baseData;
}
if ($value->fid == 17) {
$activity = $value->baseData;
}
if ($value->fid == 21) {
$display = $value->baseData;
}
}
[...]
// It ends at if ($value->fid == 83)
}
So I name my variable like this $title_NUM, $activity_NUM, ..., where _NUM is a number starting at "nothing", it ends at 24 for now, but it could be more if I have more data in my table.
After I get the data I display the html like this :
if ($display == 1) {
echo "<tr bgcolor=\"#eaeaeb\">
<td valign=\"top\">".$repere."</td>
<td align=\"top\">".$level."</td>
<td valign=\"top\"><a data-lightbox=\"width:600;type:iframe;\" href=\"LINK\">".$title."</a></td>
<td align=\"top\">".$activity."</td>
</tr>";
}
And the same happens here I'm displaying each linke of the html "by hand" , O don't have any loop to do the job.
Is there a way to do the job with only loops ?
what i understand so far is that you have
$title1 , $title2 , $title3 , ...
you want to do loop for it
see this example
<?php
for($i=0;$i<=8;$i++)//note it start from 0 to 8
${'test'.$i}=5*$i;
$test9=5*9;
echo "let's test <br/>";
echo $test0.'<br/>';
for($i=1;$i<=9;$i++)//note it start from 1 to 9
echo ${'test'.$i}.'<br/>';
?>

Using php's count () command to count the result of an if statement

I am trying to work my head round this, I am using the following code to check the answers to a quiz and output either CORRECT or INCORRECT depending on the result of the comparison, and if the answer field is black (which only comes from the feedback form) a different message is displayed.
I cant quite work out how to apply the php count function in this situation though, what im trying to get it to do it count the amount of CORRECT and INCORRECT answers and add the two together, and then I can work out a % score from that.
<?php
// Make a MySQL Connection
// Construct our join query
$query = "SELECT * FROM itsnb_chronoforms_data_answerquiz a, itsnb_chronoforms_data_createquestions
q WHERE a.quizID='$quizID' AND a.userID='$userID' and q.quizID=a.quizID and
a.questionID = q.questionID ORDER BY a.cf_id ASC" or die("MySQL ERROR: ".mysql_error());
$result = mysql_query($query) or die(mysql_error());
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
if ($row['correctanswer'] == ''){echo '<tr><td style="color:blue;">Thankyou for your feedback</td></tr>';}
elseif ($row['correctanswer'] == $row['quizselectanswer']){
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';}
else {echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
}}
?>
Iv found this example and have been trying to work out how to work it in, but cant think how to count the results of an if statement with it ?.
<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
$result = count($people);
echo $result;
?>
Just increment two counters
$correct_answers = 0;
$incorrect_answers = 0;
while ($row = mysql_fetch_array($result)) {
if ($row['correctanswer'] == '') {...
} elseif ($row['correctanswer'] == $row['quizselectanswer']) {
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';
$correct_answers++;
} else {
echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
$incorrect_answers++;
}
}
Simply increase some counter in each branch of your if/elseif/else construct...
$counters = array( 'blank'=>0, 'correct'=>0, 'incorrect'=>0 );
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
if ( ''==$row['correctanswer'] ) {
echo '<tr><td style="color:blue;">Thankyou for your feedback</td></tr>';
$counters['blank'] += 1;
}
elseif ( $row['correctanswer']==$row['quizselectanswer'] ) {
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';
$counters['correct'] += 1;
}
else {
echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
$counters['incorrect'] += 1;
}
}
echo '#correct answers: ', $counters['correct'];
How about creating a variable with a count of correct answers? For each question you loop through, increment the value by one.
<?php
$correct_answers = 0;
while($questions) {
if($answer_is_correct) {
// Increment the number of correct answers.
$correct_answers++;
// Display the message you need to and continue to next question.
}
else {
// Don't increment the number of correct answers, display the message
// you need to and continue to the next question.
}
}
echo 'You got ' . $correct_answers . ' question(s) right!';
<?php
// Make a MySQL Connection
// Construct our join query
$query = "SELECT ... ";
$result = mysql_query($query) or die(mysql_error());
$countCorrect = 0;
$countIncorrect = 0;
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
if ($row['correctanswer'] == ''){echo '<tr><td style="color:blue;">Thankyou for your feedback</td></tr>';}
elseif ($row['correctanswer'] == $row['quizselectanswer']){
$countCorrect++;
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';}
else {
$countIncorrect++;
echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
}
}
echo ((int)($countCorrect/($countIncorrect + $countCorrect) * 100)) . "% answers were correct!" ;
?>

How to paginate a table of Mysql in PHP

I have a table in mysql.
Because it has many rows I want to put each 10 rows in a page and by clicking a link show me next 10 rows.
Is there any solution?
It was really really awesome http://www.phpsimplicity.com/tips.php?id=1
it is so simple! no need to work with huge classes! I'm Happy:D
<!DOCTYPE html>
<html lang="en">
<head>
<title>Paginate</title>
</head>
<body>
<form method='get'>
<?php
$connection = Mysql_connect( 'server', 'user', 'pass' );
if ( ! $connection ) {
echo 'connection is invalid';
} else {
Mysql_select_db( 'DB', $connection );
}
//Check if the starting row variable was passed in the URL or not
if ( ! isset( $_GET['startrow'] ) or ! is_numeric( $_GET['startrow'] ) ) {
//We give the value of the starting row to 0 because nothing was found in URL
$startrow = 0;
//Otherwise we take the value from the URL
} else {
$startrow = (int) $_GET['startrow'];
}
//This part goes after the checking of the $_GET var
$fetch = mysql_query( "SELECT * FROM sample LIMIT $startrow, 10" ) or
die( mysql_error() );
$num = Mysql_num_rows( $fetch );
if ( $num > 0 ) {
echo '
<table border=2>';
echo '
<tr>
<td>ID</td>
<td>Drug</td>
<td>quantity</td>
</tr>
';
for ( $i = 0; $i < $num; $i ++ ) {
$row = mysql_fetch_row( $fetch );
echo '
<tr>';
echo "
<td>$row[0]</td>
";
echo "
<td>$row[1]</td>
";
echo "
<td>$row[2]</td>
";
echo '
</tr>
';
}//for
echo '
</table>
';
}
//Now this is the link..
echo 'Next';
$prev = $startrow - 10;
//only print a "Previous" link if a "Next" was clicked
if ( $prev >= 0 ) {
echo 'Previous';
}
?>
</form>
</body>
</html>
By the way link of rickyduck was good too
I suggest checking out this link : http://php.about.com/od/phpwithmysql/ss/php_pagination.htm for basic pagination. Furthermore, if you have knowledge of javascript, you could use jQuery.

Categories