How to display the php values into html table? - php

I have almost did the displaying of values.But i am getting an extra td I hope the complete code is right.
Can anyone see it once.
php
<?php
session_start();
$link = mysqli_connect('localhost','root','','hoteldetails');
$sno[]="";
$roomImage[]="";
$roomNo[] = "";
$hotelName[]="";
$roomPrice[]="";
$loc[]="";
if(isset($_POST['sub']))
{
// mysqli_s(elect_db($link, "hotels");
$location=$_POST['searchVal'];
$sql = "select * from roomdetails where Location = '$location'";
$sqldata= mysqli_query($link ,$sql);
while($row = mysqli_fetch_array($sqldata)){
$sno[]=$row['S.No'];
$roomImage[] = $row['RoomImage'];
$roomNo[] = $row['RoomNo'];
$hotelName[] = $row['HotelName'];
$roomPrice[] = $row['RoomPrice'];
$loc[] = $row['Location'];
}
//two arrays to display ,$combine = array_combine($one,$two);
}
?>
html
<?php
echo "<table border='1'>";
echo "<tr><th>Hotel</th><th>Location</th></tr>";
foreach($sno as $id => $key):
echo "<tr>";
echo "<td>";?><img src="<?php echo $roomImage[$id];?>" height="100" width="100"><?php echo "</td>";
echo "<td>".$roomNo[$id]."</td>";
echo "<td>".$hotelName[$id]."</td>";
echo "<td>".$roomPrice[$id]."</td>";
echo "<td>".$loc[$id]."</td>";
echo "</tr>";
endforeach;
echo "</table>";
//echo $html;
?>
Is there anything wrong in it . Please is this process is right to display the values from mysql into html.

First, format your code, using tools like http://phpbeautifier.com for example.
Next, you have lines that contain both an echo and a ?> ... <?php instruction that tells php to echo stuff without any PHP parsing.
This is quite unreadable and unmaintainable.
You should better go for some "templating-like" practices using only HTML and using PHP only to output some vars, like this:
<?php
foreach ($data as $item) {
?>
<tr>
<td>Name: <?php echo $item['name']; ?></td>
<td>Price: <?php echo $item['price']; ?></td>
</tr>
<?php
}
This would drastically improve readability, maintainability, and especially your capacity of debugging the code.
And finally, you should take care of your php.ini configuration and check that display_errors is set to 1 and error_reporting is set to E_ALL.
This way, any error like PHP - Notice : Undefined index ... will be shown in the output so you can debug it.

Related

PHP undefined offset (not an error) try catch

I would like to list (upto) six of the remaining assignments due for the acedemic year onto a webpage.
The data for the remaining assignments comes from a mysql db.
When there are six or more assignments left, the webpage displays the info correctly.
If there are less than six left, then i get a undefined offset error (and i understand why).
Basically, i am trying to programmatically ignore the offset error.
I've tried looking and the following:
try/catches in the php.
tried using (in the foreach loop)
if($row['name'] == null){$row['name'] = "";}
etc.
index.php
include('getdata.php');
$nextAssArray0 = getNextAssessments($courseInfoArray[0], 0);
$nextAssArray1 = getNextAssessments($courseInfoArray[0], 1);
$nextAssArray2 = getNextAssessments($courseInfoArray[0], 2);
$nextAssArray3 = getNextAssessments($courseInfoArray[0], 3);
$nextAssArray4 = getNextAssessments($courseInfoArray[0], 4);
$nextAssArray5 = getNextAssessments($courseInfoArray[0], 5);
<div class="col-sm-4">
<h3>You have <?php echo '' ?> assignments left</h3>
<p>Assignment: <?php echo $nextAssArray0[0]; ?> is due on <?php echo $nextAssArray0[1]; ?></p>
<p>Assignment: <?php echo $nextAssArray1[0]; ?> is due on <?php echo $nextAssArray1[1]; ?></p>
<p>Assignment: <?php echo $nextAssArray2[0]; ?> is due on <?php echo $nextAssArray2[1]; ?></p>
<p>Assignment: <?php echo $nextAssArray3[0]; ?> is due on <?php echo $nextAssArray3[1]; ?></p>
<p>Assignment: <?php echo $nextAssArray4[0]; ?> is due on <?php echo $nextAssArray4[1]; ?></p>
<p>Assignment: <?php echo $nextAssArray5[0]; ?> is due on <?php echo $nextAssArray5[1]; ?>
</p>
</div>
getdata.php
function getNextAssessments($courseID, $offset)
{
try
{
include('dbconn.php');
$array = array();
$stm = $conn->prepare("CALL getUpcomingAssignments(:courseID, :offset)");
$stm->bindParam(':courseID', $courseID);
$stm->bindParam(':offset', $offset);
$stm->execute();
foreach ($stm->fetchALL() as $row)
{
array_push($array, $row['name']);
array_push($array, $row['due_date']);
array_push($array, $row['tem']);
}
}
catch (Exception $e)
{
$array = array('','','');
}
return $array;
}
I am after the following functionality:
1) if there is only three assignments left - then only three display.
2) if there is ten assignments left - then only six are displayed.
3) if there are no assignments left - then nothing is displayed in those
First of all, it is not a good idea to make SQL query for every database record. Remove limit from query, and put all your assesments in array. Then do something like this:
<h3>You have <?php echo count($assesments) ?> assignments left</h3>
<?php
foreach($assesments as $assesment){
echo "<p>Assignment: {$assesment[0]} is due on {$assesment[1]} ?></p>"
}
?>
Also I would recommend changing your code so you have array like $assesment['dueDate'] instead of $assesment[1].

How to speedup by code?

is there a way to speed up my code? It takes about 15 seconds to load ... I don't really see a way to reduce my code... I just thought about inserting the values into database, so the user does not have to load new info every time.. but the thing is that my cron only allows 1 load per hour ... by loading new info on every load it gives me fresh information..
$q1=mysql_query("SELECT * FROM isara");
while($r1=mysql_fetch_array($q1)){
$named=$r1['name'];
$idd=$r1['id'];
$descd=$r1['desc'];
$online=check_online($named);
$char = new Character($r1['name'],$r1['id'],$r1['desc']);
if($online == "online"){
$char->rank = $i++;
}
else{
$char->rank = 0;
}
$arr[] = $char;
}
?>
<br />
<h2 style="color:green">Online enemies</h2>
<?php
foreach ($arr as $char) {
if($char->rank>=1){
echo "<a style=\"color:green\" href=\"http://www.tibia.com/community/?subtopic=characters&name=$char->name\">";
echo $char->name." ";
echo "</a>";
echo level($char->name)."<b> ";
echo vocation($char->name)."</b> (<i>";
echo $char->desc." </i>)<br />";
}
}
?>
<br />
<h2 style="color:red">Offline enemies</h2>
<?php
foreach ($arr as $char) {
if($char->rank==0){
echo "<a style=\"color:red\" href=\"http://www.tibia.com/community/?subtopic=characters&name=$char->name\">";
echo $char->name." ";
echo "</a>";
echo level($char->name)."<b> ";
echo vocation($char->name)."</b> (<i>";
echo $char->desc." </i>)<br />";
}
}
?>
As I wrote in the comment, fetch the page once instead of once for every name in the database.
Pseudo code for my comment:
users = <get users from database>
webpage = <get webpage contents>
for (user in users)
<check if user exists in webpage>
As mentioned in the comments you're calling a webpage for each entry in your database, assuming that's about 2 seconds per call it's going to slow you down a lot.
Why don't you call the page once and pass the contents of it into the check_online() function as a parameter so your code would look something like this which will speed it up by quite a few magnitudes:
$content=file_get_contents("http://www.tibia.com/community/?subtopic=worlds&worl‌​d=Isara",0);
$q1=mysql_query("SELECT * FROM isara");
while($r1=mysql_fetch_array($q1)){
$named=$r1['name'];
$idd=$r1['id'];
$descd=$r1['desc'];
$online=check_online($named,$content);
$char = new Character($r1['name'],$r1['id'],$r1['desc']);
if($online == "online"){
$char->rank = $i++;
}
else{
$char->rank = 0;
}
$arr[] = $char;
}
?>
<br />
<h2 style="color:green">Online enemies</h2>
<?php
foreach ($arr as $char) {
if($char->rank>=1){
echo "<a style=\"color:green\" href=\"http://www.tibia.com/community/?subtopic=characters&name=$char->name\">";
echo $char->name." ";
echo "</a>";
echo level($char->name)."<b> ";
echo vocation($char->name)."</b> (<i>";
echo $char->desc." </i>)<br />";
}
}
?>
<br />
<h2 style="color:red">Offline enemies</h2>
<?php
foreach ($arr as $char) {
if($char->rank==0){
echo "<a style=\"color:red\" href=\"http://www.tibia.com/community/?subtopic=characters&name=$char->name\">";
echo $char->name." ";
echo "</a>";
echo level($char->name)."<b> ";
echo vocation($char->name)."</b> (<i>";
echo $char->desc." </i>)<br />";
}
}
?>
and your check_online() function would look something like this:
function check_online($name,$content){
$count=substr_count($name, " ");
if($count > 0){ $ex=explode(" ",$name); $namez=$ex[1]; $nameused=$namez; }
else{ $nameused=$name; }
if(preg_match("/$nameused/",$content)){ $status="online"; }
else{ $status="offline"; }
return $status;
}
You can also do the following to make it faster
Stop using select * which is very bad on innodb
Put better indexes on your database to make the recordset return faster
Install PHP 5.4 as it's faster especially as you're creating a new object in each iteration
Use a byte code accelerator/cache such as xdebug
you should avoid using distinct (*) keyword in your SQL Query
for more information read this http://blog.sqlauthority.com/category/sql-coding-standards/page/2/

Couldn't fetch mysqli...Call to a member function fetch_assoc() on a non-object

I'm totally baffled. My entire page code is below.
Originally, I had the include header.php, sidebar, topMenuBar, & mainContentShell at the top of the page, ran the first query after it, and then the second query, etc for the rest of the page. Everything worked. My first query was different though... I checked that the $_GET['stone'] number was greater than zero and less than the select max(StoneID), but I could still get errors if someone manually put in the StoneID for a stone that was deleted from inventory. I revised my $_GET validation plan, and moved it above the included files so the header() redirect would work properly. Now, my second query won't work, even though it is completely unchanged.
Var_dump($querySN) yields string(53) "select StoneName from stonetypes where StoneID = '1' " and var_dump($resultSN) yields NULL.
It states: error occurred at line 35 --- $resultSN = $db->query($querySN);
States several times: Couldn't fetch mysqli
States a number of times: Property access is not allowed yet
And states in conclusion: Call to a member function fetch_assoc() on a non-object on line 36---$rowSN = $resultSN->fetch_assoc();
Does anyone know what's going on here and how I can fix it? Page code follows. Thanks!!!
<?php
require('./inc/config.inc.php');
$stone = (INT)$_GET['stone'];
require(MYSQL1);
$queryCk = "select StoneID from stonetypes";
$resultCk = $db->query($queryCk);
$var = array();
while ($rowCk = $resultCk->fetch_assoc()){
$var[] = $rowCk['StoneID'];
}
if(!in_array($stone, $var)) {
header('Location: beadgallery.php?type=stones');
exit;
} else {
include('inc/header.inc.php');
include('inc/sidebar.inc.php');
include('inc/topMenuBar.inc.php');
include('inc/mainContentShell.inc.php');
?>
<div id="mainContent">
<div class="center">
<?php
$querySN = "select StoneName from stonetypes where StoneID = '$stone' ";
$resultSN = $db->query($querySN);
$rowSN = $resultSN->fetch_assoc();
echo '<table id="cartDisplayTable">';
echo '<tr>';
echo '<td colspan="2">';
echo '<table id="titleTable">';
echo '<tr>';
echo '<td id="stoneTitle">';
if (isset($rowSN['StoneName'])){
echo '<h2>'.ucwords($rowSN['StoneName']).'</h2>';}
echo '</td>';
echo '</tr>';
$query = "select * from organized_inventory2 where StoneID = '$stone' ";
$result = $db->query($query);
$num_beadItems = $result->num_rows;
$justused='abc';
for ($i=0; $i < $num_beadItems; $i++) {
$row = $result->fetch_assoc();
if (!isset($row['itmphoto'])) {
echo '</table>';
echo '</td>';
echo '</tr>';
echo '<tr><td colspan="2"><hr id="cartDivider"></td></tr>';
echo '<tr>';
echo '<td id="cartImgCell">';
echo '<img src="img/nophoto.gif">';
echo '</td>';
echo '<td id="cartInfoCell">';
echo '<table id="innerTable">';
include ('inc/stoneCartInfo.inc.php');
} elseif ($row['itmphoto'] == $justused) {
echo '<tr><td colspan="2"><hr id="itemDivider"></td></tr>';
include ('inc/stoneCartInfo.inc.php');
} else {
echo '</table>';
echo '</td>';
echo '</tr>'
;
echo '<tr><td colspan="2"><hr id="cartDivider"></td></tr>'
;
echo '<tr>';
echo '<td id="cartImgCell">';
echo '<img src="img/invent/'.$row['itmphoto'].'">';
$justused = $row['itmphoto'];
echo '</td>';
echo '<td id="cartInfoCell">';
echo '<table id="innerTable">';
include ('inc/stoneCartInfo.inc.php'); }
}
echo '</table>'
;
echo '</td>';
echo '</tr>'
;
echo '</table>'
;
}
$result->free();
unset($result);
$db->close();
?>
</div> <!-- div class="center" -->
</div> <!-- div id="mainContent" -->
Integers don't nee quotes around the value as in StoneID = '1', this shouldn't be a problem because MySQL should typecast.
You have not checked what "$result" contains, if it's boolean then the query failed and you need to see the output of mysqli_error.

Find change of title in while ($row = mysql_fetch_array($result)) { PHP

while ($row = mysql_fetch_array($result)) {
<h3> <?php echo $row['ideaTitle']; ?> </h3>
<blockquote>
<p>
<em>
<?php echo $row['feedback']; ?>
</em>
</p>
</blockquote>
<?php } ?>
Here's my working code. I want to attempt to find when $row['ideaTitle'] is new, but I'm not sure how to do it. I thought about setting a temp variable w/ the title name, but I feel like there needs to be a simpler solution.
Using a temporary variable is pretty much the way to go, I would say -- that's what I do in this kind of situation.
And it generally translates to this kind of code :
$previousTitle = null;
while ($row = mysql_fetch_array($result)) {
if ($row['ideaTitle'] != $previousTitle) {
// do something when the current line
// is the first with the current title
}
// work with $row
// Store the current title to the temporary variable,
// to be able to do the comparison on next iteration
$previousTitle = $row['ideaTitle'];
}
There is no other way than to use a temporary variable. But instead of using a single last value string, try a count map:
if (#$seen_titles[ $row["ideaTitle"] ]++ == 0) {
print "new title";
}
This trick works, because the counting up ++ is in effect done after the comparison. It needs an # error suppression however for the redundant notices here.
Imo this is quite a simple solution. However, you could also preprocess the data and create a title => feedbacks map:
$feedbacks = array();
while (($row = mysql_fetch_array($result))) {
if(!array_key_exists($row['ideaTitle'], $feedbacks) {
$feedbacks[$row['ideaTitle']] = array();
}
$feedbacks[$row['ideaTitle']][] = $row['feedback'];
}
And then create the output:
<?php foreach($feedbacks as $title => $fbs): ?>
<h3> <?php echo $title; ?> </h3>
<?php foreach($fbs as $fb): ?>
<blockquote>
<p>
<em><?php echo $fb ?></em>
</p>
</blockquote>
<?php endforeach; ?>
<?php endforeach; ?>
Keep a track of previously encountered titles in a key value array.
$prevTitles = array();
while ($row = mysql_fetch_array($result)) {
if($prevTitles[$row['ideaTitle']] == true)
continue;
$prevTitles[$row['ideaTitle']] = true;
<h3> <?php echo $row['ideaTitle']; ?> </h3>
<blockquote>
<p>
<em>
<?php echo $row['feedback']; ?>
</em>
</p>
</blockquote>
<?php } ?>

php and mysql not showing data, not entering foreach loop

I am having trouble with modifying a php application to have pagination. My error seems to be with my logic, and I am not clear exactly what I am doing incorrectly. I have had before, but am not currently getting errors that mysql_num_rows() not valid result resource
and that invalid arguments were supplied to foreach. I think there is a problem in my logic which is stopping the results from mysql from being returned.
All my "test" echos are output except testing while loop. A page is generated with the name of the query and the word auctions, and first and previous links, but not the next and last links. I would be grateful if a more efficient way of generating links for the rows in my table could be pointed out, instead of making a link per cell. Is it possible to have a continuous link for several items?
<?php
if (isset($_GET["cmd"]))
$cmd = $_GET["cmd"]; else
die("You should have a 'cmd' parameter in your URL");
$query ='';
if (isset($_GET["query"])) {
$query = $_GET["query"];
}
if (isset($_GET["pg"]))
{
$pg = $_GET["pg"];
}
else $pg = 1;
$con = mysql_connect("localhost","user","password");
echo "test connection<p>";
if(!$con) {
die('Connection failed because of' .mysql_error());
}
mysql_query('SET NAMES utf8');
mysql_select_db("database",$con);
if($cmd=="GetRecordSet"){
echo "test in loop<p>";
$table = 'SaleS';
$page_rows = 10;
$max = 'limit ' .($pg - 1) * $page_rows .',' .$page_rows;
$rows = getRowsByProductSearch($query, $table, $max);
echo "test after query<p>";
$numRows = mysql_num_rows($rows);
$last = ceil($rows/$page_rows);
if ($pg < 1) {
$pg = 1;
} elseif ($pg > $last) {
$pg = $last;
}
echo 'html stuff <p>';
foreach ($rows as $row) {
echo "test foreach <p>";
$pk = $row['Product_NO'];
echo '<tr>' . "\n";
echo '<td>'.$row['USERNAME'].'</td>' . "\n";
echo '<td>'.$row['shortDate'].'</td>' . "\n";
echo '<td>'.$row['Product_NAME'].'</td>' . "\n";
echo '</tr>' . "\n";
}
if ($pg == 1) {
} else {
echo " <a href='{$_SERVER['PHP_SELF']}?pg=1'> <<-First</a> ";
echo " ";
$previous = $pg-1;
echo " <a href='{$_SERVER['PHP_SELF']}?pg=$previous'> <-Previous</a> ";
}
echo "---------------------------";
if ($pg == $last) {
} else {
$next = $pg+1;
echo " <a href='{$_SERVER['PHP_SELF']}?pg=$next'>Next -></a> ";
echo " ";
echo " <a href='{$_SERVER['PHP_SELF']}?pg=$last'>Last ->></a> ";
}
echo "</table>\n";
}
echo "</div>";
function getRowsByProductSearch($searchString, $table, $max) {
$searchString = mysql_real_escape_string($searchString);
$result = mysql_query("SELECT Product_NO, USERNAME, ACCESSSTARTS, Product_NAME, date_format(mycolumn, '%d %m %Y') as shortDate FROM {$table} WHERE upper(Product_NAME) LIKE '%" . $searchString . "%'" . $max);
if($result === false) {
echo mysql_error();
}
$rows = array();
while($row = mysql_fetch_assoc($result)) {
echo "test while <p>";
$rows[] = $row;
}
return $rows;
mysql_free_result($result);
}
edit: I have printed out the mysql error of which there was none. However 8 "test whiles" are printed out, from a database with over 100 records. The foreach loop is never entereded, and I am unsure why.
The problem (or at least one of them) is in the code that reads:
$rows = getRowsByProductSearch($query, $table, $max);
$numRows = mysql_num_rows($rows);
The $numRows variable is not a MySQL resultset, it is just a normal array returned by getRowsByProductSearch.
Change the code to read:
$rows = getRowsByProductSearch($query, $table, $max);
$numRows = count($rows);
Then it should at least find some results for you.
Good luck, James
Hi there,
The next problem is with the line that reads:
$last = ceil($rows/$page_rows);
It should be changed to read:
$last = ceil($numRows / $page_rows);
Would recommend adding the following lines to the start of you script at least while debugging:
ini_set('error_reporting', E_ALL | E_STRICT);
ini_set('display_errors', 'On');
As that would have thrown up a fatal error and saved you a whole lot of time.
if (!(isset($pg))) {
$pg = 1;
}
How is $pg going to get set? You don't appear to be reading it from $_GET. If you're relying on register_globals: don't do that! Try to read it from $_GET and parse it to a positive integer, falling back to '1' if that fails.
<a href='{$_SERVER['PHP_SELF']}?pg=$next'>Next -></a>
You appear to be losing the other parameters your page needs, 'query' and 'cmd'.
In general I'm finding it very difficult to read your code, especially the indentation-free use of echo(). Also you have untold HTML/script-injection vulnerabilities every time you "...$template..." or .concatenate a string into HTML without htmlspecialchars()ing it.
PHP is a templating language: use it, don't fight it! For example:
<?php
// Define this to allow us to output HTML-escaped strings painlessly
//
function h($s) {
echo(htmlspecialchars($s), ENT_QUOTES);
}
// Get path to self with parameters other than page number
//
$myurl= $_SERVER['PHP_SELF'].'?cmd='.urlencode($cmd).'&query='.urlencode($query);
?>
<div id="tableheader" class="tableheader">
<h1><?php h($query) ?> Sales</h1>
</div>
<div id="tablecontent" class="tablecontent">
<table border="0" width="100%"> <!-- width, border, cell width maybe better done in CSS -->
<tr>
<td width="15%">Seller ID</td>
<td width="10%">Start Date</td>
<td width="75%">Description</td>
</tr>
<?php foreach ($rows as $row) { ?>
<tr id="row-<?php h($row['Product_NO']) ?>" onclick="updateByPk('Layer2', this.id.split('-')[1]);">
<td><?php h($row['USERNAME']); ?></td>
<td><?php h($row['shortDate']); ?></td>
<td><?php h($row['Product_NAME']); ?></td>
</tr>
<?php } ?>
</table>
</div>
<div class="pagercontrols">
<?php if ($pg>1) ?>
<<- First
<?php } ?>
<?php if ($pg>2) ?>
<-- Previous
<?php } ?>
<?php if ($pg<$last-1) ?>
Next -->
<?php } ?>
<?php if ($pg<$last) ?>
Last ->>
<?php } ?>
</div>
Is it possible to have a continuous link for several items?
Across cells, no. But you're not really using a link anyway - those '#' anchors don't go anywhere. The example above puts the onclick on the table row instead. What exactly is more appropriate for accessibility depends on what exactly your application is trying to do.
(Above also assumes that the PK is actually numeric, as other characters may not be valid to put in an 'id'. You might also want to consider remove the inline "onclick" and moving the code to a script below - see "unobtrusive scripting".)
This is wrong:
if($cmd=="GetRecordSet")
echo "test in loop\n"; {
It should be:
if($cmd=="GetRecordSet") {
echo "test in loop\n";
In your getRowsByProductSearch function, you return the result of mysql_error if it occurs. In order to debug the code, maybe you can print it instead, so you can easily see what the problem is.

Categories