4
\$\begingroup\$

I use the following code <div><?php echo $obj->text; ?></div> in while loop.

Is this the best way?

Is there a better way, either to optimize or replace this code?

<?php
    $akhbarkotah1 = $conn->prepare("SELECT text,time FROM small WHERE active='0' ORDER BY time DESC LIMIT 10");
    $akhbarkotah1->execute();
    while($obj = $akhbarkotah1->fetch(PDO::FETCH_OBJ)){

?>
<div><?php echo $obj->text; ?></div>
<?php
    }
?>
\$\endgroup\$
1
  • \$\begingroup\$ Does this code work? \$\endgroup\$
    – Malachi
    Mar 3, 2014 at 18:36

1 Answer 1

6
\$\begingroup\$

It looks like you don't really need to exit out of the PHP tag on this one.

<?php
    $akhbarkotah1 = $conn->prepare("SELECT text,time FROM small WHERE active='0' ORDER BY time DESC LIMIT 10");
    $akhbarkotah1->execute();
    while($obj = $akhbarkotah1->fetch(PDO::FETCH_OBJ)){
        echo "<div>" . $obj->text . "</div>";
    }
?>

This simplifies the code and shortens it. I think that I have the Syntax Correct. I am rather new to PHP myself but I am pretty sure that this will work exactly the same.

If you leave your code the other way you should indent the HTML to match what is inside the PHP since it is really inside the PHP (kind of/sort of) like this

<?php
    $akhbarkotah1 = $conn->prepare("SELECT text,time FROM small WHERE active='0' ORDER BY time DESC LIMIT 10");
    $akhbarkotah1->execute();
    while($obj = $akhbarkotah1->fetch(PDO::FETCH_OBJ)){
?>
        <div><?php echo $obj->text; ?></div>
<?php
    }
?>

I personally don't like the way that this looks though.

\$\endgroup\$
7
  • \$\begingroup\$ thanks , but i have more than a <div> tag html code about 10 line in whaile loop and i dont write here and my main question is for about replace a code for while, for example foreach or dont using loop and ... \$\endgroup\$ Mar 3, 2014 at 15:13
  • 2
    \$\begingroup\$ then you probably want to post the full code. because what you have here can be simplified to what I showed you. you can put that same echo line that I used into the while statement. \$\endgroup\$
    – Malachi
    Mar 3, 2014 at 15:16
  • \$\begingroup\$ my problem is using another code replace while($obj = $akhbarkotah1->fetch(PDO::FETCH_OBJ)) \$\endgroup\$ Mar 3, 2014 at 15:29
  • \$\begingroup\$ what do you mean "code replace"? \$\endgroup\$
    – Malachi
    Mar 3, 2014 at 16:19
  • \$\begingroup\$ i want save array in variable and call with $var[0] \$\endgroup\$ Mar 3, 2014 at 16:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.