display php search results in html table - php

im running this php script and not quite getting the result i want. at the moment its giving me this output
scuba tank
mike
0.00
450.00
5.00
2012-06-04 18:50:22
scuba tank
liam
80.00
350.00
2.50
2012-06-04 19:00:09
Displaying 3 results
scuba tank
josh
410.00
0.00
5.00
2012-06-04 19:00:09
its pretty much what i want except the line displaying 3 results should be displayed at the end instead of before the last entry. what do i need to do to my script to fix this?
<?php
$host = "localhost";
$user = "root";
$pass = null;
// ========================================
$dbhost = #mysql_connect($host, $user, $pass) or die("Unable to connect to server");
#mysql_select_db("divebay") or die("Unable to select database");
$var = "scuba";
$query = trim($var);
if(!isset($query)){
echo "Your search was invalid";
exit;
} //line 18
$sql = "SELECT * FROM auction WHERE name LIKE '%" . $query . "%'";
$result = mysql_query($sql);
$numrows = mysql_num_rows($result);
mysql_close($dbhost);
if($numrows == 0){
echo "Sorry, your search did not return any results";
}
$i = 0;
while($i < $numrows){
$row = mysql_fetch_array($result);
$ID = $row['ID'];
$name = $row['name'];
$owner = $row['owner'];
$holder = $row['holder'];
$start = $row['sprice'];
$current = $row['cprice'];
$instant = $row['iprice'];
$inc = $row['incprice'];
$image = $row['img'];
$time = $row['stime'];
$length = $row['duration'];
echo "
<?xml version = '1.0' encoding = 'utf-8'?>
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org /TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<title>searchdbresults</title>
</head>
<body>
<table style='width = 800px;'>
<tr style ='height = 200px;'>
<td style ='width = 200px;'></td>
<td style ='width = 300px;'>
<div style ='180px'> $name </div>
<div> $owner </div>
</td>
<td style='width =200px'>
<div style='height = 100px'> $current </div>
<div style='height = 50px'> $instant </div>
<div> $inc </div>
</td>
<td> $time </td>
</tr>
";
$i++;
}
echo "
<tr> Displaying $numrows results</tr>
</table>
</body>
</html>
";
?>

I can't comment, but there is several problems in your code.
1st the style must double quote
<div style="width:100%;">
for example.
2nd : there must be a td inside a tr for this line : Displaying $numrows results
and last one i see is : you have this :
<?xml version = '1.0' encoding = 'utf-8'?>
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org /TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<title>searchdbresults</title>
</head>
<body>
inside your while loop, so its several times in your page, and it must not
You also have the table opening in your while loop, but not the closing. So it's opened several times, but opened only once.
edit : you also need to add protection into your sql query

Your script is generating "messy" HTML. From what I see your so generated HTML page will have (in the current example) 3 DOCTYPE definitions, 3 head's as well as 3 opening table tags and only one closing /table. And also you don't need to echo every single html entity, you can use plain html in php files
Try something like that:
<?xml version = '1.0' encoding = 'utf-8'?>
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<title>searchdbresults</title>
</head>
<body>
<?php
$host = "localhost";
$user = "root";
$pass = null;
// ========================================
$dbhost = #mysql_connect($host, $user, $pass) or die("Unable to connect to server");
#mysql_select_db("divebay") or die("Unable to select database");
$var = "scuba";
$query = trim($var);
if(!isset($query)){
echo "Your search was invalid";
exit;
} //line 18
$sql = "SELECT * FROM auction WHERE name LIKE '%" . $query . "%'";
$result = mysql_query($sql);
$numrows = mysql_num_rows($result);
mysql_close($dbhost);
if($numrows == 0){
echo "Sorry, your search did not return any results";
}
else{
?>
<table style='width = 800px;'>
<?php
$i = 0;
while($i < $numrows){
$row = mysql_fetch_array($result);
$ID = $row['ID'];
$name = $row['name'];
$owner = $row['owner'];
$holder = $row['holder'];
$start = $row['sprice'];
$current = $row['cprice'];
$instant = $row['iprice'];
$inc = $row['incprice'];
$image = $row['img'];
$time = $row['stime'];
$length = $row['duration'];
?>
<tr style ="height: 200px;">
<td style ="width: 200px;"></td>
<td style ="width: 300px;">
<div style ="width: 180px"><?php echo $name; ?></div>
<div><?php echo $owner; ?></div>
</td>
<td style="width: 200px;">
<div style="height: 100px;"><?php echo $current; ?></div>
<div style="height: 50px;"><?php echo $instant; ?></div>
<div><?php echo $inc; ?></div>
</td>
<td><?php echo $time; ?></td>
</tr>
<?php
i++;
} //end of while
} //end of else
?>
<tr>
<td colspan="4">Displaying <?php echo $numrows; ?> results</td>
</tr>
</table>
</html>
And also consider preventing SQL Injection too: http://bobby-tables.com/

I think you would be much better off if you separated your php and html into separate files. You seem to be losing track of your opening " and closing ". If you want your
<tr> Displaying $numrows results</tr>
at the bottom of your page, then take it out of the table.

I'd suggest simplifying your table a little bit, maybe taking the 'Displaying $numrows results' out of the table entirely.
The line '<tr> Displaying $numrows results</tr>' is not valid HTML. <tr> means 'Define a new table row', but it needs a <td> inside it to wrap the content. Because most rows of your table contain several TD elements, whilst this row only contains one piece of information, you would need to tell that table cell to span multiple columns.
A good way of debugging this sort of thing is to feed the generated HTML to http://validator.w3.org/, or replace the $variables with sample data and feed the template code to a validator. This is usually a little frustrating at first (as it will force you to be exact about the HTML version you want to use, etc) but it is a good way of tracing problems. If you feed the following HTML snippet into the W3 validator, it will give you some useful feedback:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head><title>A</title></head>
<body>
<table><tr><td>aaa</td><td>bbb</td></tr>
<tr><td>cccc</td><td>dddd</td></tr>
<tr>Test</tr>
</table>
</body>
</html>
The validator tells you that: Line 7, Column 5: character data is not allowed here
<tr>Test</tr>
In other words, the TR element should not directly contain text.
It also says that: Line 7, Column 13: end tag for "tr" which is not finished
<tr>Test</tr>
"Most likely, you nested tags and closed them in the wrong order... Another possibility is that you used an element which requires a child element that you did not include. Hence the parent element is "not finished", not complete. For instance, in HTML the <head> element must contain a <title> child element, lists require appropriate list items (<ul> and <ol> require <li> ...), and so on."
Once you have the static HTML looking, and validating, the way you want, you can then add the PHP loops back in, but this time you can compare the script output to your working HTML example.

Related

How to make a unordered list using fetch_assoc from database and arrays

Trying to create a list by selecting booking references from the database, sorting them into an array and then having each array value passed into each item on the list. e.g. first booking reference on the first item, second reference on the second item etc...
Here is the code.
<html>
<head>
<title>Manage booking</title>
<link rel="stylesheet" type="text/css" href="style1.css">
</head>
<body>
<h3>Oadby Granville Tennis Club Manage Booking</h3>
<br><br><br>
<?php
include "dbconnect.php";
session_start();
$login_ID = $_SESSION['id'];
$query = "SELECT Booking_ID
FROM `booking`
WHERE Login_ID = '$login_ID';";
$bookingArray = array();
$result = $mysqli -> query($query);
while ($row = $result->fetch_assoc()){
printf ("%s<br>", $reference = $row["Booking_ID"]);
array_push($bookingArray, $reference . "<br>");
}
print_r ($bookingArray);
?>
<table border="1" style="width:50%">
<caption>Please select a booking to edit:</caption>
<tr>
<td>
<ul style="list-style-type:circle">
<?php
$arrayNo = 1;
while ($row = $result->fetch_assoc()){
printf ("<li><a href='UpdateBooking.php'>Booking ID:%s</a>" . $bookingArray[$arrayNo] . "</li><br>");
$arrayNo = $arrayNo + 1;
}
?>
<li>Booking ID</li>
</ul>
</td>
</tr>
</body>
</html>
Your first while ($row = $result->fetch_assoc()) {..} transfers everything into $bookingArray until the result set is exhausted. With your second while ($row = $result->fetch_assoc()) {..} you don't get anything more. Additionally, your use of printf is weired.
Try this instead your second loop:
foreach($bookingArray as $Booking)
{
echo "<li><a href='UpdateBooking.php'>Booking ID:$Booking</a></li><br>";
}
However, UpdateBooking.php wont know which booking should be changed. So you should consider to append the BookingId to the URL.
Edit 2016-03-02:
To append the BookingId to the URL you should try:
foreach($bookingArray as $Booking)
{
echo "<li><a href='UpdateBooking.php?BookingId=" . urlencode($Booking) . "'>Booking ID:$Booking</a></li><br>";
}

Using arrays in PHP/MySQL

Hi I'm using file_get_contents() to search an off site text file, which returns an array as follows:
$foo_data = file_get_contents('http://foo/data_csv.php?code='.$row->code);
$foo_code = explode(",",$foo_data);
$foo_id = $foo_code[9];
If I place the above lines before the MySQL Select statement then the $foo_data variable is empty as it hasnt been initialised yet.
How do I reference this variable in the MySQL statement eg:
SELECT `field1`, `field2`, COUNT(distinct $foo_id) AS Ref
I've tried:
SELECT `field1`, `field2`, COUNT(distinct {$foo_id}) AS Ref
SELECT `field1`, `field2`, COUNT(distinct '{$foo_id}') AS Ref
Anyone know if it's possable to reference a table row from the array obtained in the above file_get_contents() ?
Complete code as follows:
<?php
include $_SERVER['DOCUMENT_ROOT']. '/class2.php';
Global $currentUser;
$user_name = $currentUser['user_loginname'];
$user_call = strtoupper($user_name);
$user_region = $currentUser['user_region'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<?
include("db_uploadlog.php");
if (!file_exists("db_uploadlog.php")) {
echo "Error - Config file is missing!";
}
else
{
$db_2 = mysql_connect($database_host, $database_username, $database_password);
mysql_select_db("db_name") or die("Cannot select database");
$foo_data = file_get_contents('http://foo.com/data_csv.php?code='.$row->code);
$foo_code = explode("|",$foo_data);
$foo_id - $foo_code[9]
$result = mysql_query("SELECT `column1`, `column1_id`, `code`, `column1_region`, '{$foo_id}' AS score FROM $table GROUP BY `column1` ORDER BY score DESC", $db_2);
$rowpos = mysql_num_rows($result);
$mnum = 1;
$mnum2 = 1;
if(mysql_num_rows($result) > 0)
{
?>
<table width="100%" align="center" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="2%"><b>Pos</b></td>
<td><b>Code</b></td>
<td width="10%"><b>Score</b></td>
</tr>
<?
for($i = 0; $i < mysql_num_rows($result); $i++)
{
$row = mysql_fetch_object($result);
?>
<tr>
<td><? echo $mnum2; ?></td>
<td><? echo $row->column1; ?></td>
<td><? echo $row->score; ?></td>
</tr>
<?
$mnum2 = $mnum2 + 1;
$mnum = $mnum + 1;
}
mysql_free_result($result);
mysql_close($db_2);
?>
</table>
</div>
<?
}
}
?>
</body>
</html>
Edited according to comment:
Then your problem is that file_get_contents don't recover data, you have to activate the property allow_url_fopen, set this property to 1 on your php.ini and your code should work
But i recommend you to use curl instead of file_get_contents you will have more control and curl was designed for this isn't it?
"If I place the above lines before the MySQL Select statement then the $foo_data variable is empty as it hasnt been initialised yet. "
This is probably because you reference the results from the MySQL select in your file_get_contents.
Other than that it should work, you are basically making a string in PHP and sending it to the MySQL server for parsing. So to MySQL it wont matter if you type it in by hand or if you use some pregenerated value.
Though, you need to trust the source if you are assembling the string from external sources, otherwise you should use PDO with bindParam.
edit
I see my initial thought was correct,
$foo_data = file_get_contents('http://foo.com/data_csv.php?code='.$row->code);
Here $row->code hasn't been initialized yet so file_get_contents goes to "http://foo.com/data_csv.php?code=" (if it goes anywhere at all).
You need to have another select above $foo_data which sets $row->code.
PHP normally shows an error message, but you probably are running on production mode. If you are testing you can put this in the top of your document
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
?>
Which should help you debug your script a bit better.

Generate report from mysql, errors appear

heres my code , when i first try to display all the data from my database using my query it appears, but when i add this to my query WHERE SECTION = '$.thissection'" i got pdf error , and it doest work even i have set the POST to call the value on my page, what is wrong of my codes , please i really need it,
include_once( 'dompdf\dompdf_config.inc.php');
$html = '<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="container">
<caption><h2 style="margin-left: 180px;">St. Therese Lisioux School of Cainta </h2></caption>
<table class="zebra">
$thissubject = $_POST['subject'];
$thissection = $_POST['section'];
$thisgrade_level = $_POST['grade_level'];
$sqlQuery = mysql_query("SELECT si.STUDENT_ID, concat(si.LNAME,', ',si.FNAME) as Name,
sg.*
From student_info si Left join grades sg On si.STUDENT_ID = sg.STUDENT_NO
WHERE SECTION = '$.thissection'");
while($row = mysql_fetch_assoc($sqlQuery))
{
$student_id = $row['STUDENT_NO'];
$Name = $row['Name'];
$SUBJECT_NAME = $row['SUBJECT'];
$first_Grading = $row['FIRST_GRADING'];
$second_Grading = $row['SECOND_GRADING'];
$third_Grading = $row['THIRD_GRADING'];
$fourth_Grading =$row['FOURTH_GRADING'];
$final = $row['FINAL'];
$status = $row['STATUS'];
$html .= '<tbody>
<tr class="warning">
<td>'.$student_id.'</td>
<td>'.$Name.'</td>
<td>'.$SUBJECT_NAME.'</td>
<td>'.$first_Grading.'</td>
<td>'.$second_Grading.'</td>
<td>'.$third_Grading.'</td>
<td>'.$fourth_Grading.'</td>
<td>'.$final.'</td>
<td>'.$status.'</td>
</tr>
</tbody>';
}
$html .= ' </table>
</div>
</body>
</html>
';
$dompdf = new DOMPDF();
$dompdf ->set_paper("a4", "landscape");
$dompdf ->load_html($html);
$dompdf ->render();
$dompdf ->stream('Student_report.pdf');
?>strong text
Your codes have severe PHP syntax errors.
You use PHP codes within a single-quoted string variable, which is not parsed by PHP parser.
Also, you didn't escape the the codes.
Use slash instead of backslash in include_once()
You didn't initialize your MySQL connection
stop using deprecated mysql_* functions and your code is subjected to SQL Injection attack, as you directly allow POST values to be inserted in your query. use MySQLi or PDO instead. Here is a good tutorial for PDO.
Your HTML lacks <title>
Where is your error handling mechanism? You expect no errors for all sorts of inputs?
For a quick fix, change the line:
<table class="zebra">
to
<table class="zebra">';
in order to end the $html variable.

it wont sum up, what is wrong with my code?

I want to be able to sum up all the revenue that is being displayed in the page and it auto sums every time I added another data to the revenue column:
Following is my code :
<?php
require_once('Connections/connect.php');
$id_customer = mysql_real_escape_string($_GET['id_customer']);
$sql_PK = "SELECT * FROM tbl_delivery_details WHERE tbl_customer_id_customer = {$id_customer}";
$PK = mysql_query($sql_PK, $connect);
if ( mysql_error() ) {
die ( mysql_error());
}
$row_PK = mysql_fetch_assoc($PK);
$customer_name = $row_PK['tbl_customer_id_customer'];
$customer_name = mysql_real_escape_string($customer_name);
$sql = "SELECT tbl_customer.customer_name,
tbl_delivery_details.delivery_details_route,
tbl_delivery_details.delivery_details_destination,
tbl_delivery_details.delivery_details_van_no,
tbl_delivery_details.delivery_details_waybill_no,
tbl_delivery_details.delivery_details_charge_invoice,
tbl_delivery_details.delivery_details_revenue,
tbl_delivery_details.delivery_details_strip_stuff,
tbl_delivery_details.delivery_details_date
FROM tbl_customer, tbl_delivery_details
WHERE tbl_customer.id_customer = tbl_delivery_details.tbl_customer_id_customer
AND tbl_customer.id_customer = '{$customer_name}'";
$res = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($res);
$sum = 0;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/x html">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Customer Revenue</title>
<link rel="stylesheet" type="text/css" href="qcc.css"/>
</head>
<body>
<table border="1">
<tr>
<th>Reveneu</th>
</tr>
<?php do { ?>
<tr>
<td><?php echo $row_PK['delivery_details_revenue'];?></td>
</tr>
<?php } while ($row_PK = mysql_fetch_assoc($PK));?>
<?php { ?>
<?php $sum+=$row_PK['delivery_details_revenue'] ?>
<?php } ?>
</table>
<?php echo $sum; ?>
</body>
</html>
When I load the page echo $sum always is zero how to correctly sum up the column I made that it will sum automatically if I add another data to it :
Instead of adding the revenue values up in PHP, why not have MySQL do it for you in the query?
$sql = "SELECT SUM(tbl_delivery_details.delivery_details_revenue) as revenue,
tbl_customer.customer_name,
tbl_delivery_details.delivery_details_route,
tbl_delivery_details.delivery_details_destination,
tbl_delivery_details.delivery_details_van_no,
tbl_delivery_details.delivery_details_waybill_no,
tbl_delivery_details.delivery_details_charge_invoice,
tbl_delivery_details.delivery_details_revenue,
tbl_delivery_details.delivery_details_strip_stuff,
tbl_delivery_details.delivery_details_date
FROM tbl_customer, tbl_delivery_details
WHERE tbl_customer.id_customer = tbl_delivery_details.tbl_customer_id_customer
AND tbl_customer.id_customer = '{$customer_name}'";
And then in youru view, just echo the SUM figure...
echo $row_PK['revenue'];
If I read this correctly, you're summing up the values outside of your while loop. That won't work.
I think you're mixing up a normal while loop, and a 'do while' loop.
See this code:
<?php do { ?>
<tr>
<td><?php echo $row_PK['delivery_details_revenue'];?></td>
</tr>
<?php } while ($row_PK = mysql_fetch_assoc($PK));?>
<?php { ?>
<?php $sum+=$row_PK['delivery_details_revenue'] ?>
<?php } ?>
It should be more along these lines:
<?php do { ?>
<tr>
<td><?php
echo $row_PK['delivery_details_revenue'];
$sum+=$row_PK['delivery_details_revenue']
?>
</td></tr>
<?php } while ($row_PK = mysql_fetch_assoc($PK));?>
this wouldn't happen if you would write the code a bit more clearly; try to avoid interleaving html and php so much:
<?php
do {
$revenue = $row_PK['delivery_details_revenue'];
$sum += revenue;
println("<tr><td>$revenue</td></tr>");
} while ($row_PK = mysql_fetch_assoc($PK));
?>
This is a lot clearer, if you ask me.
Well, I don't have a PHP interpreter in my head to run your code on sight. So, just a few things which I can spot
First, there is an SQL injection in your first query. Either cast your variable to integer
$id_customer = intval($_GET['id_customer']);
or treat it as a string in your query
$sql_PK = "SELECT * FROM tbl_delivery_details WHERE tbl_customer_id_customer = '$id_customer'";
or - better yet - use some database wrapper that allows you to use placeholders to represent actual data in the query.
Next, your query is incredible hard to read.
If your field names do not interfere, there is no reason to use table.field notation then.
Also use shortland aliases and consider using * if you want most of the fields from the table:
$sql = "SELECT SUM(delivery_details_revenue) as revenue,
customer_name, tbl_delivery_details.*
FROM tbl_customer, tbl_delivery_details
WHERE id_customer = tbl_customer_id_customer
AND id_customer = '$customer_name'";
By the way, while editing your query, I've noticed inconsistent naming: id_customer = '$customer_name'. Don't confuse yourself with wrong variable names. If it's id, then call it "id", not "name"
And also I see no point in the first query at all, if id_customer is equal to tbl_customer_id_customer. I think you need to simplify your code - it's compexity is the main reason why you're not getting your results, I believe.
Start from very simple query like
$sql = "SELECT SUM(delivery_details_revenue) as revenue,
FROM tbl_delivery_details
WHERE tbl_customer_id_customer = '$id_customer'";
and see if it returns anything.
If so - start adding some more data to fetch.
If no - check your data and overall data structure if it's all right.

Create table with PHP and populate from MySQL

I am creating a table to display on a web page and that table is populated from data in a MySQL database. I am trying to do a couple of things that are making it difficult for me.
First I am trying to have call the PHP code that exists in a separate file in HTML via JavaScript. I think I have that working right but I am not 100% sure (because the table will not display). I think it is working right because some of the code for the table (which is in the PHP file) displays in FireBug.
Second I am trying to make it so the rows alternate colors for easy viewing too. My PHP code so far is below. The table does not display at all in any browser.
$query = "SELECT * FROM employees";
$result = mysql_query($query);
$num = mysql_num_rows($result);
echo '<table>';
for ($i = 0; $i < $num; $i++){
$row = mysql_fetch_array($result);
$id = $row['id'];
$l_name = $row['l_name'];
$f_name = $row['f_name'];
$ssn = $row['ssn'];
$class = (($i % 2) == 0) ? "table_odd_row" : "table_even_row";
echo "<tr>";
echo "<td class=" . $class . ">$wrap_id</td>";
echo "<td class=" . $class . ">$wrap_l_name</td>";
echo "<td class=" . $class . ">$wrap_f_name</td>";
echo "<td class=" . $class . ">$wrap_ssn</td>";
echo "</tr>";
}
echo '</table>';
mysql_close($link);
}
EDIT
To answer a few questions:
#controlfreak123, I am not sure what you mean by "include ('filename_with_php_in_it')". As far as the page not being called to be parsed, I think it is being called and contact is being made. I pointed out in my original question that I believe this is true because FireBug shows the code for the table, and that code is in separate PHP file, thus communication between the HTML file and the PHP file must be taking place. Here is how I am calling the PHP file from the HTML file you if you care to know:
<script language="javascript" type="text/javascript" src="/Management/Employee_Management.php?action=Edit_Employee"></script>
#Matt S, I am not getting much in the way of output, in fact I didn't know I was getting anything at all until I looked at FireBug and saw that the PHP code (or some of it) was indeed being passed to the HTML file. The specific question is how do I get the data I want from my MySQL database and populate it into an HTML table via PHP. I can also confirm that employees does have data in it, two entries I put in for testing. I can try to put the code into its own file without the JavaScript as you suggested, but that would defeat my purpose since I want my HTML and PHP files to be separate, but I may try it just to see if the PHP code is good and to make sure the JavaScript isn't breaking it.
#Aaron, I am not sure what you are asking (sorry). The code is meant to populate create and populate a table on an HTML page.
Here is a full example of what you're looking for:
pull some data from mysql using php
put that data into an html table
apply alternating colored rows to the table
For the styling I cheat a little and use jquery which I find a bit easier then what you're trying to do.
Also, remember $row[field] is case sensitive. So $row[id] != $row[ID].
Hope this helps:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<style type="text/css">
tr.header
{
font-weight:bold;
}
tr.alt
{
background-color: #777777;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$('.striped tr:even').addClass('alt');
});
</script>
<title></title>
</head>
<body>
<?php
$server = mysql_connect("localhost","root", "");
$db = mysql_select_db("MyDatabase",$server);
$query = mysql_query("select * from employees");
?>
<table class="striped">
<tr class="header">
<td>Id</td>
<td>Name</td>
<td>Title</td>
</tr>
<?php
while ($row = mysql_fetch_array($query)) {
echo "<tr>";
echo "<td>".$row[ID]."</td>";
echo "<td>".$row[Name]."</td>";
echo "<td>".$row[Title]."</td>";
echo "</tr>";
}
?>
</table>
</body>
</html>
Here's the table code only using PHP to alternate the styles like you're trying to do in your example:
<table class="striped">
<tr class="header">
<td>Id</td>
<td>Title</td>
<td>Date</td>
</tr>
<?php
$i = 0;
while ($row = mysql_fetch_array($query)) {
$class = ($i == 0) ? "" : "alt";
echo "<tr class=\"".$class."\">";
echo "<td>".$row[ID]."</td>";
echo "<td>".$row[Name]."</td>";
echo "<td>".$row[Title]."</td>";
echo "</tr>";
$i = ($i==0) ? 1:0;
}
?>
</table>
The reason your code is not executing is that you cannot include PHP with the Script tag. You must use PHP's include function, and the original page must be parsed as PHP.
<?php
include('./my_other_file.php');
?>
The starting of the coding is a little bit wrong. It should be:-
<?php
$query = "SELECT * FROM employees";
$result = mysql_query($query);
$num = mysql_num_rows($result);
echo '<table>';
if($num) {
while( $row = mysql_fetch_array($result) ) {
// all logic for each of the rows comes here
}
}
else {
// no rows fetched, so display proper message in a row
}
echo "</table>";
?>
The first time "mysql_fetch_array" function is used on a Resource Handler, after that it does not work properly. This answer may seem a bit vague, but I have seen it many times, so I always use a "while" or "do-while" loop for fetching multiple rows from DB.
Try using the above code, & see if any information crops up.

Categories