Unable to Load Gallery Images With 'foreach' command - php

I've put together the following script which allows users to view their uploaded images in the original folder structure that they were saved.
UPDATED CODE
<?php session_start();
$_SESSION['username']=$_POST['username'];
$_SESSION['locationid']=$_POST['locationid'];
?>
<!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">
<?php
//This variable specifies relative path to the folder, where the gallery with uploaded files is located.
$galleryPath = 'UploadedFiles/' . $_SESSION['username'] . '/' . $_SESSION['locationid'] . '/';
//let's DEBUG the above assignment
if (!is_dir($galleryPath)) { die("No folder exists at $galleryPath!"); }
$absGalleryPath = realpath($galleryPath);
//let's DEBUG this one too
if (!is_dir($absGalleryPath)) { die("No folder exists at $absGalleryPath!"); }
$descriptions = new DOMDocument('1.0');
// DEBUG: let's check for the XML while we're at it
//if (!file_exists($absGalleryPath.'files.xml')) { die("No XML found at $absGalleryPath"."files.xml"); }
$descriptions->load($absGalleryPath . '/' . 'files.xml');
$items = array();
for ($i = 0; $i < $descriptions->documentElement->childNodes->length; $i++) {
$xmlFile = $descriptions->documentElement->childNodes->item($i);
$path = $xmlFile->getAttribute('name');
$path = explode('/', $path);
$t = &$items;
for ($j = 0; $j < count($path); $j++) {
if (empty($t[$path[$j]])) {
$t[$path[$j]] = array();
}
$t = &$t[$path[$j]];
}
$t['/src/'] = $xmlFile->getAttribute('source');
$t['description'] = $xmlFile->getAttribute('description');
$t['size'] = $xmlFile->getAttribute('size');
}
$basePath = empty($_GET['path']) ? '' : $_GET['path'];
if ($basePath) {
$basePath = explode('/', $basePath);
for ($j = 0; $j < count($basePath); $j++) {
$items = &$items[$basePath[$j]];
}
}
$files = array();
$dirs = array();
function urlpartencode(&$item, $index) {
$item = rawurlencode($item);
}
foreach ($items as $key => $value) {
if (isset($value['/src/'])) {
$value['/src/'] = explode('/', $value['/src/']);
array_walk($value['/src/'], 'urlpartencode');
$value['/src/'] = implode('/', $value['/src/']);
$files[] = array(
'name' => $key,
'src' => $value['/src/'],
'description' => htmlentities($value['description'], ENT_COMPAT, 'UTF-8'),
'size' => htmlentities($value['size'], ENT_COMPAT, 'UTF-8')
);
} else {
$dirs[] = $key;
}
}
$basePath = empty($_GET['path']) ? '' : $_GET['path'];
$up = dirname($basePath);
if ($up == '.') {
$up = '';
}
sort($files);
sort($dirs);
?>
<head>
<title>View Image Folders</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="Styles/style.css" rel="stylesheet" type="text/css" />
<script src="Libraries/jquery/jquery-1.4.3.min.js" type="text/javascript"></script>
<style type="text/css">
<!--
.style1 {
font-size: 14px;
margin-top: 5px;
margin-right: -50px;
}
-->
</style>
<body style="font-family: Calibri; color: #505050; margin-right: 160px; margin-left: -180px;">
<div align="right" class="style1"> View All Images </div>
<form id="imagefolders" name="imagefolders" class="page" action="gallery.php" method="post" enctype="application/x-www-form-urlencoded">
<div id="container">
</div>
<div id="center">
<div class="aB">
<div class="aB-B">
<?php if ('Uploaded files' != $current['title']) :?>
<?php endif;?>
<div class="demo">
<input name="username" type="hidden" id="username" value="IRHM73" />
<input name="locationid" type="hidden" id="locationid" value="1" />
<div class="inner">
<div class="container">
<div class="gallery">
<table class="gallery-link-table" cellpadding="0" cellspacing="0">
<thead>
<tr class="head">
<th class="col-name">
Name
</th>
<th class="col-size">
Size
</th>
<th class="col-description">
Description
</th>
</tr>
</thead>
<tbody>
<tr class="directory odd">
<td class="col-name">
..
</td>
<td class="col-size">
</td>
<td class="col-description">
</td>
</tr>
<?php $i = 1; ?>
<?php foreach ($dirs as $dir) : ?>
<tr class="directory <?php $i++; echo ($i % 2 == 0 ? 'even' : 'odd'); ?>">
<td><?php echo htmlentities($dir, ENT_COMPAT, 'UTF-8'); ?></td>
<td>Folder</td>
<td></td>
</tr>
<?php endforeach; ?>
<?php foreach ($files as $file) : ?>
<tr class="<?php $i++; echo ($i % 2 == 0 ? 'even' : 'odd'); ?>">
<td><a target="_blank" href="<?php echo $galleryPath . $file['src']; ?>"><?php echo htmlentities($file['name'], ENT_COMPAT, 'UTF-8'); ?></a></td>
<td><?php echo htmlentities($file['size'], ENT_COMPAT, 'UTF-8'); ?></td>
<td><?php echo htmlentities($file['description'], ENT_COMPAT, 'UTF-8'); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
I can correctly show the folders, but when I click on the folder to drill down to the individual images I receive the following error:
Warning: DOMDocument::load() [domdocument.load]: I/O warning : failed to load external entity "/homepages/2/d333603417/htdocs/development/UploadedFiles/files.xml" in /homepages/2/d333603417/htdocs/development/imagefolders.php on line 25 Warning: Invalid argument supplied for foreach() in /homepages/2/d333603417/htdocs/development/imagefolders.php on line 65
Line 25 is this line $descriptions->load($absGalleryPath . '/' . 'files.xml'); and line 65 is this:foreach ($items as $key => $value) {`
My initial script didn't use session variables and I didn't have any issues. However I now need to include these, so I'm sure that there is a conflict between these and the foreach command. I've done quite a bit of research to see if anyone else has had similar issues, but can't find anything.
I just wondered whether someone could look at this and let me know where I'm gong wrong.
Many thanks and regards

Error 1
Warning: DOMDocument::load() [domdocument.load]: I/O warning : failed to load external entity "/homepages/2/d333603417/htdocs/development/UploadedFiles/files.xml"
The Origin of the Problem is $descriptions->load($absGalleryPath . '/' . 'files.xml');
It is bad practice trying to load file you are not sure it exists or is readable
Something like this is better and make sure you catch exception
$file = $absGalleryPath . '/' . 'files.xml' ;
if(!is_readable($file) || !file_exists($file))
{
throw new Exception("Missing XML File");
}
Error 2
Warning: Invalid argument supplied for foreach() in /homepages/2/d333603417/htdocs/development/imagefolders.php on line 65
A. Since you are not able to load the first xml document ... trying to continue the process would result to this error
B. foreach ($items as $key => $value) { so it would run independently where it is populated or not
C. Too many Referencing would make your code more difficult to understand and debug ...
Conclusion
I think you should post the content of files.xml you would be surprised it innovative solutions and ore effective code people would come up with

I think Invalid argument supplied for foreach() is about your foreach ($items as $key => $value). So place var_dump($items); before that foreach to see full dump of items variable. Seems like it's not even an array.

your foreach loop is not getting properdata as you are willing to do..pls use var_dump to check data you are getting.
check out path for your XML.

Related

How to put JSON array in HTML table using PHP [duplicate]

This question already has answers here:
Output a php multi-dimensional array to a html table
(3 answers)
Closed 3 years ago.
I need to create REST API in PHP. I take JSON data from https://jsonplaceholder.typicode.com/ . Now I need to put all that data in table HTML. It is one array, inside with other 200 array. How can i create all row automaticly, without typing whole code by hands.
This is the code how i take data from https://jsonplaceholder.typicode.com/ :
<?php
$url = 'https://jsonplaceholder.typicode.com/todos/';
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_HTTPGET, true);
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json'
));
$result = curl_exec($cURL);
curl_close($cURL);
$arrays = json_decode($result);
?>
I tried like this:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JSON</title>
<link rel="shortcut icon" type="image/x-icon" href="icon.ico">
<meta name="description" content="HTML, PHP, JSON, REST API">
<style>table, th, td {border: 1px solid black;}</style>
</head>
<body>
<?php foreach ($arrays as $key => $value) { ?>
<div style="width:80px;border:2px solid black;height:20px;"> <?php echo 'User ID: ' . $value -> userId ?> </div><br />
<div style="width:50px;border:2px solid black;height:20px;"> <?php echo 'ID: ' . $value -> id ?> </div><br />
<div style="width:550px;border:2px solid black;height:20px;"> <?php echo 'Title: ' . $value -> title ?> </div><br />
<div style="width:90px;border:2px solid black;height:20px;"> <?php echo 'Completed: ' . $value -> completed ?> </div><br />
<br /> <?php } ?>
<table table style="width:100%"; table class="data-table">
<tr>
<th> User ID:</th> <th>ID:</th> <th>Title:</th><th>Completed</th>
</tr>
<tr>
<td><?php echo $value -> userId ?> </td> <td><?php echo $value -> id ?> </td> <td><?php echo $value -> title ?> </td><td><?php echo $value -> completed ?> </td>
</tr>
<tr>
<td><?php echo $value -> userId ?> </td> <td><?php echo $value -> id ?> </td> <td><?php echo $value -> title ?> </td><td><?php echo $value -> completed ?> </td>
</tr>
</table>
</body>
</html>
But i dont know to do it by once for all 200 row. Any suggestion?
use foreach() one more time and put <table> outside of it:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JSON</title>
<link rel="shortcut icon" type="image/x-icon" href="icon.ico">
<meta name="description" content="HTML, PHP, JSON, REST API">
<style>table, th, td {border: 1px solid black;}</style>
</head>
<body>
<?php foreach ($arrays as $value) { ?>
<div style="width:80px;border:2px solid black;height:20px;"> <?php echo 'User ID: ' . $value -> userId ?> </div><br />
<div style="width:50px;border:2px solid black;height:20px;"> <?php echo 'ID: ' . $value -> id ?> </div><br />
<div style="width:550px;border:2px solid black;height:20px;"> <?php echo 'Title: ' . $value -> title ?> </div><br />
<div style="width:90px;border:2px solid black;height:20px;"> <?php echo 'Completed: ' . $value -> completed ?> </div><br />
<br />
<?php } ?>
<table style="width:100%"; class="data-table">
<tr>
<th> User ID:</th>
<th>ID:</th>
<th>Title:</th>
<th>Completed</th>
</tr>
<?php foreach ($arrays as $value) { ?>
<tr>
<td><?php echo $value -> userId ?> </td>
<td><?php echo $value -> id ?> </td>
<td><?php echo $value -> title ?> </td>
<td><?php echo $value -> completed ?> </td>
</tr>
<?php } ?>
</table>
</body>
</html>
Note:- I am not sure that you want first foreach() inside <body> or not? so please check and if not needed then remove it.

Hide first <td> if second in <td> is not selected any value (empty)

I need hide first one < td > <?php echo $user_feature['tab_title_single']; ?> if second < td > are abolutely empty without any checked ('tab_title_labels') values.
<?php
if (!defined('ABSPATH')) {
exit; // Exit if accessed directly
}
if (!empty($id)) {
$post_id = $id;
}
$user_features = array(
array(
'tab_title_single' => 'Apsauga',
'tab_title_labels' => 'Imobilaizeris,Signalizacija,Palydovinė sekimo sistema,Šarvuotas (apsaugos)'
),
array(
'tab_title_single' => 'Audio/video įranga',
'tab_title_labels' => 'CD grotuvas,MP3 grotuvas,Papildoma audio įranga,CD keitiklis,AUX jungtis,Žemų dažnių garsiakalbis,DVD grotuvas,USB jungtis,Laisvų rankų įranga,Apple CarPlay / Android Auto'
),
array(
'tab_title_single' => 'Eksterjeras',
'tab_title_labels' => 'Lengvojo lydinio ratlankiai,LED dienos žibintai,LED žibintai,Žibintai „Xenon“,Rūko žibintai,Kablys,Priekinių žibintų plovimo įtaisas,Stogo bagažinės laikikliai,Automatiškai užsilenkiantys veidrodėliai,Žieminių padangų komplektas'
),
array(
'tab_title_single' => 'Elektronika',
'tab_title_labels' => 'El. valdomi veidrodėliai,El. valdomas bagažinės dangtis,Automatiškai įsijungiantys žibintai,Borto kompiuteris,El. reguliuojama vairo padėtis,Kritulių jutiklis,Šildomi veidrodėliai,Atstumo jutiklių sistema,Beraktė sistema,Autopilotas,El. šildomas priekinis stiklas,Start-Stop funkcija,Valdymas balsu,Pavarų perjungimas prie vairo,LCD ekranas,Navigacija/GPS'
)
);
?>
<?php if (!empty($user_features)) {
if (!empty($post_id)) {
$features_car = get_post_meta($post_id, 'additional_features', true);
$features_car = explode(',', $features_car);
} else {
$features_car = array();
}
foreach ($user_features as $user_feature) { ?>
<table style="width: 100%; margin-bottom: 0px">
<tr>
<td style="width: 16%; padding-left:5px;">
<div class="heading-font" style="color:#555555;font-size: 13px;font-weight: 500;"><?php echo $user_feature['tab_title_single']; ?></div>
</td>
<td style="width: 84%; padding-left:5px;">
<?php $features = explode(',', $user_feature['tab_title_labels']); ?>
<?php if (!empty($features)): ?>
<?php foreach ($features as $feature): ?>
<?php
$checked = '';
$hide = 'style="display:none;"';
if (in_array($feature, $features_car)) {
$checked = 'checked';
$hide = '';
};
?>
<label <?php echo $hide; ?>>
<span class="featuresspan"><?php echo esc_attr($feature); ?></span>
</label>
<?php endforeach; ?>
<?php endif; ?>
</td>
</tr>
</table>
<?php }
}
?>
To compare two arrays ($features and $features_car) in php, the most direct tool for that task is array_intersect(). Although I should tell you (and researchers) that it would be far, far better to Normalize your table data so that you are not storing comma-separated values. Having a normalized/granular table of labels and their individual features spread across multiple rows will allow your application to enjoy cleaner and more efficient queries and allow you to move the filtering processes from php to mysql where it belongs.
Code: (Demo)
$features_car = ['USB jungtis', 'Rūko žibintai'];
foreach ($user_features as $user_feature) {
$features = explode(',', $user_feature['tab_title_labels']);
$matched_features = array_intersect($features, $features_car);
if ($matched_features) {
echo "<table>";
echo "<tr>";
echo "<td>";
echo "<div class=\"heading-font\">{$user_feature['tab_title_single']}</div>";
echo "</td>";
echo "<td>";
foreach ($matched_features as $show_feature) {
echo "<label><span class=\"featuresspan\">{$show_feature}</span></label>";
}
echo "</td>";
echo "</tr>";
echo "</table>";
}
}
Output:
<table>
<tr>
<td>
<div class="heading-font">Audio/video įranga</div>
</td>
<td>
<label><span class="featuresspan">USB jungtis</span></label>
</td>
</tr>
</table>
<table>
<tr>
<td>
<div class="heading-font">Eksterjeras</div>
</td>
<td>
<label><span class="featuresspan">Rūko žibintai</span></label>
</td>
</tr>
</table>
p.s. I don't know if I support the stacking of <table> elements like this, but it is up to you how you wish to style your markup. You should move ALL of your inline styles to an external stylesheet so that your markup is easier to read and manage. I removed the esc_attr() only so that my demo would work without errors -- you can safely apply it to all variables that you are concerned about.

How to apply if-else on css class in php code?

I am trying to apply if else condition in bootstrap class with php variable but its not working. My variable is getting result.
Below is my tbody where i am applying php code:
<div class="<?php '#count_rows#' <= '2')
{
echo 'middle_menu';
}
else
{
echo 'middle_menu1';
} ?>">
<table class="table_4">
<thead>
<tr>
<th class="th_11">Quantity</th>
</tr>
</thead>
<tbody>
#TABLE_BODY#
</tbody>
</table>
</div>
Below is my 2 css classes:
.middle_menu
{
margin-top: 40px;
padding-bottom: 200px;
}
.middle_menu1
{
margin-top: 40px;
}
I am fetching my variable from another page where i set this type of opening and closing variable with #.
Below is my code for your reference but i dont think that is an issue for me because i check this #count_rows# variable with print_r in my current page and it showing me correct result.
foreach ($form_field as $key => $value){
$htmlContent = str_replace('#'.$key.'#', $value, $htmlContent);
}
<?php $className = $count_rows <= 2 ? 'middle_menu' : 'middle_menu1'; ?>
<div class="<?php echo $className; ?>" />
You can create a test.php then run php test.php and you should see the result
<?php
// $count_rows = 1;
$count_rows = 3;
$className = $count_rows <= 2 ? 'middle_menu' : 'middle_menu1';
echo "<div class=\"$className\"/>\n";
<div class="<?php '#count_rows#' <= '2')
You are missing a keyword here and also some brackets (which should cause a fatal syntax error), Also you are comparing two different literal strings - surely one of the terms should be a PHP variable?
You can't read back stuff you've previously written to the output stream - you are confusing what is happening in HTML, CSS and PHP.
I think you mean...
<div class="<?php if ($form_fields['count_rows'] <= '2')
Comparing a number by casting it to a string is rather dangerous.
Personally I would do this:
<div class="<?php echo (2 <= $form_fields['count_rows'])
? 'middle_menu' : 'middle_menu1'; ?>">
Since you didn't mention that the script blew up in your face, I suspect there may be a lot of other issues.
foreach ($form_field as $key => $value){
$htmlContent = str_replace('#'.$key.'#', $value, $htmlContent);
}
This is very innefficient. Consider:
$find=array_keys($form_field);
foreach ($find as $index=>$term) {
$find[$index]='#' . $term . '#';
}
$htmlContent = str_replace($find, $form_feld, $htmlContent);

Parse error: syntax error, unexpected T_IS_GREATER_OR_EQUAL in

over the past few weeks ive been learning php, its been quite a daunting task but stack overflow has helped me alot. I am currently having issues with a parse error,
<?php
include('config.php');
function html($html)
{
return htmlentities($html, ENT_QUOTES, 'utf-8');
}
?>
<html xmlns="http://www.w3.org/1999/xhtml"/>
<head>
<meta http-equiv="content-type" content="text/html"/>
<link href="<?php echo $design ?>/style.css" rel="stylesheet" title="Style">
<title><?php echo $title ?></title>
</head>
<body>
<html>
<div class="header">
<a href="<?php echo $root ?>" img src="<?php echo $design ?>/images/<?php echo $logo ?>" alt="home"/>
</div>
<table class="home" cellpadding="0" cellspacing="0">
<tr>
<th class="rank_th">Ranking</th>
<th class="site_th">Site</th>
<th class="votes_th">Votes</th>
</tr>
<?php
//we get #sites
$req1 = mysqli_fetch_array(mysqli_query('SELECT COUNT(id) as # FROM Sites WHERE status="ok"'));
//we get current top
IF (isset($_GET['Page'])) {
$page = intval($_GET['page']);
} else {
$page = 1;
}
//calculate #pages & display page links
$nbpage = ceil($req1['nb'] / $nbpage);
if ($page < 1 or $page > $nbpage);
{ >= 'Pages: ';
if ($page > 1) {
$pages_site .= ''last ';
}
for ($i=1;$i<=$nbpage;$i++)
{
if ($i==$page){
$pages_site .=<strong> .$i. </strong>';
}
}
if ($page < $page<$nbpage){
$pages_site .= 'next')''
}
?>
<tr>
<td colspan="3" class="pages"><?php ECHO $pages_site; ?></td>
</tr>
<div class="new">Please register or to add your website. </div>
<?php
//calculate order
$first_site = ($page-1)*$nbpage;
$last_site = $first_site +$nbpage;
$i=$first_site ;
//display sites
$req2 = mysqli_query('select id, url, name, description, banner, votes FROM sites where status="ok" order .by votes desc limit ' .$first_site . ',' .$last_site .);
while($dnn2 = mysqli_fetch_array($req2))
{
$i++;
}
?>
<tr>
<td class="ranking"><?php echo $i; ?> </td>
<td class="site"><?php echo html($dnn2['name']); ?><br />
<?php echo html($dnn2['description']); ?><br />
<?php echo html($dnn2['url']); ?>
<div style="text-align:center;"<img src="<?php echo html($dnn2['banner'],?>" alt="<?php echo html($dnn2['name']); ?>" style="max-width:500px;max-height:200px;" /></div></td>
<td class="votes"><?php echo html($dnn2['votes']); ?> <br />vote</td>
</tr>
<?php
}
//display page # again
?>
<tr>
<td colspan="3" class="pages"> <?php echo $pages_site; ?></td>
</tr>
</table>
<div class="footer">
<?php echo $footer ?>
</div>
</body>
</html>
/**
* Created by PhpStorm.
* User: weller
* Date: 19/12/13
* Time: 11:41 AM
*/
is the index.php page.
<?php
//change to your details.
$host = 'localhost';
$user = 'username';
$pass = 'password';
$dbname = 'database';
//connects here(dont change)
$db = mysqli_connect($host, $user, $pass, $dbname);
//webmaster email
$mail1 = 'webmaster#site.com';
//site root url
$root = 'www.site.com/';
//homepage filename
$index = 'index.php';
//pages per index
$nbpages = '10';
//css name
$design = 'default';
//site title
$title = 'LOLOLOL';
//Footer msg
$footer = 'LOLOL';
?>
/**
* Created with PhpStorm.
* User: weller
* Date: 19/12/13
* Time: 11:31 AM
*/
is the config.php
and my parse error is:
Parse error: syntax error, unexpected T_IS_GREATER_OR_EQUAL in /home3/crazycr1/public_html/index.php on line 37
every parse error ive had sofar ive been able to solve with google but this one has had me stumped for an hour now.
i have tried moving the >= around and i did try a few other ways of doing it but i keep getting the same issue.
any help at all is welcome && feel free to check for easier or more secure ways of doing things. THANKS :D
weller.
here is the correct from. Thanks
/**
* Created by PhpStorm.
* User: weller
* Date: 19/12/13
* Time: 11:41 AM
*/
include('config.php');
function html($html)
{
return htmlentities($html, ENT_QUOTES, 'utf-8');
}
?>
<html xmlns="http://www.w3.org/1999/xhtml"/>
<head>
<meta http-equiv="content-type" content="text/html"/>
<link href="<?php echo $design ?>/style.css" rel="stylesheet" title="Style">
<title><?php echo $title ?></title>
</head>
<body>
<html>
<div class="header">
<a href="<?php echo $root ?>" img src="<?php echo $design ?>/images/<?php echo $logo ?>" alt="home"/>
</div>
<table class="home" cellpadding="0" cellspacing="0">
<tr>
<th class="rank_th">Ranking</th>
<th class="site_th">Site</th>
<th class="votes_th">Votes</th>
</tr>
<?php
//we get #sites
$query = "SELECT COUNT(id) as # FROM Sites WHERE status=`ok`";
$req1 = mysqli_fetch_array(mysqli_query($query, $db));
//we get current top
IF (isset($_GET['Page'])) {
$page = intval($_GET['page']);
} else {
$page = 1;
}
//calculate #pages & display page links
$nbpage = ceil($req1['nb'] / $nbpage);
if ($page < 1 or $page > $nbpage);
{
$pages_site = 'Pages: ';
if ($page > 1) {
$pages_site .= 'last';
}
for ($i=1;$i<=$nbpage;$i++)
{
if ($i==$page){
$pages_site .='<strong> .$i. </strong>';
}
}
if ($page < $nbpage){
$pages_site .= 'next';
}
?>
<tr>
<td colspan="3" class="pages"><?php ECHO $pages_site; ?></td>
</tr>
<div class="new">Please register or to add your website. </div>
<?php
//calculate order
$first_site = ($page-1)*$nbpage;
$last_site = $first_site +$nbpage;
$i=$first_site ;
//display sites
$query1 = 'select id, url, name, description, banner, votes FROM sites where status="ok" order .by votes desc limit ' .$first_site . ',' .$last_site;
$req2 = mysqli_query($query1, $db);
while($dnn2 = mysqli_fetch_array($req2))
{
$i++;
}
?>
<tr>
<td class="ranking"><?php echo $i; ?> </td>
<td class="site"><?php echo html($dnn2['name']); ?><br />
<?php echo html($dnn2['description']); ?><br />
<?php echo html($dnn2['url']); ?>
<div style="text-align:center;"<img src="<?php echo html($dnn2['banner']);?>" alt="<?php echo html($dnn2['name']); ?>" style="max-width:500px;max-height:200px;" /></div></td>
<td class="votes"><?php echo html($dnn2['votes']); ?> <br />vote</td>
</tr>
<?php
}
//display page # again
?>
<tr>
<td colspan="3" class="pages"> <?php echo $pages_site; ?></td>
</tr>
</table>
<div class="footer">
<?php echo $footer ?>
</div>
</body>
</html>
corrections:
/**
* Created by PhpStorm.
* User: weller
* Date: 19/12/13
* Time: 11:41 AM
*/
this needed to in a php tag.
">
bracket expected.
'select id, url, name, description, banner, votes FROM sites where status="ok" order .by votes desc limit ' .$first_site . ',' .$last_site .
extra dot put and also db connect link wasn't in the param.
if ($page < $page
quotes are not put correctly.
$title = 'LOLOLOL';
//Footer msg
$footer = 'LOLOL';
You missed semicolons at the end of both statements.
Errm...
if ($page < 1 or $page > $nbpage);
{ >= 'Pages: ';
if ($page > 1) {
Pretty sure that's not supposed to be there...
if ($page < 1 or $page > $nbpage);
{ >= 'Pages: ';
In the above code you have the error.
you have end the if condition there so remove the ;.
there is >= 'Pages: ' without any condition so remove that or make it right.
So do this:
if ($page < 1 or $page > $nbpage)
{
......
And in the below line you have error:
$pages_site .= ''last ';
^^^ extra comma
this must be as following:
$pages_site .= 'last ';

Fire Query on CSV data

I have a public google spreadsheet.I got the CSV data as an array from the remote URL.Then I displayed the information as an HTML list, referencing the appropriate array items.
Now I want to fire an php select query on it such that only the gossip of a particular actor is displayed.How to do it ?
(I want to use a variable $Name.wen I supply Name.I should get the gossip of that Actor.)
my excel sheet contains following columns
> 1.Sr No.
> 2.Name
> 3.Gossip
This is the code of my php page that retrieves the data as a list :
$lines = file('https://docs.google.com/spreadsheet/pub?key=0AgzUC4MxdChJdFIyMHFUZ21PS053b3Z1OHFnbHJwYVE&single=true&gid=0&output=csv');
$headers = array_shift($lines);
foreach ($lines as $line)
{
$ldata = explode(',', trim($line));
if ($ldata[0] == '') break;
echo '<li>Sr No. <strong>' . $ldata[0] . '</strong></li><li>Name <strong>' . $ldata[1] . '</strong></li><li>Gossip <strong>' . $ldata[2] . '</strong></li>';
}
Give this a shot:
<?php
// get the CSV data as an array from the remote URL
define('GOOGLE_DOC','https://docs.google.com/spreadsheet/pub?key=0AgzUC4MxdChJdFIyMHFUZ21PS053b3Z1OHFnbHJwYVE&single=true&gid=0&output=csv');
if(isset($_GET['filterColumn'])){define('FILTER_COLUMN',$_GET['filterColumn']);}
if(isset($_GET['filterValue'])){define('FILTER_VALUE',$_GET['filterValue']);}
function readCSVIntoArray($fileName)
{
$rows=array();
if (($handle = fopen($fileName, "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE){$rows[]=$data;}
fclose($handle);
}
$h=array_shift($rows);
return array($h,$rows);
}
list($head,$rows)=readCSVIntoArray(GOOGLE_DOC);
header('Content-Type: text/html; charset=utf-8');
?><!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Ultimater's Example</title>
<style type="text/css">
html,body
{
margin:0;
padding:0;
font-family:'Source Sans Pro',sans-serif;
font-size: 13px;
color:black;
background:#e2e2ec;
line-height:15px;
}
table{border-collapse:collapse;}
table thead tr th{font-weight:bold;padding:2px;margin:1px;border:1px solid black;background-color:blue;color:white;}
table tbody tr td{margin:1px;padding:2px;border:1px solid black;}
</style>
</head>
<body>
<div>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="GET">
<select name="filterColumn">
<?php foreach($head as $i=>$h){echo sprintf('<option value="%s">%s</option>',$i,htmlentities($h));} ?>
</select>
<input type="text" name="filterValue" place-holder="filter" value="" />
<input type="submit" value="Filter" />
</form>
</div>
<hr />
<?php
echo '<table>';
echo '<thead><tr><th>'.implode('</th><th>',$head).'</th></tr></thead>';
echo '<tbody>';
foreach($rows as $row)
{
if(defined('FILTER_COLUMN')&&defined('FILTER_VALUE'))
{
if(strpos($row[FILTER_COLUMN],FILTER_VALUE)===false)continue;
}
echo '<tr><td>'.implode('</td><td>',$row).'</td></tr>';
}
echo '</tbody>';
echo '</table>';
?>
</body>
</html>
Simply do not display a line if name is not like required:
<?php
// get the CSV data as an array from the remote URL
$lines = file('https://docs.google.com/spreadsheet/pub?key=0AgzUC4MxdChJdFIyMHFUZ21PS053b3Z1OHFnbHJwYVE&single=true&gid=0&output=csv');
// get rid of header row
$headers = array_shift($lines);
// Loop through data- therer is only one line hear
foreach ($lines as $line) {
$ldata = explode(',', trim($line)); // split row to its own array of elements
if ($ldata[0] == '') break; // an empty line means we are done, so exit the foreach loop
if($ldata[1] == $var_with_required_name) {
// now we can just output the information as an HTML list, referencing the appropriate array items
echo '<li>Sr No. <strong>' . $ldata[0] . '</strong></li><li>Name <strong>' . $ldata[1] . '</strong></li><li>Gossip <strong>' . $ldata[2] . '</strong></li>';
}
}
?>

Categories