Jump to content

Most efficient code


Go to solution Solved by mystic7,

Recommended Posts

Hey, I'm just learning PHP. Used to be an ASP programmer so I'll have a lot of questions on how to do things in php that I used to do in ASP. Anyway, I am teaching myself by building a blog from an HTML template. Afterwards I'll study my code to really see what does what, proper syntax etc.

 

On my home page there are two div's, each with different names but each containing the same information, i.e. a preview of a blog post. I have it so the two most recent posts show. The way I'm doing it is, I'm calling the top post with the following SQL statement:

$sql="SELECT * FROM $tbl_name ORDER BY id DESC LIMIT 1";

I'm then displaying that post in the first div. For the second div, I'm retrieving the post previous to that with this SQL statement:

 

$id = $rows['id'];
$id2 = $id - 1;
$sql="SELECT * FROM $tbl_name WHERE id = $id2";
 
This all works, but I'm wondering if there is a way to loop through the recordset and grab the two latest posts and then display them. The thing that's stopping me right now is the fact that the two posts are contained within two differently named divs. Or is my method acceptable as is?
Link to comment
https://forums.phpfreaks.com/topic/282642-most-efficient-code/
Share on other sites

I would suggest grabbing both of the new entries at the same time.

$sql="SELECT * FROM $tbl_name ORDER BY id DESC LIMIT 2";

You could then use a loop to separate the entries to display the divs. Decrementing the $id variable may work for the most part. But what if one of the row IDs gets removed?

Edited by cyberRobot
Link to comment
https://forums.phpfreaks.com/topic/282642-most-efficient-code/#findComment-1452209
Share on other sites

Hey, thanks for responding. As I said this is just a fake blog that I'm using to get familiar with php syntax, so right now it doesn't matter if a row ID gets deleted. In fact that already happened so I just manually renumbered the recordsets in phpMyAdmin. 

 

If I may be so dense, could you explain, or point me to, directions on how to separate the entries using a loop? I know how to loop through recordsets in a database but I've never looped through recordsets after I've called for them. Again, if it's a normal looping procedure, how do I display the two recordsets inside two different divs?

Link to comment
https://forums.phpfreaks.com/topic/282642-most-efficient-code/#findComment-1452227
Share on other sites

EDIT: OK, I used a loop, and changed my SQL statement, and it does pull the last two posts and displays them, but the second one is not formatted nicely because it's going by the CSS rules for the first div. I'm going to try and come up with a way to dynamically change the name of the div with each loop in the meantime but if you have a better solution I'd love to hear it.

Link to comment
https://forums.phpfreaks.com/topic/282642-most-efficient-code/#findComment-1452235
Share on other sites

You can do something like

$classes = array('class1', 'class2'); // define div classes here

$i = -1; // initiate counter to -1
while(/* how you fetch next record */) {
    $class = $classes[++$i]; // get the next class, ++$i will increment $i by 1
    echo '<div class="' . $class . '">your div contents</div>';
}

On the first iteration it'll set the div class to class1 and on the secoud iteration it'll set the class to class2

Edited by Ch0cu3r
Link to comment
https://forums.phpfreaks.com/topic/282642-most-efficient-code/#findComment-1452237
Share on other sites

You can do something like

$classes = array('class1', 'class2'); // define div classes here

$i = -1; // initiate counter to -1
while(/* how you fetch next record */) {
    $class = $classes[++$i]; // get the next class, ++$i will increment $i by 1
    echo '<div class="' . $class . '">your div contents</div>';
}

On the first iteration it'll set the div class to class1 and on the secoud iteration it'll set the class to class2

Yes, that's exactly what I did, if slightly less elegantly ;) But as I said, it messes up other CSS layout rules, so I'll leave it and concentrate on the PHP portion for now. I will, however, keep your code as a better way of implementing what I did with my usual half wit solution. Thanks!

Link to comment
https://forums.phpfreaks.com/topic/282642-most-efficient-code/#findComment-1452240
Share on other sites

Also (sorry, I'm not allowed to edit my posts yet) the div names were "post_box" and "post_box post_box_last", which I can't change using your method (it's a template I found, again, for the purpose of learning PHP, not web design).

 

This is the code I used, which actually worked, but like I said, messed up other parts of the page layout:

 

$count = 1;
If ($count = 1)
{
$div = "post_box";
}
Else
{
$div = "post_box post_box_last";
}
Link to comment
https://forums.phpfreaks.com/topic/282642-most-efficient-code/#findComment-1452242
Share on other sites

Can anyone tell me what's wrong with my If...Else statement? My $count is changing from 1 to 2 but the value of "div" is not changing.

 

// Start looping rows in mysql database.
$count = 1;
while($rows=mysql_fetch_array($result)){
$mystring = $rows['message'];


If ($count = 1)
{
$div = ("post_box");
}
Else
{
$div = ("post_box post_box_last");
}


?>
      <div class="<? echo $div; ?>"> <img src="images/templatemo_image_01.jpg" alt="image" />
        <div class="post_box_right">
          <h2><? echo $rows['title']; ?></h2>
          <div class="post_meta"><strong>Date: </strong><strong><? echo $rows['dateday']; ?></strong> <? echo $rows['datemonth']; ?> <? echo $rows['dateyear']; ?>| <strong>Author: </strong><? echo $rows['name']; ?></div>
          <p><? echo substr($mystring, 0, 100); ?>...</p>
          <a href="blog_post.php?id=<? echo $rows['id']; ?>" class="more">Read more</a><br />
          <div class="category">Category: <a href="#">Freebies</a>, <a href="#">Templates</a> | <a href="blog_post.php">244 comments</a></div>
        </div>
        <?php
// close while loop 
$count = $count + 1;


}
Link to comment
https://forums.phpfreaks.com/topic/282642-most-efficient-code/#findComment-1452249
Share on other sites

GOT IT! I had to alter your classes code a bit but I got it working:

// Retrieve data from database 
$sql="SELECT * FROM $tbl_name ORDER BY id DESC LIMIT 2";
$result=mysql_query($sql);


// Start looping rows in mysql database.
$classes = array('post_box', 'post_box post_box_last'); // define div classes here
$i = -1; // initiate counter to -1
while($rows=mysql_fetch_array($result)){
$divname = $classes[++$i]; // get the next class, ++$i will increment $i by 1
$mystring = $rows['message'];


?>
 <div class= "<? echo $divname; ?>"><img src="images/templatemo_image_01.jpg" alt="image" />
        <div class="post_box_right">
          <h2><? echo $rows['title']; ?></h2>
          <div class="post_meta"><strong>Date: </strong><strong><? echo $rows['dateday']; ?></strong> <? echo $rows['datemonth']; ?> <? echo $rows['dateyear']; ?>| <strong>Author: </strong><? echo $rows['name']; ?></div>
          <p><? echo substr($mystring, 0, 100); ?>...</p>
          <a href="blog_post.php?id=<? echo $rows['id']; ?>" class="more">Read more</a><br />
          <div class="category">Category: <a href="#">Freebies</a>, <a href="#">Templates</a> | <a href="blog_post.php">244 comments</a></div>
        </div>
                <div class="cleaner"></div>
      </div>
        <?php
// close while loop 


}
Link to comment
https://forums.phpfreaks.com/topic/282642-most-efficient-code/#findComment-1452257
Share on other sites

Did you see my post above why your code wasn't working correctly

 

Your if statement is wrong

If ($count = 1)

that argument will always return true and thus the class never changes.

To compare if $count is equal to 1. You need to use the equals to comparison operator (==). The above line should read

If ($count == 1)
Link to comment
https://forums.phpfreaks.com/topic/282642-most-efficient-code/#findComment-1452258
Share on other sites

 

Your if statement is wrong

If ($count = 1)

that argument will always return true and thus the class never changes.

To compare if $count is equal to 1. You need to use the equals to comparison operator (==). The above line should read

If ($count == 1)

Right, forgot about that. There's no equivilent in ASP for ==. Thanks for all your help!

Link to comment
https://forums.phpfreaks.com/topic/282642-most-efficient-code/#findComment-1452259
Share on other sites

GOT IT! I had to alter your classes code a bit but I got it working:

 

// Retrieve data from database 
$sql="SELECT * FROM $tbl_name ORDER BY id DESC LIMIT 2";
$result=mysql_query($sql);


// Start looping rows in mysql database.
$classes = array('post_box', 'post_box post_box_last'); // define div classes here
$i = -1; // initiate counter to -1
while($rows=mysql_fetch_array($result)){
$divname = $classes[++$i]; // get the next class, ++$i will increment $i by 1
$mystring = $rows['message'];


?>
 <div class= "<? echo $divname; ?>"><img src="images/templatemo_image_01.jpg" alt="image" />
        <div class="post_box_right">
          <h2><? echo $rows['title']; ?></h2>
          <div class="post_meta"><strong>Date: </strong><strong><? echo $rows['dateday']; ?></strong> <? echo $rows['datemonth']; ?> <? echo $rows['dateyear']; ?>| <strong>Author: </strong><? echo $rows['name']; ?></div>
          <p><? echo substr($mystring, 0, 100); ?>...</p>
          <a href="blog_post.php?id=<? echo $rows['id']; ?>" class="more">Read more</a><br />
          <div class="category">Category: <a href="#">Freebies</a>, <a href="#">Templates</a> | <a href="blog_post.php">244 comments</a></div>
        </div>
                <div class="cleaner"></div>
      </div>
        <?php
// close while loop 


}

 

uhm.. right. A few pointers:

 

1) Always write <?php not just <?. The short notation may be turned off and then your code is displayed in the browser.

2) Always properly indent your code.

3) Separate HTML and PHP.

 

<?php

// PHP processing here

// include the HTML
include 'posts.view.php';
Inside posts.view.php you would write something like and use PHP's alternative syntax:

http://php.net/manual/en/control-structures.alternative-syntax.php

 

<?php foreach ($posts as $post): ?>
<div class="post <?php alternate('class1', 'class2'); ?>">
  .. $post here ..
</div>
<?php endforeach; // notice this tag here ?>
which makes for maintainable code. Edited by ignace
Link to comment
https://forums.phpfreaks.com/topic/282642-most-efficient-code/#findComment-1452285
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.