could you please help me out?
I need to show a registry of a .dbf table in php and have the following code.
<html>
<form method="get">
<input type="text" name="nrdoc"></input>
<input type="submit"></input>
</form>
<?php
if(isset ($_GET['nrdoc'])){
$thefile = "winges/vcabdoc.DBF";
if($thefile){
include('./dbf_class.php');
$dbf = new dbf_class($thefile);
$num_rec=$dbf->dbf_num_rec;
$field_num=$dbf->dbf_num_field;
$endexct = $timer->end();
echo("<blockquote>File Name : $thefile<br>Number of Records : $num_rec<br>Number of Fields : $field_num</blockquote>");
echo('<table border=1 cellspacing=0>');
echo('<tr>');
echo('<td>No. </td>');
for($j=0; $j<$field_num; $j++){
echo '<td> '.$dbf->dbf_names[$j]['name'];
if ($dbf->dbf_names[$j]['type']!='M') {
echo '<br>Length='.$dbf->dbf_names[$j]['len'];
}
echo '<br>Type='.$dbf->dbf_names[$j]['type'].'</td>';
}
echo '</tr>';
$i=$_GET['nrdoc'];
if ($row === $dbf->getRow("SELECT *, FROM winges/vcabdoc.dbf WHERE 'VCANUM' == $i")) {
echo('<tr>');
echo('<td align="right">'.str_pad($i+1, 3, "0", STR_PAD_LEFT).'</td>');
for($j=0; $j<$field_num; $j++){
if ($dbf->dbf_names[$j]['type']=='N') {
echo '<td align="right">';
}
else {
echo '<td align="left">';
}
echo htmlentities($row[$j]).' </td>';
}
echo '<tr>';
}
}
echo('</table>');
}
?>
</html>
The dbf_class.php is from http://www.phpclasses.org
And it always returns the first data line on the database, please help me.
Thanks in advance.
João
I found an easy way to extract data from .dbf using perl library XBASE
Using this library I wrote a small scripts which reads given file and outputs a json string.
# foxpro2json.pl
use File::Basename;
use XBase;
$filename=$ARGV[0];
my $table = new XBase $filename or die XBase->errstr;
my #fields = $table->field_names;
my $cursor = $table->prepare_select();
my $return = '';
my $i = 0;
while (my #row = $cursor->fetch) {
$json = '{';
$i = 0;
foreach $val (#row) {
$val =~ s/(['"\/\\])/\\$1/g;
$json .= '"'.$fields[$i].'":"'.$val.'",';
$i++;
}
$json = substr($json, 0, -1);
$json .= '},';
$return .= $json;
}
$return = substr($return, 0, -1);
print '['.$return.']';
This is how I call this file inside my php code:
exec('/usr/bin/perl /var/www/foxpro2json.pl /var/www/myfilename.dbf', $json);
$array = json_decode($json[0], true);
Related
This is a code i used to prase a data through html dom php and echo a data in table form
all data came in perfect table form. but i want to show only 5 out of all data echo in table.at last i used table to echo a content or data i want only to echo 5 data out of all showing out but i am not getting any idea to code this.. any one can help me to do this?
<?php
include('simple_html_dom.php');
$html = file_get_html('http://www.discoverhongkong.com/us/see-do/events-festivals/events-calendar/index.jsp');
$eventRowData = array();
class eventRecord
{
public $dates;
public $eventDescription;
}
;
foreach ($html->find('#event_table tr') as $eventItem) {
$eventDateArray = array();
$oneEventData = new eventRecord;
foreach ($eventItem->find('.date') as $eventDate) {
$oneDateData = array();
$dom = new domDocument('1.0', 'utf-8');
$dom->loadHTML($eventDate);
$dom->preserveWhiteSpace = true;
$hTwo = $dom->getElementsByTagName('div')->item(0);
foreach ($hTwo->childNodes as $dateElement) {
array_push($oneDateData, $dateElement->nodeValue);
}
//print_r ($oneDateData);
array_push($eventDateArray, $oneDateData);
}
//
$oneEventData->dates = $eventDateArray;
$eventData = null;
foreach ($eventItem->find('.event_name') as $eventName) {
$dom = new domDocument('1.0', 'utf-8');
$dom->loadHTML($eventName);
$dom->preserveWhiteSpace = true;
$baseLink = "http://www.discoverhongkong.com";
$img = $dom->getElementsByTagName('a')->item(0);
$relativeLink = $img->attributes->getNamedItem("href")->value;
$eventLink = $baseLink . $relativeLink;
$eventData = '<strong>' . $img->textContent . '</strong><br />';
$oneEventData->eventDescription = $eventData;
//echo $oneEventData->eventDescription;
}
array_push($eventRowData, $oneEventData);
}
$arr = array_values($eventRowData);
//Print_r ($eventRowData);
//echo "----------";
//echo $arr[0]->eventDescription;
//echo "----------";
echo '</br>';
echo '<h2>Events In HongKong</h2>';
echo '<table class="table-bordered">';
echo '<tr>';
echo '<th class="abc">EVENT NAME</th>';
echo '<th>START DATE</th>';
echo '<th>END DATE</th>';
echo '</tr>';
foreach ($arr as $xyz) {
//print_r ($xyz);
echo '<tr>';
echo '<td>';
echo ($xyz->eventDescription);
echo '</td>';
//$mydates = array_values($xyz->dates);
//print_r ($mydates);
foreach ($xyz->dates as $datevalue) {
//echo '<tr>';
echo '<td>';
foreach ($datevalue as $datevalueitem) {
echo $datevalueitem;
echo '/';
}
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
?>
Which of these loops is the one you want to restrict? Whichever one it is, the structure would be the same. Something like this:
$i = 0;
foreach ($collection as $item) {
$i++;
if ($i > 5) {
break;
}
// the rest of your loop code
}
So you're basically storing in $i (or whatever you want to call the variable) a count of how many times the loop has executed. After 5 times, you use break; to exit the loop, regardless of how many records remain.
I'm trying to display all the information in a msSQL table in an HTML table and have up with something that is not so great.
<table border="1">
<?
echo "<tr>";
for ($i = 0; $i < mssql_num_fields($result); ++$i){
echo "<th>" .$column_names[$i] . "</th>";
}
echo "</tr>";
$num_rows = mssql_num_rows($result);
for ($i = 0; $i < $num_rows; ++$i){
echo "<tr>";
foreach ($column_names as $key => $val){
$result_row = mssql_query("SELECT * FROM username WHERE id = '$i'");
$row = mssql_fetch_assoc($result_row);
echo "<td>";
echo $row[$val];
echo "</td>";
}
echo "</td>";
}
?>
</table>
This works. The first part prints out the column names successfully, but as for the rest:
1) I think it is sort of cumbersome to make a query for every time through the loop
2) it doesn't really work because the ids of the rows go much higher than the number of rows in the table, as some ids aren't used.
It seems like I should be able just make one query and pull everything from the database at one go, then build my HTML table from that, but I can't figure out how to access it row by row where I could go $row[next row][shifted value from $column_names. How can improve this query?
function table_cell($item, $header=false) {
if (!$item) return '';
$elemname = ($header) ? 'th' : 'td';
$escitem = htmlspecialchars($item, ENT_NOQUOTES, 'UTF-8');
return "<{$elemname}>{$escitem}</{$elemname}>";
}
function table_header_cell($item) {
return table_cell($item, true);
}
function table_row($items, $header=false) {
$func = ($header) ? 'table_header_cell' : 'table_cell';
return "<tr>\n\t".implode("\n\t", array_map($func, $items))."\n</tr>\n";
}
function echo_result_as_table($result) {
if ($result && $row = mssql_fetch_assoc($result)) {
$columnnames = array_keys($row);
echo "<table>\n", table_row($columnnames, true), "\n";
do {
echo table_row($row), "\n";
} while ($row = mssql_fetch_assoc($result));
echo "</table>\n";
}
}
$result = mssql_query("SELECT * FROM username");
echo_result_as_table($result);
if ($result) mssql_free_result($result);
If you have an array of associative arrays instead of a raw mssql result handle, you can use a function like this to produce a table string:
function array_to_table($arrayofassoc) {
if (!$arrayofassoc) return '';
$tablestr = '<table>';
$tablestr .= table_row(array_keys($arrayofassoc[0]), true);
$tablestr .= implode('', array_map('table_row', $arrayofassoc));
$tablestr .= '</table>';
return $tablestr;
}
try this:
while($row = mysql_fetch_results($result)){
echo '<td>'.$row['column_name'].'</td>';
}
with 'column_name' being the name of the column in mysql.
but some will say..."wait, but PDO"
I have a MySQL query that returns data using PHP.
My problem is that I need to populate my html table (with 3 columns) with the data returned by the query but the data should be populated Columnwise.
Like first the first column should be populated .. then the second and finally the third one.
Also I would like to know that is it possible to do so for an unlimited set of data?
Following the screen shot of the desired layout
you can use while.
<table>
$sql=mysql_query("select * from table");
while($s=mysql_fetch_array($sql))
{
$x=$s["x"];
<tr>
<td ><?php echo $x; ?></td>
<td ><?php echo $y; ?></td>
<td ><?php echo $z; ?></td>
</tr>
}
</table>
guybennet's answer is correct but if you want it to work for an unlimited amount of columns you could do this: (I also threw in some column headers for readability)
echo '<table>';
$counter = 0;
$result = mysql_query("select * from table");
while($row = mysql_fetch_array($result)) {
$counter++;
if($counter == 1) {
echo '<tr>';
foreach($row as $key => $val) {
echo "<th>$key</th>";
}
echo '</tr>';
}
echo '<tr>';
foreach($row as $key => $val) {
echo "<td>$val</td>";
}
echo '</tr>';
}
echo '</table>';
Also of course you should use mysqli or PDO I'm just showing a quick example.
If you don't care about how it's organized, you can try something like this:
echo "<table><tr>";
$i=0;
while($row = mysql_fetch_array($sql))
{
echo "<td>".$row[0]."</td>\n";
$i++;
if($i==3)
{
echo "</tr>\n<tr>";
$i=0;
}
}
echo "</tr></table>";
Otherwise, I'd suggest putting it all into an array and then putting it into the table.
$data = array();
$result = mysql_query("SELECT * FROM your_table");
while ($row = mysql_fetch_array($result)) {
$data[] = $row;
}
$itemsAmount = count($data);
$ceilAmount = ($itemsAmount - $itemsAmount % 3) / 3;
$lastAmount = $itemsAmount % 3;
$firstArray = array_slice($data, 0, $itemsAmount);
$secondArray = array_slice($data, 0, $itemsAmount*2);
$thirdArray = array_slice($data, 0, $lastAmount);
$output = "<table>";
foreach ($data as $key => $value) {
$output .= "<tr>";
$output .= "<td>" . $firstArray[$key][0] . "</td>";
$output .= "<td>" . $secondArray[$key][0] . "</td>";
if (empty($thirdArray[$key])) {
$str = '';
} else {
$str = $thirdArray[$key][0];
}
$output .= "<td>" . $str . "</td>";
$output .= "</tr>";
}
$output .= "</table>";
echo $output;
You need to check all the results returned, then print them as you won't print in order:
First get an array with all the results
<?php
$sql= mysql_query('SELECT * FROM table');
$num= mysql_affected_rows($sql);
$items = array();
$i=0;
while($item=mysql_fetch_array($sql)){
$items[++$i]=$item['data'];
}
Now start printing
int $num_rows;
$num_rows=$num%3;
echo '<table>';
for ($i=0;$i<$num_rows;$i++){
echo '<tr>';
for ($j=0;$j<2,$j++){
$n=$i+1+($j*$num_rows);
if($items[$n]!==null)
echo '<td>'.$items[$n].'</td>';
else
echo '<td></td>';
}echo '</tr>';
}echo'</table>';
?>
I edited a PHP code that reads an Excel Spreadsheet (.xlsx form) and displays it very well.
But I want an extra column to be added when PHP page displays the Spreadsheet. (For textareas to update one cell in each row.)
What can I do for it?
Thanks.
<?php
if((!empty($_FILES["file"])) && ($_FILES['file']['error'] == 0)) {
$limitSize = 15000000;
require_once "simplexlsx.class.php";
$getWorksheetName = array();
$xlsx = new SimpleXLSX( $_FILES['file']['tmp_name'] );
$getWorksheetName = $xlsx->getWorksheetName();
echo ' <hr>
<div id="datacontent">
';
'<div id="datacontent">';
for($j=1;$j <= $xlsx->sheetsCount();$j++){
echo '<h3>Tablodaki Worksheet: '.$getWorksheetName[$j-1].'</h1>';
echo '<table id="xlsxTable">';
list($cols,) = $xlsx->dimension($j);
foreach( $xlsx->rows($j+1) as $k => $r) {
if ($k == 0){
$trOpen = '<th';
$trClose = '</th>';
$tbOpen = '<thead>';
$tbClose = '</thead>';
}else{
$trOpen = '<td';
$trClose = '</td>';
$tbOpen = '<tbody>';
$tbClose = '</tbody>';
}
echo $tbOpen;
echo '<tr>';
for( $i = 0; $i < $cols; $i++)
echo $trOpen.'>'.( (isset($r[$i])) ? $r[$i] : ' ' ).$trClose;
echo '</tr>';
echo $tbClose;
}
echo '</table>';
}
}
?>
I have the following PHP function which will list the users from a MySql table and will print the HTML code as you can see:
//List All Users From The Database Table In An Array
public function listUsersInArray() {
$sql = "SELECT username FROM user";
$users = array();
if($stmt = $this->conn->prepare($sql)) {
$stmt->bind_result($usrn);
$stmt->execute();
while ($row = $stmt->fetch()) {
$stmt->bind_result($usrn);
$users[] = $usrn;
}
$stmt->close();
return $users;
}
else {
$error = true;
$message['error'] = true;
$message['message'] = "The Users Could Not Stored In Array";
return json_encode($message);
}
}
//Build A Form In Order To Print Out The Users For Deleting
private function createForm($id) {
$form = array( '<form name="delete-user" id="'.$id.'" class="delete-user" method="post" action="#">',
'<input type="hidden" name="user_id" value="'.$id.'" />',
'<fieldset class="user-wrapper">',
'<label for="user" class="user-label">User</label>',
'<input type="text" name="user" class="user" value="'.$id.'" autocomplete="off" readonly="readonly" />',
'</fieldset>',
'<fieldset class="delete-wrapper">',
'<button type="submit" name="delete" class="delete">Delete</button>',
'</fieldset>',
'</form>'
);
$form = implode("",$form);
return $form;
}
//List All Users From Array As Forms For Deleting
public function listUsersForDelete() {
$users = $this->listUsersInArray();
for ($i = 0; $i < sizeof($users) ; $i++) {
while((sizeof($users) <= ($i % 7 == 0 || $i == 0))) {
echo $this->createForm($users[$i]);
$i++;
}
}
}
And now I just have to figure out how to add a wrap the all the forms in a div if the forms are more than 7 and do that each time I encounter a multiple of 7.
For example, if I have 9 forms, wrap the first 7 in a div but also wrap the rest in another div, and if I have 16 forms, wrap the first 7 in a div, the next 7 in a div and the rest of 2 in another div, and so on ...
You suggested code looks fine. The only thing I would suggest is that you store the <form> code into a variable first instead of just copying and pasting it. Copying and pasting is prone to a lot of errors, especially if you have to update the code later.
Modulus would work but you may want to use an array to easily enclose the forms in divs if it's greater then 7 results.
Try adapting this script as it displays results in a table grid view.
<?php
echo '<table>';
$number_of_thumbs_in_row = 2;
$result = mysql_query("");
$nr = mysql_num_rows($result);
if (empty($nr)) {
$result_final = "\t<tr><td></td></tr>\n";
} else {
while ($row = mysql_fetch_array($result)) {
$result_array[] = "<tr>your data</tr>";
}
$result_final = "<tr>\n";
foreach ($result_array as $thumbnail_link) {
if ($counter == $number_of_thumbs_in_row) {
$counter = 1;
$result_final .= "\n</tr>\n<tr>\n";
} else
$counter++;
$result_final .= "\t<td>" . $thumbnail_link . "</td>\n";
}
if ($counter) {
if ($number_of_photos_in_row - $counter)
$result_final .= "\t<td colspan='" . ($number_of_photos_in_row - $counter) .
"'> </td>\n";
}
$result_final .= "</tr>";
}
echo $result_final;
echo '</table>';
?>