Using arrays in PHP/MySQL - php

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.

Related

PHP + MySQL + Cookies, why is this not loading properly?

I've got a PHP page with 2 MySQL statements in various parts of the code. I'm using the generated result sets to set cookie values then call it later. Yet, when I call the cookie data, it does not update the display of the cookie values until after a 2nd refresh. To Better understand, Here's the 3 sections of code:
<?php
include 'functions.php';
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$SqlStatement = "SELECT Deceased.PK_Deceased, Deceased.Date_Death, Personal_Info.First_Name, Personal_Info.Last_Name FROM Deceased INNER JOIN Personal_Info ON Personal_Info.PK_Personal_Info = Deceased.FK_Personal_Info WHERE Deceased.FK_Personal_Info = '".$_POST['cboDeceased']."'";
$result = ExecuteSql($SqlStatement);
if(mysqli_num_rows($result) == 1)
{
$row = mysqli_fetch_array($result);
setcookie('deceasedID', $row['PK_Deceased'], time()+360000, '/');
setcookie('deceasedName', ($row['First_Name']." ".$row['Last_Name']), time()+360000, '/');
setcookie('deceasedDoD', $row['Date_Death'], time()+360000, '/');
}
}
?>
This is the code that pulls the data from the postback. I think that this is the part that is incorrect, but I'm not sure.
<tr>
<td width="25%" rowspan="2" align="center">Current User: <?php echo $_COOKIE['username']; ?> </td>
<td width="25%" rowspan="2" align="center">Current Deceased: <?php if(isset($_COOKIE['deceasedName']))echo $_COOKIE['deceasedName']; ?></td>
<td width="50%" rowspan="2" align="center">Deceased Date of Death: <?php if(isset($_COOKIE['deceasedDoD']))echo $_COOKIE['deceasedDoD']; ?></td>
This is the code to load the cookie data into fields and the part that takes the 2nd refresh to display properly.
<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<table align="center" width="500" border="0.5">
<tr>
<td width="176" align="right" style="font-weight:bold;">Please select deceased:</td>
<td width="214">
<select name="cboDeceased" id="cboDeceased">
<option>Select...</option>
<?php
$SqlStatement = "SELECT Deceased.PK_Deceased , Personal_Info.First_Name, Personal_Info.Last_Name FROM Deceased INNER JOIN Personal_Info ON Personal_Info.PK_Personal_Info = Deceased.FK_Personal_Info";
$res = ExecuteSQL($SqlStatement);
while($row = mysqli_fetch_array($res))
{
echo "<option value='".$row['PK_Deceased']."'>".$row['First_Name']." ".$row['Last_Name']."</option>";
}
?>
This is the code that passes a variable based on ID to the 1st code block. This part works fine.
function ExecuteSQL($SQL)
{
$con = mysqli_connect("localhost", "root", "", "exec_support_db");
$res = mysqli_query($con, $SQL);
mysqli_close($con);
return $res;
}
Here's the code for the ExecuteSQL function. I know that this isn't the problem.
I think the problem is up above in the 1st code block, but I'm not sure. I've tried everything I can and am now out of ideas. Any help would be appreciated.
Beyond the SQL injection mentioned above by DaveRandom take a look at the php manual on how setcookie works:
http://php.net/manual/en/function.setcookie.php
It mentions specifically the info is injected into the headers, and therefor not available until your next page load. You probably want to do something like
if(isset($_COOKIE['deceasedID']))
{
$deceasedID = $_COOKIE['deceasedID'];
}
else
{
setcookie('deceasedID', $row['PK_Deceased'], time()+360000, '/');
$deceasedId = $row['PK_Deceased'];
}

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.

display php search results in html table

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.

msql fetch array no longer listing all results

I have a code that I have used over and over again before and now it's messing up. All I want to do is list information from the database into the table on the page, but now it will only show one result, instead of all the results it has found.
<table>
<tr><td style="background-color:#009745; color:#FFFFFF"><center><strong>Address Book</strong></center></td></tr>
<tr>
<?php
$getids = mysql_query("SELECT id, first_name, last_name FROM accounts WHERE s1='$id' ORDER BY id DESC", $db);
if (mysql_num_rows($getids) > 0) {
while ($gids = mysql_fetch_array($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
}
?>
<td><?= $ab_id ?> - <?= $ab_fn . " " . $ab_ln ?></td>
<?php
} else {
?>
<td><center>No Contacts</center></td>
<?php
}
?>
</tr>
</table>
please help me with this.
Thank You for your help :)
I love this site!! I can always get answers when I need them.
I saw two thing wrong
you are using mysql_fetch_array and later you are using string indexes to print the result
print the things in loop it is overriding values and just storing last row
if (mysql_num_rows($getids) > 0) {
while ($gids = mysql_fetch_assoc($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
echo '<td>'.$ab_id.' -'. $ab_fn.''.$ab_ln.' </td>';
}
In this messy code you're closing the while loop too early:
while ($gids = mysql_fetch_array($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
}
Only the last retrieved row is used later on. Also, don't use mysql_fetch_array if you're not accessing the numeric indeces of your result. Use mysql_fetch_assoc instead.

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