Create table with PHP and populate from MySQL - php

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.

Related

How do i print/show a result from a php query (mysqli) in a HTML page

I've searched hard to find a way to print the query of the code above into a HTML part, but i don't find anything. I saw that is possible to present the result by a HTML table using the fetch_assoc() of php. Below is the code, and on a global view the code is fine, because i test it on a full php page. But i need a solution to put it in HTML. Am i trying an impossible thing?
<?php
require_once('connconf.php');
$conn = mysqli_connect($server, $user, $pw, $bdname) or die ('Connection Error');
$sqlquery = "select ID_Vote from Votes where ID_Player = '1'";
if($result = mysqli_query($conn, $sqlquery)) {
$rowcount = mysqli_num_rows($result);
echo $rowcount; //this is the value i want to publish on a HTML <label>
}
?>
If you want to output the results in a table you could do like this:
print "<table>";
while($row = mysqli_fetch_assoc($result)) {
print "<tr><td>".$row['ID_Vote']."</td></tr>";
}
print "</table>";
The same goes if you just want to print the amount of rows:
print "<table>";
print "<tr><td>".$rowcount."</td></tr>";
print "</table>";
Another way of doing it could be to end php:
<?
// Some code
?>
<table>
<tr>
<td><?=$rowcount;?></td>
</tr>
</table>
<?
// More php
?>
You can have a read here
Guys i found the solution to my problem, all the query was ok like i said. But the extension of my webpage was .HTML and when i change it to .php it worked. Now i got the website running with HTML and php code using a .php extension instead .html
Thanks for your attention.

Loop through database record to generate table

I want to construct an html table based on the returned results from the database. Assuming I have a table called constraints in my database and a column called riskName and it has these values: Security, Financial, Legal and Technical as shown in the image below. How do i loop through my database and come up with this table. I have tried different approach but no has worked. Here is my code so far:
<?php
error_reporting(0);
$optioner = 12;
$getObs = $db->prepare("SELECT * FROM constraints WHERE constraintsID = ?");
$riski->bindParam(1, $optioner);
$riski->execute();
$result = $riski->fetch(PDO::FETCH_ASSOC);
while($getObs->fetch(PDO::FETCH_ASSOC)){
echo "<tr><td>".($result['riskName'])."<td><tr>";
//...other code
}
?>
</tbody>
<?php };
?>
I'm not sure if this will give you the exact table you're looking for, but it should at least put you on the right lines. Also, you weren't keeping your variables the same and notice how $result is set in the while loop
$optioner = 12;
$riski = $db->prepare("SELECT * FROM constraints WHERE constraintsID = ?");
$riski->bindParam(1, $optioner);
$riski->execute();
?>
<form>
<table>
<tr> <th>i</th> <th>Importance</th> <th>How Much More?</th> <tr>
<?php
while($result = $riski->fetch(PDO::FETCH_ASSOC)){
echo '<tr>';
echo '<td>'. $result['riskName']).'<td>';
echo '<td>';
for ($i=1;$i<10;$i++){
//radio buttons go here
}
echo'<tr>';
//...other code
}
?>
Sorry I couldn't help more.
Hope this works for you.

Retrieving mysql table data that is stored within a php variable array

My connection to my database was successful. I now have all of the data from a table stored as an array in a php variable named $data. I am trying to extract three rows from this variable and display them with html.
Here is what my code looks like (with the exception of the connection info being removed):
<?php
$data = mysql_query("SELECT * FROM specs")
or die(mysql_error());
while ($row = mysql_fetch_assoc($data)) {
$rows[] = $row;
?>
I know that I can pull individual data from this variable and insert it into html successfully by entering code like this (for example):
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td>Model: <?php echo $row['name'];?></td>
</tr>
</table>
But my problem is that I want to display three separate rows of data from the database as three individual columns in a html table. (Hope that makes sense)
I've looked into how to do this with foreach and while but am not quite sure where I'm going wrong.
I'm hoping someone might be able to shed some light on this as I have read about foreach loops, while, and am still stuck! I'm also hearing that mysql_query is deprecated but ruled out not using this since our webserver is still using an old version of php and mysql and is not planning to update anytime soon.
Sorry if I'm not all here in my post - it's late and I'm tired. Thanks for your help in advance! I'll keep an eye on this in case anyone has questions.
This will print the array in a table with each row being 3 elements of the array.
echo "<table>";
for ($i = 0; $i < count($rows); $i += 3) {
echo "<tr>";
for ($j = 0; $j < 3; $j++) {
if (isset($rows[$i+$j]) {
echo "<td>Model: {$rows[$i+$j]['name']}</td>";
}
}
echo "</tr>";
}
echo "</table>";
It's simpler to limit the SQL to three rows, and then echo all incoming rows directly, without first adding to an array. That would waste resources.
<?php
echo "<table>";
$data = mysql_query("SELECT * FROM specs LIMIT 3")
or die(mysql_error());
while ($row = mysql_fetch_assoc($data))
echo '<tr></td>', $row['name'], '</td></tr>';
echo "</table>";
?>
Ah, but now I see it's a year old question. I hope you learned a lot in the meantime.

Is it possible to Query a Mysql database from a field selected from dropdown menu populated from a Query in php

Hello i am new to php and i have tried to find a piece of code that i can use to complete the task i need, i currently have a page with a form set out to view the criteria of a course. also i have a dropdown menu which currently holds all the course codes for the modules i have stored in a database. my problem is when i select a course code i wish to populate the fields in my form to show all the information about the course selected. The code i am trying to get to work is as follows:
<?php
session_start();
?>
<? include ("dbcon.php") ?>
<?php
if(!isset($_GET['coursecode'])){
$Var ='%';
}
else
{
if($_GET['coursecode'] == "ALL"){
$Var = '%';
} else {
$Var = $_GET['coursecode'];
}
}
echo "<form action=\"newq4.php\" method=\"GET\">
<table border=0 cellpadding=5 align=left><tr><td><b>Coursecode</b><br>";
$res=mysql_query("SELECT * FROM module GROUP BY mId");
if(mysql_num_rows($res)==0){
echo "there is no data in table..";
} else
{
echo "<select name=\"coursecode\" id=\"coursecode\"><option value=\"ALL\"> ALL </option>";
for($i=0;$i<mysql_num_rows($res);$i++)
{
$row=mysql_fetch_assoc($res);
echo"<option value=$row[coursecode]";
if($Var==$row[coursecode])
echo " selected";
echo ">$row[coursecode]</option>";
}
echo "</select>";
}
echo "</td><td align=\"left\"><input type=\"submit\" value=\"SELECT\" />
</td></tr></table></form><br>";
$query = "SELECT * FROM module WHERE coursecode LIKE '$Var' ";
$result = mysql_query($query) or die("Error: " . mysql_error());
if(mysql_num_rows($result) == 0){
echo("No modules match your currently selected coursecode. Please try another coursecode!");
} ELSE {
Coursecode: echo $row['coursecode'];
Module: echo $row['mName'];
echo $row['mCredits'];
echo $row['TotalContactHours'];
echo $row['mdescription'];
echo $row['Syllabus'];
}
?>
however i can only seem to get the last entry from my database any help to fix this problem or a better way of coding this so it works would be grateful
Thanks
The main error is in your final query, you're not actually fetching anything from the query, so you're just displaying the LAST row you fetched in the first query.
Some tips:
1) Don't use a for() loop to fetch results from a query result. While loops are far more concise:
$result = mysql_query(...) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
...
}
2) Add another one of these while loops to your final query, since it's just being executed, but not fetched.
For me i would use some javascript(NOTE: i prefer jQuery)
An easy technique would be to do this(going on the assumption that when creating the drop downs, your record also contains the description):
Apart from creating your dropdown options like this <option value="...">data</option>, you could add some additional attributes like so:
echo '<option value="'.$row['coursecode'].'" data-desc="'.$row['description'].'">.....</option>
Now you have all your drop down options, next is the javascript part
Let's assume you have included jQuery onto your page; and let's also assume that the description of any selected course is to be displayed in a <div> called description like so:
<div id="course-description"> </div>
<!--style it how you wish -->
With your javascript you could then do this:
$(function(){
$("#id-of-course-drop-down").change(function(){
var desc = $(this).children("option").filter("selected").attr("data-des");
//now you have your description text
$("#course-description").html(desc);
//display the description of the course
}
});
Hope this helps you, even a little
Have fun!
NOTE: At least this is more optimal than having to use AJAX to fecch the description on selection of the option :)

jQuery doesn't work on elements echoed via PHP

What I have is a PHP code that generates a html table from mysql database, and then I'm trying to use a jQuery addon that makes the table sortable. I've had this problem many times and can't seem to find a solution anywhere... why doesn't jQuery (or is it Javascript period?) work on a PHP output? Isn't there a way around this?
Here's the code:
<html><head>
<title>MySQL Table Viewer</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="http://tablesorter.com/jquery.tablesorter.min.js"></script>
<script src="http://tablesorter.com/addons/pager/jquery.tablesorter.pager.js"></script>
<script>
$(document).ready(function()
{
$("#mytable").tablesorter();
}
);
</script>
</head><body>
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = 'lptm42b';
$database = 'sphinx';
$table = 'spheres';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
// sending query
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
echo "<h1>Table: {$table}</h1>";
echo "<table id=\"mytable\" border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysql_free_result($result);
?></table>
</body>
</html>
Output is:
<html><head>
<script src="../js/jquery_plugin.tablesorter.min.js"></script>
<script src="../js/jquery-1.6.min.js"></script>
<script src="../js/jquery_plugin.tablesorter.pager.js"></script>
<title>MySQL Table Viewer</title></head><body>
<h1>Table: lobby</h1><table id="mytable" border='1'><thead><tr><td>tableid</td> <td>name</td><td>datecreated</td><td>active</td></tr></thead>
<tbody><tr><td>12341231241</td><td>Oyunum1</td><td>2011-05-09 14:26:51</td><td>0</td> </tr>
<tr><td>6677768</td><td>m2</td><td>2011-05-05 14:26:39</td><td>1</td></tr>
<tr><td>ddf1</td><td>m3</td><td>2011-05-09 14:27:19</td><td>0</td></tr>
<tr><td>7856844444</td><td>m4</td><td>2011-05-09 14:27:31</td><td>0</td></tr>
<tr><td>xxxxde4rfd</td><td>m5</td><td>2011-05-09 14:27:43</td><td>0</td></tr>
</tbody></table>
</body></html>
<script>
$(document).ready(function()
{
$("#mytable").tablesorter();
}
);
</script>
UPDATE: For some reason syntax coloring is lost at the end / script> tag in chrome view source
tablesorter plugin requires THEAD and TBODY tags in table for it to work
You don't gave a #mytable element.
You need to use a selector that matches an element that actually exists.
EDIT: Your PHP has mis-nested quotes, so the ID isn't actually in the string.
Look at the page source.
you should add the ID for the table with "mytable" .
Also alsways put thead, tbody in table tags for better output while using JQuery.
Late coming to this party, but you need to know that document.ready won't pick up dynamically generated html if that html is generated AFTER the dom is loaded initially. There are jQuery plugins to work around this (liveQuery is one of them), but the Document.Ready event fires once per page load, and if the PHP that generates the html is fired AFTER that, then the tablesorter method you call has nothing to sort.
Javascript is a client-side technology, meaning to get it work with elements generated directly by the server through php, there are some gymnastics involved.
Try to read up on the json_encode() function in PHP and ajax calls in general.
Also, you might be interested in the .delegate() jQuery method.

Categories