.load into DIV with PHP content - php

I am trying to .load a script called 'refreshImages.php'. Inside that script is a while loop pulling from the database. I have got it to load a single echo function but it wont load anything inside the while loop I have on the script... this is what the php file has...
<?php
include 'includes/config.php';
$pimages = mysql_query("SELECT * FROM property_images WHERE pid='$pid'");
//Cant Post Images So Leaving The Echo Content Out//
while($img = mysql_fetch_array($pimages)){
$image = $img['image'];
$image_alt = $img['image_alt'];
echo "<li>$img</li>";
}?>
I am using .load('refreshImages.php') on the page I need it to show up on.
Any explanation I am not seeing?

Your $img is an array, not a string. You will get output like <li>Array</li>, if you have stuff coming from the database. Is that what you mean? Or are you getting an empty result?
If empty - what does your mysql_num_rows tell you when ran against the result resource?

try changing this:
echo "<li>$img</li>";
to
echo "<li><img src=\"{$image}\" alt=\"{$image_alt}\" /></li>";

You may not be getting any results from the database. Try using this code which will display a message if there is something wrong with your sql query.
<?php
include 'includes/config.php';
$pimages = mysql_query("SELECT * FROM property_images WHERE pid=" . $pid );
if (mysql_num_rows($pimages) > 0) { // checks to see if you are getting results from db
while($img = mysql_fetch_array($pimages)){
$image = $img['image'];
$image_alt = $img['image_alt'];
echo '<li><a class="thumb" href="{$image}"><img src="{$image}" width="50px" height="50px" alt="{$image_alt}"></a></li>';
}
} else {
echo "no results returned from database";
} // end of mysql_num_rows check
?>

You might be better off concatenating all the images and then echo-ing it out rather than echo-ing each one e.g
$htmlOutput = '';
while($img = mysql_fetch_array($pimages)){
$image = $img['image'];
$image_alt = $img['image_alt'];
$htmlOutput .= "<li><img src=\"{$image}\" alt=\"{$image_alt}\" /></li>";
}
echo $htmlOutput ;

Related

Displaying image path in PHP from MySQL

I would like to display multiple images on my index page. Doesn’t matter if they are displayed in any order.
Each of the images have their image path and their unique ID. I have the following code but it is not displaying anything:
<?php
$result = mysql_query("SELECT * FROM my_image", $connection);
while($row = mysql_fetch_array($result))
{
$ID = $row['name'];
$file = $row['file_path'] ;
echo '<img style="margin: -32.5px 0 0 0;" alt="" src="'.$file.'">' ;
}
?>
Anyone know what could be wrong?
you should start to debug your code, as example :
while($row = mysql_fetch_array($result))
{
$file = $row['file_path'] ;
echo $file; continue;
//...
}
and see if you get expected result.
EDIT:
what about var_dump($result) ?

php working locally and remotely on own hosting, but not remotely on client's hosting

I'm not good with PHP, so please bear with me. I have the following code:
<?php $thisPage="designers";
include("phpincludes/header.php") ?>
<div id="contentLeft">
<?echo "<h2><a href='designer_display.php?d_name=".$_GET['d_name']."'>" . $_GET['d_name']. "</a></h2>";?>
<?
error_reporting(0);
require_once "phpincludes/connection.php";
$designer = $_GET['d_name'];
// Category Selection Start.
$cat_qry = "SELECT DISTINCT (
`own_category`
)
FROM `products`
WHERE `designer` ='".$designer."' && own_category != ''";
$rs_qry = mysql_query($cat_qry);
$i = 0;
while($rec_qry = mysql_fetch_array($rs_qry))
{
if($i==0)
$first_cat = $rec_qry['cat_name'];
$cat_name[$i]=$rec_qry['cat_name'];
$i++;
}
// Category Selection Start.
$cat_name = $_GET['catName1'];
$cat_qry = "SELECT DISTINCT (
`own_category`
)
FROM `products`
WHERE `designer` ='".$designer."' && own_category != ''";
//"select * from categories";
$rs_qry = mysql_query($cat_qry);
$rec_no = mysql_affected_rows();
/*if($_GET["catName1"]=="")
$catName = $first_cat;
else
$catName = $cat_name;*/
$n1 = 1;
echo "<ul id=\"designers\">";
while($rec_qry = mysql_fetch_array($rs_qry))
{
$cate_name = str_replace('_',' ',$rec_qry['own_category']);
//print_r($cate_name[1]);
if($rec_qry["own_category"]!= $_GET['catName'])
echo "<li><A HREF='d_items.php?no=".$n1."&d_name=".$designer."&catName=".$rec_qry["own_category"]."'>".strtoupper($cate_name)."</A></li>";
else
echo "<li><A HREF='d_items.php?no=".$n1."&d_name=".$designer."&catName=".$rec_qry["own_category"]."'><font color='#8d9354'>".strtoupper($cate_name)."</font></a></li>";
if($rec_qry["own_category"]== $_GET['catName'])
{
$query="SELECT A.photo_filename, A.photo_title, B.dc_cat_name FROM displays A
LEFT JOIN displays_categories B ON B.dc_display_photos = A.photo_filename
WHERE dc_cat_name ='".$rec_qry["cat_name"]."'";
$query="SELECT B.pro_name, B.own_category, B.own_photo_filename from categories as A LEFT JOIN
products as B ON A.cat_name = B.own_category
where cat_name ='".$_GET["catName"]."' and designer ='".$designer."' order by B.pro_name";
$rs1_qry = mysql_query($query);
echo "<ul class=\"items\">";
while($row = mysql_fetch_array($rs1_qry))
{
if ($designer == "Jardan") {
$p1name = str_ireplace($designer,'',$row["pro_name"]);
$pname = substr($p1name, 0, -3);
} else {
$pname = str_ireplace($designer,'',$row["pro_name"]);
}
if($_GET['ProName'] != $row["pro_name"])
echo "<li><A HREF='d_item_details.php?d_name=".$designer."&ProName=".$row['pro_name']."&catName1=".$rec_qry['own_category']."&catName=".$rec_qry['own_category']."'>".$pname."</A></li>";
else
echo "<li><A HREF='d_item_details.php?d_name=".$designer."&ProName=".$row['pro_name']."&catName1=".$rec_qry['own_category']."&catName=".$rec_qry['own_category']."'><font color='#fff'>".$pname."</font></A></li>";
}
echo "</ul>";
}
}
echo "</ul>";
$f=1;
$recnm = $_GET['ProName'];
$owncat = $_GET['catName1'];
$photo_title = $_GET['ptitle'];
$query2="SELECT pro_code, pro_dimensions, own_photo_filename, designer_pdf, palette FROM products
WHERE pro_name ='".$recnm."' and own_category ='".$owncat."'";
$rt2=mysql_query($query2);
echo mysql_error();
?>
</div>
<div id="contentRight">
<?
while($row2 = mysql_fetch_array($rt2))
{
?>
<?$d = explode(' ',$designer);
for($p=0;$p<count($d);$p++)
{
$des.=$d[$p];
}
if ($designer == "Playstar") {
$p2name = str_ireplace($designer,'',$recnm);
$poname = substr($p2name, 0, -3);
} else {
$poname = str_ireplace($designer,'',$recnm);
}
?>
<img class="lighting" src="img/designers/<?echo $des."/".$row2['own_photo_filename'];?>.jpg" />
<div class="mailerBtn"><h4>ENQUIRE</h4>
<h4>Download Product PDF</h4></div>
<h3><?echo $poname;?></h3>
<p>
<?
echo "<b>Product code:</b> ". $row2['pro_code']."<BR>";
if ($designer == "Playstar") {
echo $row2['pro_dimensions'];
} else {
echo "<b>Dimensions:</b> ". $row2['pro_dimensions'];
} ?>
</p>
<? if($row2[4]=='yes') {
?>
<img class="palette" src="img/designers/<?echo $des."/".$row2['own_photo_filename'];?>-palette.jpg" />
<? } ?>
<?}?>
<?php include("phpincludes/base.php") ?>
Much of the code was written by someone else, but I've been modifying it in a couple of ways. It works locally (on XAMP) and on my personal site where I've been hosting it as a test site.
But when i uploaded it to the client's host, this page stops abruptly at echo "<ul class=\"items\">"; - roughly line 73. I can't see what's stopping it from running properly.
Some assistance would be gratefully received!
MTIA.
That's hard to tell. It's very obviously something with the clients setup.
Taking a wild guess, that client is still running PHP4. Because after line 73 you have a call to str_ireplace which wasn't available for that.
You would likely get a fatal error for this one. And this is the right avenue for investigation here. Add this on top for debugging (instead of error_reporting(0) which is not so helpful):
error_reporting(E_ALL|E_WARNING);
And ask for errors. Better yet, provide a custom error handler which prints out something shiny for end user-type clients. Otherwise ask for the error.log which should contain the exact error likewise.
You should avoid using the "short tags" <? and replace with the regular <?php tags. At a minimum, on that line not having a space after the "?" is asking for trouble, but overall you should just replace the short tags as they can cause trouble for various reasons and many installations do not have them enabled by default.
FYI, one specific case where they often cause trouble is for XHTML documents, if the xml declaration isn't printed with PHP, it will throw an error. Now with HTML5 I guess this will be less of an issue, but IMHO, best practice would be to avoid them.
Glad you got it working, but I wouldn't be using this code in production on your clients web host.
$f=1;
$recnm = $_GET['ProName'];
$owncat = $_GET['catName1'];
$photo_title = $_GET['ptitle'];
$query2="SELECT pro_code, pro_dimensions, own_photo_filename, designer_pdf, palette FROM products WHERE pro_name ='".$recnm."' and own_category ='".$owncat."'";
This and all the other queries here are vulnerably to sql injection. (if I passed in catName1='; DELETE * FROM products where 1=1 or '2'='2)
You need to either convert the queries to paramaterised queries, or use mysql_real_escape_string.
ie
$owncat = mysql_real_escape_string($_GET['ProName']);

quotes in html in php problem

I am trying to generate a specific link and accompanying html depednant on the existance of a file. The code I am using to do so:
if(file_exists('../images/'. $pk . '.jpg'))
{
$imageSrc = "../images/". $pk . ".jpg";
$imagehtml = htmlentities(json_encode("<img src=\"".$imageSrc."\" >"));
$screenshotLink = "<p>View Screenshot";
}
else {
$screenshotLink = '';
}
This results in the following, useless html:
View Screenshot
I don't understand this, because the above is essentialy the same code as:
$html = htmlentities(json_encode($ARTICLE_DESC));
$imagehtml = htmlentities(json_encode("<img src='".$imageSrc."' >"));
echo "<a href='#' onclick=\"makewindows(" . $imagehtml . "); return false;\">
<img src='".$imageSrc."' width='".$imageSize["width"]."' height='".$imageSize["height"]."'></a>
<p>Click for full description </p>";
which produces the following html which works fine:
<a href="#" onclick='makewindows("<img src=\"..\/images\/160329461329.jpg\" >"); return false;'>
<img src="../images/160329461329.jpg" width="199" height="300"></a>
I know it has something to do with quotes, but I am not sure what exactly.
Try this:
$imagehtml = htmlspecialchars(json_encode("<img src=\"".$imageSrc."\" >"), ENT_QUOTES);
$screenshotLink = "<p>View Screenshot";
$imagehtml = htmlspecialchars(json_encode('<img src="'.$imageSrc.'" >'), ENT_QUOTES);
$screenshotLink = '<p>View Screenshot';
Why not use ticks?
Lookup the ENT_NOQUOTES parameter in the php manual
And htmlspecialchars() != htmlentities() btw.

PHP If else statement that a database record is empty it will display a default picture

Hi basicly I am trying to create a simple IF statement that shows a default picture if one hasn't been entered in to my database. I am using server to store my picture and a database to store the file name, so I can get the image to display if it has a file name in the db but I want the If statement to say if the record is empty display this default image. I have some code here that I have tried however it doesn't work any thoughts? I tried a few other ways of doing it but they didn't work either.
Cheers.
Code so far:
//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM db*****") or die(mysql_error());
//Puts it into an array
while($info = mysql_fetch_array( $data ))
{
?>
<div class="member">
<div class="imageSection">
<?
if($info['photo'] == '')
{echo "<img class=\"memberImage\" src=images/default.jpg>";}
else {echo "<img class=\"memberImage\" src=images/".$info['photo'] .">";}
?>
</div>
<div class="memberInfo">
<? Echo "<p><strong>Name: ".$info['nameMember'] . "</strong></p>";
Echo "<p>Position: ".$info['bandMember'] . " </p>";
Echo "<p>About Band Member ".$info['nameMember'] .":".$info['aboutMember'] . "</p>";
Echo "<p>Other Bands: ".$info['otherBands'] . " </p><br/></div></div><br class=\"clearBoth\"/>";
}
?>
What about a simple ternary:
$photo = ($info['photo'] == null) ? "default.jpg" : $info['photo'];
echo "<img class=\"memberImage\" src=images/". $photo .">";
Are you sure the default value for the column is set to "". it could be set to null? although idk if that would cause it not work.
add the following code before the if statement
echo $info['photo'];
Another suggestion would be to trim the data before comparing it.
You could use file_exists, which will work even if the image is deleted manually.
$photo = 'images/'. $info['photo'];
if (file_exists($photo) == FALSE)
{
$photo = 'images/default.jpg';
}
echo '<img class="memberImage" src="'. $photo .'"/>';
empty() can catch the sort of conditions you are after, so try
if(empty($info['photo']))
{
....
}
empty() returns true if the parameter is '', NULL, false, '0', 0, or an empty array.

php and mysql not showing data, not entering foreach loop

I am having trouble with modifying a php application to have pagination. My error seems to be with my logic, and I am not clear exactly what I am doing incorrectly. I have had before, but am not currently getting errors that mysql_num_rows() not valid result resource
and that invalid arguments were supplied to foreach. I think there is a problem in my logic which is stopping the results from mysql from being returned.
All my "test" echos are output except testing while loop. A page is generated with the name of the query and the word auctions, and first and previous links, but not the next and last links. I would be grateful if a more efficient way of generating links for the rows in my table could be pointed out, instead of making a link per cell. Is it possible to have a continuous link for several items?
<?php
if (isset($_GET["cmd"]))
$cmd = $_GET["cmd"]; else
die("You should have a 'cmd' parameter in your URL");
$query ='';
if (isset($_GET["query"])) {
$query = $_GET["query"];
}
if (isset($_GET["pg"]))
{
$pg = $_GET["pg"];
}
else $pg = 1;
$con = mysql_connect("localhost","user","password");
echo "test connection<p>";
if(!$con) {
die('Connection failed because of' .mysql_error());
}
mysql_query('SET NAMES utf8');
mysql_select_db("database",$con);
if($cmd=="GetRecordSet"){
echo "test in loop<p>";
$table = 'SaleS';
$page_rows = 10;
$max = 'limit ' .($pg - 1) * $page_rows .',' .$page_rows;
$rows = getRowsByProductSearch($query, $table, $max);
echo "test after query<p>";
$numRows = mysql_num_rows($rows);
$last = ceil($rows/$page_rows);
if ($pg < 1) {
$pg = 1;
} elseif ($pg > $last) {
$pg = $last;
}
echo 'html stuff <p>';
foreach ($rows as $row) {
echo "test foreach <p>";
$pk = $row['Product_NO'];
echo '<tr>' . "\n";
echo '<td>'.$row['USERNAME'].'</td>' . "\n";
echo '<td>'.$row['shortDate'].'</td>' . "\n";
echo '<td>'.$row['Product_NAME'].'</td>' . "\n";
echo '</tr>' . "\n";
}
if ($pg == 1) {
} else {
echo " <a href='{$_SERVER['PHP_SELF']}?pg=1'> <<-First</a> ";
echo " ";
$previous = $pg-1;
echo " <a href='{$_SERVER['PHP_SELF']}?pg=$previous'> <-Previous</a> ";
}
echo "---------------------------";
if ($pg == $last) {
} else {
$next = $pg+1;
echo " <a href='{$_SERVER['PHP_SELF']}?pg=$next'>Next -></a> ";
echo " ";
echo " <a href='{$_SERVER['PHP_SELF']}?pg=$last'>Last ->></a> ";
}
echo "</table>\n";
}
echo "</div>";
function getRowsByProductSearch($searchString, $table, $max) {
$searchString = mysql_real_escape_string($searchString);
$result = mysql_query("SELECT Product_NO, USERNAME, ACCESSSTARTS, Product_NAME, date_format(mycolumn, '%d %m %Y') as shortDate FROM {$table} WHERE upper(Product_NAME) LIKE '%" . $searchString . "%'" . $max);
if($result === false) {
echo mysql_error();
}
$rows = array();
while($row = mysql_fetch_assoc($result)) {
echo "test while <p>";
$rows[] = $row;
}
return $rows;
mysql_free_result($result);
}
edit: I have printed out the mysql error of which there was none. However 8 "test whiles" are printed out, from a database with over 100 records. The foreach loop is never entereded, and I am unsure why.
The problem (or at least one of them) is in the code that reads:
$rows = getRowsByProductSearch($query, $table, $max);
$numRows = mysql_num_rows($rows);
The $numRows variable is not a MySQL resultset, it is just a normal array returned by getRowsByProductSearch.
Change the code to read:
$rows = getRowsByProductSearch($query, $table, $max);
$numRows = count($rows);
Then it should at least find some results for you.
Good luck, James
Hi there,
The next problem is with the line that reads:
$last = ceil($rows/$page_rows);
It should be changed to read:
$last = ceil($numRows / $page_rows);
Would recommend adding the following lines to the start of you script at least while debugging:
ini_set('error_reporting', E_ALL | E_STRICT);
ini_set('display_errors', 'On');
As that would have thrown up a fatal error and saved you a whole lot of time.
if (!(isset($pg))) {
$pg = 1;
}
How is $pg going to get set? You don't appear to be reading it from $_GET. If you're relying on register_globals: don't do that! Try to read it from $_GET and parse it to a positive integer, falling back to '1' if that fails.
<a href='{$_SERVER['PHP_SELF']}?pg=$next'>Next -></a>
You appear to be losing the other parameters your page needs, 'query' and 'cmd'.
In general I'm finding it very difficult to read your code, especially the indentation-free use of echo(). Also you have untold HTML/script-injection vulnerabilities every time you "...$template..." or .concatenate a string into HTML without htmlspecialchars()ing it.
PHP is a templating language: use it, don't fight it! For example:
<?php
// Define this to allow us to output HTML-escaped strings painlessly
//
function h($s) {
echo(htmlspecialchars($s), ENT_QUOTES);
}
// Get path to self with parameters other than page number
//
$myurl= $_SERVER['PHP_SELF'].'?cmd='.urlencode($cmd).'&query='.urlencode($query);
?>
<div id="tableheader" class="tableheader">
<h1><?php h($query) ?> Sales</h1>
</div>
<div id="tablecontent" class="tablecontent">
<table border="0" width="100%"> <!-- width, border, cell width maybe better done in CSS -->
<tr>
<td width="15%">Seller ID</td>
<td width="10%">Start Date</td>
<td width="75%">Description</td>
</tr>
<?php foreach ($rows as $row) { ?>
<tr id="row-<?php h($row['Product_NO']) ?>" onclick="updateByPk('Layer2', this.id.split('-')[1]);">
<td><?php h($row['USERNAME']); ?></td>
<td><?php h($row['shortDate']); ?></td>
<td><?php h($row['Product_NAME']); ?></td>
</tr>
<?php } ?>
</table>
</div>
<div class="pagercontrols">
<?php if ($pg>1) ?>
<<- First
<?php } ?>
<?php if ($pg>2) ?>
<-- Previous
<?php } ?>
<?php if ($pg<$last-1) ?>
Next -->
<?php } ?>
<?php if ($pg<$last) ?>
Last ->>
<?php } ?>
</div>
Is it possible to have a continuous link for several items?
Across cells, no. But you're not really using a link anyway - those '#' anchors don't go anywhere. The example above puts the onclick on the table row instead. What exactly is more appropriate for accessibility depends on what exactly your application is trying to do.
(Above also assumes that the PK is actually numeric, as other characters may not be valid to put in an 'id'. You might also want to consider remove the inline "onclick" and moving the code to a script below - see "unobtrusive scripting".)
This is wrong:
if($cmd=="GetRecordSet")
echo "test in loop\n"; {
It should be:
if($cmd=="GetRecordSet") {
echo "test in loop\n";
In your getRowsByProductSearch function, you return the result of mysql_error if it occurs. In order to debug the code, maybe you can print it instead, so you can easily see what the problem is.

Categories