hiding content when variable is not present - php

I am using php to publish news articles from my mysql database. The articles have images placed within their text. The images are stored as variables, each its own path. The problem is I don't always use the full complement of images for each article, and the way I've written it, a broken image displays.
In short, how can I keep broken images from showing up if say '$image_ii' or '$image_iii' does not exist for a specific ID.
The way I have it written out is as follows:
<?php
include ('connect.php');
$friendly_url=$_GET['friendly_url'];
$query = "SELECT * FROM entries WHERE friendly_url='$friendly_url'";
$entries = mysql_query($query);
while($row = mysql_fetch_array($entries, MYSQL_ASSOC))
{
$title = $row['title'];
$author = $row['author'];
$pub_date = $row['pub_date'];
$content_i = $row['content_i'];
$content_ii = $row['content_ii'];
$content_iii = $row['content_iii'];
$content_iv = $row['content_iv'];
$image_i = $row['image_i'];
$image_ii = $row['image_ii'];
$image_iii = $row['image_iii'];
$image_caption_i = $row['image_caption_i'];
$image_caption_ii = $row['image_caption_ii'];
$image_caption_iii = $row['image_caption_iii'];
$pre_link = $row['pre_link'];
$post_link = $row ['post-link'];
$id = $row['id'];
$friendly_url = $row['friendly_url'];
$american_date = date("F d, Y", strtotime($pub_date));
$friendly_content_i = nl2br($content_i);
$friendly_content_ii = nl2br($content_ii);
$friendly_content_iii = nl2br($content_iii);
$friendly_content_iv = nl2br($content_iv);
echo "
<div id='post'>
<div id='post-title'>$title</div>
<div id='post-content'
$friendly_content_i
<div id='media'> <img src='../$image_i' class='scale-image'> </div>
<div id='media-caption'> $image_caption_i </div>
$friendly_content_ii
<div id='media'> <img src='../$image_ii' class='scale-image'> </div>
<div id='media-caption'> $image_caption_ii </div>
$friendly_content_iii
<div id='media'> <img src='../$image_iii' class='scale-image'> </div>
<div id='media-caption'> $image_caption_iii </div>
$friendly_content_iv
</div>
<div id='post-footer'> by $author <br> $american_date </div>
</div>
</div> ";
} mysql_close($connection); ?>
Apologies if this is terrible, it's my first dynamic website.

Try using the following snippet
if (file_exists("../".$image_iii)) {
echo "<img src='../$image_iii' class='scale-image'>";
} else {
echo "<img src='../default-image' class='scale-image'>";
}

I ended up finding a solution that worked using:
if (!empty($image_iii)) { echo "<img src='../$image_iii' class='scale-image'>"; }
else { echo "";}
That said, clearly you kind folks are right about me needing to swap over to mysqli...found this website as a good resource for migrating code to mysqli. Thanks to everyone who responded, everyones comments were helpful.

You already told us the solution to your problem:
if say '$image_ii' or '$image_iii' does not exist for a specific ID.
Use if file_exists() to check that your image exists, and don't output it, if it doesn't.
Furthermore I see you're using mysql_query - This is deprecated and very unsafe. You should use mysqli or PDO instead

Related

PHP linking from one page to the next

I am trying to create a small website to sell items on and learn php. I have a index.php which links to a chairs.php page and then from there to a viewItem.php page depending on which item they choose.
I have in my database 4 items. On the chairs.php a while loop runs to display on the page all items in that database.
I would like to use the id of the item to link to the next page but I think the while loop is always going to assign to the variable that I am using the very last entry in that while loop.
Can someone point me in the direction of how I would resolve this? I would like the user to select a Chair 1 on my Chairs.php page with ID 1 in my db to link to the corresponding page. Currently all links on the chairs.php would link to the last item in my while loop which is then assigned to the $_SESSION['output_id'] = $output_id variable.
Thank You
<?php
$query = "SELECT * FROM `chairs_table";
$queryChairs = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($queryChairs)) {
$output_id = $row["ID"];
$output_img = $row["Image"];
$output_name = $row["Name"];
$output_desc = $row["Desc"];
$output_price = $row["Price"];
$_SESSION['output_id'] = $output_id;
$_SESSION['output_img'] = $output_img;
$_SESSION['output_name'] = $output_name;
$_SESSION['output_desc'] = $output_desc;
$_SESSION['output_price'] = $output_price;
?>
<div class="itemContainer" onclick="location.href = 'viewItem.php?id=<?php echo "{$output_id}" ?>'" style="cursor:pointer;" >
<div> <img src = "img/<?php echo "{output_img}" ?>"> </div>
<div class="itemTextTitle"><?php echo"{$output_name}" ?></div>
<div class="itemTextDesc"><?php echo"{$output_desc}" ?></div>
<div class="itemTextPrice">cop <?php echo"{$output_price}"?></div>
</div>
<?php
}
?>
</div>

Generate an accordion from PHP and MySQL

Okay guys this is going to be one long question so please bear with me.
I want to create an accordion with contents in it:
How I want the image to look like
How it looks right now
I have a web application, where I upload various types(blog, homepage) of images every week. The first week is round 1 and the image can be labelled something like 1.x.x where 1 is the number corresponding to the week. Likewise for 2.x.x, 3.x.x etc.
I insert these images to a server using php and log the entry into a database, with information like project_name, file_name, url, version etc.
What I want to do is, automatically generate multiple accordion tabs one below the other. First tab should be the round corresponding to the latest week of uploading. Below that the week before and like wise till it reaches round 1(See images attached).
Now I am able to pull data and display files from ALL the rounds in a single round. What I want to do is separate rounds, automatically based on version number.=>> 1.x.x files in Round 1, 2.x.x in round 2 etc
Following is the code that I have written. The commented part is what I have been follow and and do. I am a total new comer to PHP and would appreciate it if anyone could help me with this. Thanks!
$project_name_download_form = $_GET['project_name'];
$file_name_download_form = $_GET['file_name'];
$version_download_form = $_GET['version'];
$download_data = "SELECT *
FROM projects, files
WHERE project_id = projects.id
AND project_name = '$project_name_download_form'
AND file_name = '$file_name_download_form'
AND version = '$version_download_form'";
mysqli_select_db($conn, $GLOBALS['database']);
$return_data = mysqli_query($conn, $download_data);
if (!$return_data) {
die('Could not get what you wanted: ' . mysqli_error($conn));
}
while ($row = mysqli_fetch_array($return_data)) {
$url = $row['url'];
$project_folder = $row['project_folder'];
//$id = 18;
$file_name = $row['file_name'];
$version = $row['version'];
$details = $row['details'];
$file = $row['file'];
$new = basename($row['file']); // GET FILE NAME ONLY, GET RID OF PATH.
// $design->url = $row[file_name]
// $design->version = $row[version]
// $designs.push ($design)
}
mysqli_free_result($return_data);
// $lastRound = 0;
// for each $design in $designs
// {
// $round = $design.version.split('.')[0];
// if $round <> $lastRound {
?>
<div class="col-sm-2" id = "accordianSet">
<div class="panel-group" id="accordion">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseOne"><span>
</span>Explore</a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse">
<div class="panel-body">
<?php
}
?>
<?php
// <HTML FOR LINK >
}
echo "<table class = 'table'>";
echo "<tr>";
echo " <th>File Name</th>
<th>File Link</th>";
echo "</tr>";
What you want to do is pull the results for each week and loop through but each time you loop you want to print variables in html like follows:
<?php
$i=0
while ($row = mysqli_fetch_array($return_data)) {
$url = $row['url'];
$project_folder = $row['project_folder'];
//$id = 18;
$file_name = $row['file_name'];
$version = $row['version'];
$details = $row['details'];
$file = $row['file'];
$new = basename($row['file']);
$i++
//1st Round
echo' <table>
<caption> Round $i</caption>
<tr>
<th>File Name</th>
<td>$file_name</td>
</tr>
<tr>....
</tr>
</table>';
}//while loop close tag
Note that you can format the data anyway you want but you have to spit out the html as you loop through the mysql results. Hope this helps.

No images displayed on the page after querying the database PHP mysql

This is my first post on stackoverflow after following posts for a very long time.
My problem is, I have a function that is supposed to retrieve data from a table (models) and display a name, location and an image to one of the pages. Everything is working but the images don't get displayed. Please look at my code and tell me what I should change to get these images to display. I'm using twitter bootstrap for styling.
My directory is: localhost/mainsite/admin/uploads
I've checked everything related to this post and tried it out but they didn't solve my problem. So please help.
function view_models() {
global $dbc;
$q = "SELECT * FROM models";
$r = mysqli_query($dbc, $q);
while ($row = # mysqli_fetch_array($r)) {
$id = $row['model_id'];
$mn = $row['model_name'];
$ln = $row['location'];
$img = $row['image1'];
echo "
<div class='col-xs-6 col-lg-3'>
<h3>$mn</h3>
<a href='details.php?id=$id'>
<img src='admin/uploads/$img' class='img-thumbnail' />
<p>$ln</p>
</div>";
}
}
Try this.,
I have changed the echo statement because you did a error, that was misplaced '&"
echo "<div class='col-xs-6 col-lg-3'>
<h3>".$mn."</h3>
<a href='details.php?id=".$id."'>
<img src='admin/uploads/".$img."' class='img-thumbnail' />
<p>".$ln."</p>
</a>
</div>";

Display data for specific ID

I have been trying for a while to figure out how to display data from a specific row within my database based on the ID.
Say I want the link to be survivaloperations.net/page/mso?p=contracts&id=#
where id=# is the ID of the row I am pulling data from in the database
How would I pull and display data from the database using a link like shown above?
I Tried to google it, but didn't really know what to google to find related things
Any help or links for references are appreciated!
Here is what I had tried:
<?php
if ($p == contracts) {
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0; // if $_GET['id'] exists, return it as an integer, otherwise use a sentinel, id's usually start with 1, so 0 works
if ($id != 0):
// I assume this is a specific news item meaning you know it's ONE result
$query = 'SELECT * FROM contracts WHERE id=' . $id . ' LIMIT 1'; // so try to use limit 1, no need to add extra steps in the database lookup
endif;
mysql_select_db('survival_contracts');
$result = mysql_query($query);
//$result = mysql_query($query) or die(mysql_error());
// now loop through the results
while ($row = mysql_fetch_array($result)) {
// and use'em however you wish
echo("<div class='mso_body_wrap'>
<div id='mso_news_container'>
<div class='mso_news_wrap'>
<div class='mso_news_top'>$row2[contract_type]</div>
<div class='mso_news_poster'>
<div class='mso_poster_avatar'><img src='images/tank.jpg'></div>
<div class='mso_poster_info'>for <a
href='#'>$row2[unit]</a><br/>by: <a
href='http://www.survivaloperations.net/user/$row2[userid]-$row2[username]/'>$row2[username]</a>
</div>
</div>
<div class='mso_news_content'>
<div class='mso_news_body'>
Callsign: $row2[callsign]<br/>
Urgency: $row2[urgency]<br/>
Location: $row2[location]<br/>
Grid: $row2[grid]<br/>
Enemy Activity: $row2[enemy_activity]<br/>
Hours Since Lasrt Contact: $row2[contact_hours]<br/><br/>
Supplies Requested: $row2[supplies]<br/>
Comments: $row2[comments]
</div>
</div>
<div class='mso_news_bottom'></div>
</div>
</div>");
}
?>
I figured it out with my original code:
if ($p == contracts)
{
$cid = $_GET['id']; // if $_GET['id'] exists, return it as an integer, otherwise use a sentinel, id's usually start with 1, so 0 works
$query = 'SELECT * FROM contracts WHERE id='. $cid .' LIMIT 1'; // so try to use limit 1, no need to add extra steps in the database lookup
mysql_select_db('survival_contracts');
$result = mysql_query($query);
//$result = mysql_query($query) or die(mysql_error());
// now loop through the results
while($row = mysql_fetch_array($result)){
// and use'em however you wish
echo ("<div class='mso_body_wrap'>
<div id='mso_news_container'>
<div class='mso_news_wrap'>
<div class='mso_news_top'>$row[contract_type]</div>
<div class='mso_news_poster'>
<div class='mso_poster_avatar'><img src='images/tank.jpg'></div>
<div class='mso_poster_info'>for <a href='#'>$row[unit]</a><br />by: <a href='http://www.survivaloperations.net/user/$row[userid]-$row[username]/'>$row[username]</a></div>
</div>
<div class='mso_news_content'>
<div class='mso_news_body'>
Callsign: $row[callsign]<br />
Urgency: $row[urgency]<br />
Location: $row[location]<br />
Grid: $row[grid]<br />
Enemy Activity: $row[enemy_activity]<br />
Hours Since Lasrt Contact: $row[contact_hours]<br /><br />
Supplies Requested: $row[supplies]<br />
Comments: $row[comments]
</div>
</div>
<div class='mso_news_bottom'></div>
</div>
</div>");
}
Google for $_GET variable in PHP and have a look at database connection using PDO or mysqli
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/pdo.query.php
After you added code:
mysql_* is deprecated. Try to switch to either mysqli or PDO and have a look at the link above.
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT) ? abs( (int) $_GET['id']) : 0;
if($id == 0) {
echo 'Invalid ID';
return;
} else {
$query = "SELECT * FROM `table` WHERE `id`=". $id;
$get = $db->prepare($query);
if($get) {
$get = $db->query($query);
$r = $get->fetch_array(MYSQLI_ASSOC);
var_dump($r);
} else {
echo 'Could not connect to the database';
return;
}
I've mixed two styles of MySQLi, which isn't really standard, but it should suffice for this example.
http://php.net/mysqli
(Ensure you have database connection)
$row2 should be $row
And things like
$row[contract_type]
Better to be
$row['contract_type']
And try to move to mysqli or PDO as advised by earlier poster

How I can do client side pagination for DIV elements generated from MYSQL query?

I have this PHP code :
$query = "SELECT * FROM news WHERE news_active = 1 AND news_type = 1 ORDER BY id DESC";
$q2 = "SELECT * FROM st_photos WHERE id = 4 LIMIT 1";
$r2 = mysql_query($q2);
$row22 = mysql_fetch_array($r2);
$news_set = mysql_query($query);
$news_set2 = mysql_query($query);
if (mysql_num_rows($news_set) != 0) {
$r = mysql_fetch_array($news_set);
echo "<div id=\"d_coll\">
<div id=\"top_text\">$row22[img]</div>
<div id=\"d_image\"><img id=\"larg_p2\" src=\"photos/$r[news_image]\" width=\"320\" height=\"250\" border=\"0\"></div>
<div style=\"width:300px\"><div id=\"n_text2\">$r[news_part_en]</div>
</div>
</div>";
}
if (mysql_num_rows($news_set2) != 0) {
while ($news = mysql_fetch_array($news_set2)) {
echo "<div id=\"n_col\">
<div id=\"n_tittle\">$news[news_tittle_en] <img src=\"images/bu3.png\" border=\"0\" align=\"middle\"></div>
<div id=\"im\"><img onMouseOver=\"MM_swapImage('larg_p2','','photos/$news[news_image]','imgs[$news[id]]','','photos/$news[news_image]',1);up2('$news[news_part_en]')\" onMouseOut=\"MM_swapImgRestore()\" name=\"imgs[$news[id]]\" id=\"imgs[$news[id]]\" src=\"photos/$news[news_image]\" width=\"50\" height=\"50\"></div>
<div dir=\"ltr\" id=\"n_div\">$news[news_part_en] <div class=\"mo\">MORE</div></div>
</div>";
}
echo "<div align=\"right\" class=\"arr\"><img src=\"images/prev.png\"> <img src=\"images/next.png\"></div>";
}
There are 2 images at the end of the code (prev & next), I want to use them to do pagination but I don't want to view any numbers, only these 2 images.
How I can do that?
I think we can do that by using JQuery library, but I don't know how to use it.
Thanks in advance.
you can use one of many plugins, for example here .
you must just remoove thе numbers. you can, i believe;)
or you can write the script by yourself.
i'll give you only an idea. let's assume you have 30 rows( from DB).put them into <div> tags, and increase the id of div. the display proparty of first <div> you must set to '', and all others to none. and then, onclick on your buttons, you just change display proparty of div elements...

Categories