help formatting news entry in PHP - php

On My Site users can login and add news. That works fine. I have problems when trying to display the news. First problem is if the news text doesn't fill all the space by the side of the news image, then the next news item gets displayed too soon (not below the orange breaker) as you can see on the site at the moment. I was thinking to get around this I could set the height of each news post div to the height of the image, although the image is a little shorter than the div so I'm not sure how I'd do that.
Secondly, users put links in their news posts. How do I get them to be displayed as active? on firefox they just come out as text. Could someone point me in the right direction please!
Here's the code:
$query="SELECT id, date, title, text, author, media1, media2, deleted FROM news ORDER BY id DESC LIMIT 4";
$result=mysql_query($query);
$counter = 0;
$number1 = 1;
$number2 = 2;
while($row = mysql_fetch_array($result)){
if($row['deleted'] == 0) {
if (($counter % 2) == 0) {
echo '<div id="text">';
echo '<a name="'.stripslashes($row['title']).'" id="'.stripslashes($row['title']).'"></a>';
echo '<span class="kisstitle">'.stripslashes($row['title']).'</span><br>';
echo ' (';
echo $row['date'];
echo ')';
echo '<br>';
echo '<br>';
if((preg_match ("/\bjpg\b/",$row['media1'])) || (preg_match ("/\bjpeg\b/",$row['media1'])) || (preg_match ("/\bpng\b/i",$row['media1'])) || (preg_match ("/\bgif\b/i",$row['media1']))){
echo '<img style="max-width:300px;" src="media/news/'.$row['media1'].'" class="floatRightClear" id="border">';
}
if((preg_match ("/\bjpg\b/",$row['media2'])) || (preg_match ("/\bjpeg\b/",$row['media2'])) || (preg_match ("/\bpng\b/i",$row['media2'])) || (preg_match ("/\bgif\b/i",$row['media2']))){
echo '<img style="max-width:300px;" src="media/news/'.$row['media2'].'" class="floatRightClear" id="border">';
}
if((preg_match ("/\bmp3\b/", $row['media1']))) {
echo ' <p id="audioplayer_'.$number1.'" class="floatRightClear">Media Content</p>
<script type="text/javascript">
AudioPlayer.embed("audioplayer_'.$number1.'", {soundFile: "http://kiddiessupportscheme.org/media/news/'.$row['media1'].'"});
</script>';
echo '<br>';
}
if((preg_match ("/\bmp3\b/", $row['media2']))) {
echo ' <p id="audioplayer_'.$number2.'" class="floatRightClear">Media Content</p>
<script type="text/javascript">
AudioPlayer.embed("audioplayer_'.$number2.'", {soundFile: "http://kiddiessupportscheme.org/media/news/'.$row['media2'].'"});
</script>';
echo '<br>';
}
echo stripslashes(nl2br($row['text']));
echo '<br><br>';
echo stripslashes($row['author']);
echo '</div>';
echo '<p align="right" id="seperater">Top<img src="images/seperater.jpg" width="950" height="6" style="border:none;" /></p>';
}
else {
echo '<div id="text">';
echo '<a name="'.stripslashes($row['title']).'" id="'.stripslashes($row['title']).'"></a>';
echo '<span class="kisstitle">'.stripslashes($row['title']).'</span><br>';
echo ' (';
echo $row['date'];
echo ')';
echo '<br>';
echo '<br>';
if((preg_match ("/\bjpg\b/",$row['media1'])) || (preg_match ("/\bjpeg\b/",$row['media1'])) || (preg_match ("/\bpng\b/i",$row['media1'])) || (preg_match ("/\bgif\b/i",$row['media1']))){
echo '<img style="max-width:300px;" src="media/news/'.$row['media1'].'" class="floatLeftClear" id="border">';
}
if((preg_match ("/\bjpg\b/",$row['media2'])) || (preg_match ("/\bjpeg\b/",$row['media2'])) || (preg_match ("/\bpng\b/i",$row['media2'])) || (preg_match ("/\bgif\b/i",$row['media2']))){
echo '<img style="max-width:300px;" src="media/news/'.$row['media2'].'" class="floatLeftClear" id="border">';
}
if((preg_match ("/\bmp3\b/", $row['media1']))) {
echo ' <p id="audioplayer_'.$number1.'" class="floatLeftClear">Media Content</p>
<script type="text/javascript">
AudioPlayer.embed("audioplayer_'.$number1.'", {soundFile: "http://kiddiessupportscheme.org/media/news/'.$row['media1'].'"});
</script>';
echo '<br>';
}
if((preg_match ("/\bmp3\b/", $row['media2']))) {
echo ' <p id="audioplayer_'.$number2.'" class="floatLeftClear">Media Content</p>
<script type="text/javascript">
AudioPlayer.embed("audioplayer_'.$number2.'", {soundFile: "http://kiddiessupportscheme.org/media/news/'.$row['media2'].'"});
</script>';
echo '<br>';
}
echo stripslashes(nl2br($row['text']));
echo '<br><br>';
echo stripslashes($row['author']);
echo '</div>';
echo '<p align="right" id="seperater">Top<img src="images/seperater.jpg" width="950" height="6" style="border:none;" /></p>';
}
$number1++;
$number1++;
$number1++;
$number2++;
$number2++;
$number2++;
$counter++;
}}

to your first problem:
First problem is if the news text doesn't fill all the space by the side of the news image, then the next news item gets displayed too soon (not below the orange breaker) as you can see on the site at the moment. I was thinking to get around this I could set the height of each news post div to the height of the image, although the image is a little shorter than the div so I'm not sure how I'd do that.
You only have to edit your css file:
Change:
#seperater {
float: left;
}
To:
#seperater {
clear: both;
}
For your second problem, I found this link: http://www.sitepoint.com/forums/3713338-post5.html There is exactly the solution you need.
Code from the link I posted above:
define( 'LINK_LIMIT', 30 );
define( 'LINK_FORMAT', '%s' );
function prase_links ( $m )
{
$href = $name = html_entity_decode($m[0]);
if ( strpos( $href, '://' ) === false ) {
$href = 'http://' . $href;
}
if( strlen($name) > LINK_LIMIT ) {
$k = ( LINK_LIMIT - 3 ) >> 1;
$name = substr( $name, 0, $k ) . '...' . substr( $name, -$k );
}
return sprintf( LINK_FORMAT, htmlentities($href), htmlentities($name) );
}
$s = 'Here is a text - www.ellehauge.net - it has some links with e.g. comma, www.one.com,
in it. Some links look like this: http://mail.google.com - mostly they end with a
space or carriage return www.unis.no
<br /> - but they may also end with a period: http://ellehauge.net. You may even put
the links in brackets (www.skred-svalbard.no) (http://one.com).
From time to time, links use a secure protocol like https://gmail.com |
This.one.is.a.trick. Sub-domaines: http://test.ellehauge.net |
www.test.ellehauge.net | Files: www.unis.no/photo.jpg |
Vars: www.unis.no?one=1&~two=2 | No.: www.unis2_check.no/doc_under_score.php |
www3.one.com | another tricky one:
http://ellehauge.net/cv_by_id.php?id%5B%5D=105&id%5B%5D=6&id%5B%5D=100';
$reg = '~((?:https?://|www\d*\.)\S+[-\w+&##/%=\~|])~';
print preg_replace_callback( $reg, 'prase_links', $s );

Related

foreach() Loop Outputting Data and Creating Layout

I am currently trying to create a class schedule which I pull from my Sql Server database with PHP and I am trying to get the layout output as well as the data as I am grouping the resources.
These groupings are nested such as:
-DAY
--TIME
---CLASS
----STUDENTS
And should output like this:
However, I am getting this:
My current output is working, however, it is only on the first loop, then everything goes haywire. I am assuming there is an erroneous </div> tag somewhere in my code yet I cannot for the life of me find it.
My php code is a function that is delcare as such:
<div class="mainScheduleWrapper">
<?php daySchedule(); ?>
</div>
My php code is as such:
function daySchedule() {
global $conn;
$dayScheduleQuery = 'SET DATEFIRST 1
SELECT [DAY].[DAY] AS [DAY], CLASS.CLASSTIME AS CLASSTIME, CLASSLEVEL.CLASSLEVEL AS CLASSLEVEL, CLASS.MAXSTUDENT AS MAXSTUDENT, INSTRUCTOR.FIRSTNAME AS INSTRUCTOR, STUDENT.FIRSTNAME AS STUDENTFIRST, STUDENT.SURNAME AS STUDENTLAST, STUDENT.DOB AS STUDENTDOB
FROM STUDENT JOIN BOOKING ON STUDENT.ID = BOOKING.STUDENTID JOIN CLASS ON CLASS.ID = BOOKING.CLASSID JOIN CLASSLEVEL ON CLASS.CLASSLEVELID = CLASSLEVEL.ID JOIN [DAY] ON CLASS.CLASSDAY = [DAY].ID JOIN INSTRUCTOR ON CLASS.INSTRUCTORID = INSTRUCTOR.ID
WHERE [DAY].ID = (DATEPART(dw, GETUTCDATE() AT TIME ZONE \'AUS Eastern Standard Time\'))
ORDER BY CLASS.CLASSTIME ASC, INSTRUCTOR.FIRSTNAME ASC, CLASSLEVEL.CLASSLEVEL ASC';
// COUNTERS
$t = 0;
$i = 0;
//VARIABLES FOR DAY SCHEDULE
$classDay = NULL;
$classTime = NULL;
$classInstructor = NULL;
$closeClass = false;
$closeAll = false;
$queryConnector = $conn->query($dayScheduleQuery);
foreach ($queryConnector as $schedule) {
// CLASS DAY HEADER
if ($classDay != $schedule['DAY']) {
echo '<div class="grid-1">';
echo '<h1>' . $schedule['DAY'] . '</h1>';
echo '</div><!-- Day closed! -->';
$classDay = $schedule['DAY'];
}
// CLASS TIME HEADER
if ($classTime != $schedule['CLASSTIME']) {
if($classTime != $schedule['CLASSTIME'] && $t > 0) {
$closeAll = true;
goto closeAll;
}
echo '<div class="grid-12-noGutter scheduleContainer">'; //NON-CLOSED
echo '<h1>' . 'T = ' . $t . '</h1>';
echo '<div class="grid-middle-center col scheduleTimeTab">';
// FIX 3 DIGIT MILITARY TIME
if (strlen($schedule['CLASSTIME']) < 4) {
$classScheduleTime = '0' . $schedule['CLASSTIME'];
} else {
$classScheduleTime = $schedule['CLASSTIME'];
}
echo '<p>' . date('g:i A', strtotime($classScheduleTime)) . '</p>';
echo '</div>'; //CLOSE TIME TAB
echo '<div class="innerSchedule">'; // NON-CLOSED
$classTime = $schedule['CLASSTIME'];
$t += 100;
}
// INSTRUCTOR HEADER
if ($classInstructor != $schedule['INSTRUCTOR']) {
if ($classInstructor != $schedule['INSTRUCTOR'] && $i > 0) {
$closeClass = true;
goto closeClassWrapper;
}
echo '<div class="classWrapper">';
echo '<h1>' . 'I =' . $i . 'T = ' . $t . '</h1>';
echo '<div class="grid-3-middle classHeader">';
echo '<div class="col classHeaderCell' . classLevelColour($schedule['CLASSLEVEL']) . '">' . $schedule['CLASSLEVEL'] . '</div>';
echo '<div class="col classHeaderCell">' . $schedule['INSTRUCTOR'] . '</div>';
echo '<div class="col classHeaderCell">Max' . ' ' . $schedule['MAXSTUDENT'] . '</div>';
echo '</div>';
echo '<div class="grid-4-middle" id="studentHeaders">';
echo '<div class="col"><h6>Student Name</h6></div>';
echo '<div class="col"><h6>Student Birthday</h6></div>';
echo '<div class="col"><h6>Class Level</h6></div>';
echo '<div class="col"><h6>Attendance</h6></div>';
echo '</div>';
$classInstructor = $schedule['INSTRUCTOR'];
$i += 100;
}
echo '<div class="grid-4 studentRow">';
echo '<div class="col">';
echo '<span class="studentCell">' . $schedule['STUDENTFIRST'] . ' ' . $schedule['STUDENTLAST'] . '</span>';
echo '</div>';
echo '<div class="col">';
echo '<span class="studentCell">' . $schedule['STUDENTDOB'] . '</span>';
echo '</div>';
echo '<div class="col">';
echo '<span class="studentCell">' . $schedule['CLASSLEVEL'] . '</span>';
echo '</div>';
echo '<div class="col">';
echo '<span class="studentCell">--</span>';
echo '</div>';
echo '</div>';
// GOTO TAGS
closeClassWrapper: {
if ($closeClass === true) {
echo '</div>';
$closeClass = false;
$i = 0;
}
}
closeAll: {
if ($closeAll === true) {
echo '</div>';
echo '</div>';
echo '</div>';
$closeAll = false;
$t = 0;
$i = 0;
}
}
}
}
Any help would be greatly appreciated - even if it's to tell me I'm going about it the completely wrong way.
Kindest Regards
Michael Z
I wouldn't say you're going about it the completely wrong way, but a few red flags jumped out at me in your code.
The use of goto jumping is bad practice. It butchers your program flow and forces you to segregate tasks that shouldn't be kept apart. You marked the sections of code "// NON CLOSED" when there was a </div> missing, is there any purpose for that? How do you know the goto sections are reliable?
When you echo something like <div class="col">, without escaping the double-quotes (as in \" for every " character), it can be problematic. Your code can get mangled or misinterpreted, both on the PHP end or on the HTML end.
Like others have said, the use of PHP may be overkill here. Besides just sending the JSON, the rest could be handled with JavaScript.

Making the Comment Count on my site link to the post link or comments area

I recently updated my comments code via this tutorial. I replaced the default comments_popup_link with the following code. This works great in displaying the real comment count (FB comments + WP comments), however, I can't figure out a way to get the comment count text to link to the post permalink. Any advice?
<span class="comments-link">
<?php
$commentCount = full_comment_count();
if ( $commentCount == 0 ) {
echo '<post-date>- Leave a comment</post-date>';
}
else if ( $commentCount == 1 ) {
echo '<post-date>- One comment</post-date>';
}
else {
echo '<post-date>- ' . $commentCount . ' comments</post-date>';
}
?>
</span>
I think this way you'll be able to link to your comments
<a href="<?php the_permalink(); ?>/#comments">
<span class="comments-link">
<?php
$commentCount = full_comment_count();
if ( $commentCount == 0 ) {
echo '<post-date>- Leave a comment</post-date>';
}
else if ( $commentCount == 1 ) {
echo '<post-date>- One comment</post-date>';
}
else {
echo '<post-date>- ' . $commentCount . ' comments</post-date>';
}
?>
</span>
</a>

PHP Search: Using Jquery to alter a php a value

I have a comics website. A feature it has is to allow users to search comics... the search will instantly parse the input and return thumbnail results based on matching title and keywords.
Originally, the search would return all of the results, and the bounding search box would expand infinitely downward, holding every single comic result. I thought it may be a nice touch to limit the results to 4, and display a message like "load 5 remaining images" if the user chooses to do so.
If they click on that message, I wanted limiting php variable to be removed or changed.
So far, it loads with the limit, and shows a link...
EDIT: Latest Code:
search_field.php (the search file that get's included on a page... this file calls search.php via JQuery):
<?php $site = (isset($_GET['site']) ? ($_GET['site']) : null); ?>
<div id="sidebar" class="searchborder">
<!--Allow users to search for comic-->
<!--<span class="search">Search for <?php// echo (($site == "artwork") ? 'artwork' : 'a comic'); ?> </span>-->
<script type="text/javascript">
function GetSearch(mySearchString){
$.get("./scripts/search.php", {_input : mySearchString, _site : '<?php echo $site ?>'},
function(returned_data) {
$("#output").html(returned_data);
}
);
}
</script>
<center>
<table>
<tr>
<td>
<span class="search">
<img src="./images/SiteDesign/Search.png" />
<input type="text" onkeyup="GetSearch(this.value)" name="input" value="" />
<!--<input id="site" type="hidden" value="<?php// echo $site; ?>">-->
</span>
</td>
</tr>
</table>
</center>
<span id="output"> </span>
</div>
search.php, the file that's called to parse the string and return the results:
<?php
//Query all images:
include 'dbconnect.php';
$site = $_GET['_site'];
$input = (isset($_GET['_input']) ? ($_GET['_input']) : 0);
$siteChoice = (isset($_GET['_choice']) ? ($_GET['_choice']) : $site);
$start = (isset($_GET['_start']) ? ($_GET['_start']) : null);
echo "start: " . $start;
//if user goes to hittingtreeswithsticks.com... no "site" value will be set... so I need to set one
if ($site == null) {
$site = "comics";
}
if ($siteChoice == "artwork") {
$sql = "SELECT id, title, keywords, thumb FROM artwork";
$thumbpath = "./images/Artwork/ArtThumbnails/";
}
else if ($siteChoice == "comics") {
$sql = "SELECT id, title, keywords, thumb FROM comics";
$thumbpath = "./images/Comics/ComicThumbnails/";
}
else {
$sql = "SELECT id, title, keywords, thumb FROM $site";
if ($site == "artwork") {
$thumbpath = "./images/Artwork/ArtThumbnails/";
}
else {
$thumbpath = "./images/Comics/ComicThumbnails/";
}
}
/* For this to work, need all comics replicated in an "All Comics" file along with "All Thumbnails"
else {
$sql = "SELECT id, title, thumb FROM comics
UNION
SELECT id, title, thumb FROM artwork";
$thumbpath = "./images/AllThumbnails/";
}*/
$imgpaths = $mysqli->query($sql);
mysqli_close($mysqli);
$idresult = array();
$imgresult = array();
$thumbresult = array();
//CHECK IF $INPUT == IMAGE PATH
if (strlen($input) > 0)
{
while ($row = $imgpaths->fetch_assoc())
{
//query against key words, not the image title (no one will remember the title)
if (stripos($row['keywords'], $input) !== false || strtolower($input)==strtolower(substr($row['title'],0,strlen($input))))
//if (strtolower($input)==strtolower(substr($row['title'],0,strlen($input))))
{
array_push($idresult, $row['id']);
array_push($imgresult, $row['title']);
array_push($thumbresult, $row['thumb']);
}
}
//ECHO RESULTS ARRAY
if(count($imgresult) == 0)
{
echo "<p>no suggestions</p>";
}
else
{
echo "<ul>";
$k = 0;
$max = 4;
if (count($imgresult) > $max) {
while ($k < count($imgresult) && $k < $max)
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
$difference = count($imgresult)-$k;
echo "<br/><i><a href='.?action=homepage&site=" . $siteChoice . "&start=4' class='loadSearch'>load " . $difference . " more result" . (($difference != 1) ? 's' : '') . "... </a></i>";
}
else {
while ($k < count($imgresult))
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
}
echo "</ul>";
}
}
?>
<script type="text/javascript">
$(".loadSearch").click(function() {
//alert("Test");
$.get("./search.php", {_start : 4},
function (returned_data) {
$("#moreResults").html(returned_data);
}
);
});
</script>
Try this:
<script type="text/javascript">
$("#loadSearch").click(function() {
$.get('URL WITH QUERY', function(data) {
$('#results').html(data);
});
});
</script>
From what i get all you need is when "load more" is clicked only new results should be shown.
Load more has to be a url same as your search url.
Search/Autocomplete URL - example.com/autocomplete?q=xkd
Load More URL - example.com/autocomplete?q=xkd&start=4&max=1000
Just add two parameters to your url. start and max. Pass them to your queries and you get exact result.
Only verify Start < Max and are integers intval() and not 0 empty(). Also if Max <= 4 then dont show load more.
I would give all of your results back, then try to determine your results. If more then 4, loop out the first 4 results. If the user clicks on the load more button your start looping from your 4th element. That way you only need to hit the server once (per search).
Try to give back your results in json, so you can format it the way you like in your html file.
In pseudo code:
searchTerm = 'hello';
resultsFromServer = getResults($searchterm);
resultcounter = count(resultsFromServer);
if(resultcounter > 4)
loop 4 results
else
loop all results
$(".loadSearch").click(function(e) {
//alert("Test");
e.preventDefault();
$.get("./search.php", {_start : 4},
function (returned_data) {
$("#moreResults").html(returned_data);
}
);
I ended up going with jquery show and hide functions.
PHP Snippet:
//ECHO RESULTS ARRAY
if(count($imgresult) == 0)
{
echo "<p>no suggestions</p>";
}
else
{
echo "<ul>";
$k = 0;
$max = 4;
while ($k < count($imgresult) && $k < $max)
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
$difference = count($imgresult)-$k;
echo '<div id="moreResults">';
while ($k < count($imgresult))
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
echo '</div>';
if (count($imgresult) > $max) {
?>
<br />Load <?php echo $difference; ?> more result<?php echo (($difference != 1) ? 's' : ''); ?>...
<?php
}
echo "</ul>";
}
}
Jquery:
<script type="text/javascript">
$("#moreResults").hide();
$("#showMore").click(function() {
$("#moreResults").show();
$("#showMore").hide();
});

PHP while loop split into two

I'm running a while loop which is taking rows from mySQL and echo'ing them out. Pretty standard. However, there needs to be different HTML markup for the first item, next two items, then it continues as normal into the while loop.
Currently, my while loop looking something like this:
while( ( $row = mysql_fetch_object( $result ) ) !== false )
{
// Places ad based of predefined variable frequency
if ($ad == $adFrequency){
echo '<div class="one-advertisement-article clearfix">';
echo '<div class="grid_9 suffix_2"><img src="http://placehold.it/263x75/000000/ffffff"></div>';
echo '<div class="grid_1"><a class="navigate-right-icon ss-icon" href="#">navigateright</a></div>';
echo '</div>';
$ad = 0;
}
echo '<div class="one-news-article clearfix">';
if( $row->imagelibid )
{
$imageid = intval( $row->imagelibid );
$image_result = mysql_query( "SELECT * FROM imagelib WHERE id = {$imageid}", $db );
$image_row = mysql_fetch_object( $image_result );
$image_url = "http://www.#.com/slir/w280/imagelib/" . $image_row->id . "_" . $image_row->filename;
echo '<div class="grid_4"><img src="'.$image_url.'"></div>';
}
else {
echo '<div class="grid_4"><div class="news-placeholder"><span class="ss-icon">ellipsischat</span></div></div>';
}
echo '<div class="grid_7">';
echo '<h2>'.$row->title.'</h2>';
$published_date = date('D, d M Y', strtotime($row->datein));
echo '<p class="published-date">'.$published_date.'</p>';
echo '</div>';
echo '<div class="grid_1">';
echo '<div class="news-item-vertical-sep"> </div>';
echo '<p></p>';
echo '</div>';
echo '</div>';
$ad++;
}
This works fine, but I need to take the first three news items and use this:
echo ' <div class="one-news-featured-article clearfix">';
echo ' <div class="grid_12">';
if( $row->imagelibid )
{
$imageid = intval( $row->imagelibid );
$image_result = mysql_query( "SELECT * FROM imagelib WHERE id = {$imageid}", $db );
$image_row = mysql_fetch_object( $image_result );
$image_url = "http://www.#.com/slir/w280/imagelib/" . $image_row->id . "_" . $image_row->filename;
echo '<div class="large-featured-image-container"><img src="'.$image_url.'">/div>';
}
echo ' <div>';
echo ' <h2>'.$row->title.'</h2>';
echo ' </div>';
echo ' </div>';
echo ' </div>';
echo ' <div class="grid_6">';
Any help? Essentially, it needs to apply the second code to the first three items in the query, then follow through with the code included in the current while loop - like an offset I guess.
Thanks,
R
This is quite simple. I hope I understood your question correctly:
$i = 0;
while ( ( $row = mysql_fetch_object( $result ) ) !== false ) {
if ($i < 3) {
// First code
} else {
// Second code
}
$i += 1;
}
Firstly, you should avoid using any mysql_ functions as they are all deprecated and will be removed from future versions of PHP. I'd recommend using PDO instead. See this tutorial to get started.
Then, it'll simply be a case of doing something like this:
foreach($db->query($query) as $index => $row) {
if ($index < 3) {
// first 3 items
} else {
// other items
}
}
You can do it easaly with an simple counter and an if statement:
$count = 0;
while(fetching) {
if($count < 3) {
// items 1, 2 and 3
} else {
// do normal
}
$count++;
}

Embed from imgur

I'm currently using this code for embedding from youtube:
if($e['domain'] == "youtube.com") {
preg_match('/[\\?\\&]v=([^\\?\\&]+)/',$e['url'],$matches);
if(count($matches) > 1) {
$embed = true;
$embed_code = "<object width='480' height='344'><param name='movie' value='http://www.youtube.com/v/" . $matches[1] . "?fs=1&hl=en_US&color1=FFFFFF&color2=FFFFFF'></param><param name='allowFullScreen' value='true'></param><param name='allowscriptaccess' value='always'></param><embed src='http://www.youtube.com/v/" . $matches[1] . "?fs=1&hl=en_US&color1=FFFFFF&color2=FFFFFF' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='480' height='344'></embed></object>";
}
}
And I want to use kind of the same for imgur.com which uses the prefix "i" for embedding. So the images are prefix+$e. How do I make it work?
Right now I've tried:
if($e['domain'] == "i.imgur.com") {
preg_match('/[\\?\\&]([^\\?\\&]+)/',$e['url'],$matches);
if(count($matches) > 1) {
$embed = true;
$embed_code = "<img src='http://i.imgur.com/' alt='' title='Hosted by imgur.com' />";
}
}
But I get this error message:
Notice: Undefined variable: embed in /hsphere/local/home/xx/xx/xx/xx/view.php on line 107
EDIT: Here are the lines from 105-116:
else $embed = false;
if(isset($e['description']) || $embed == true) { ?>
<tr class="listing_spacer_tr"><td colspan="6"></td></tr>
<tr><td colspan="5"></td><td>
<?php if($embed) echo $embed_code . "<br /><br />"; ?>
<?php // DESCRIPTION
if(isset($e['description'])) { ?>
<div class="view_description"><?php echo make_clickable(nl2br($e['description'])); ?></div>
<?php }
} ?>
There isn't problem in code you have posted. You've probably got some problems somewhere else. Problem is reading, not assigning value to your $embed variable.

Categories