|
Posted by Jackson Linux on 03/29/05 15:19
As usual, Jochem, thanks for all those useful tips. They are much
appreciated.
Jack
On 29 Mar 2005, at 05:15, Jochem Maas wrote:
> Jackson Linux wrote:
>> Hello all,
>> I am a newbie trying to build a set of links to content in a db. I am
>> connecting with the db and seeing the proper number of rows. if I
>> echo out the values of $id and $sidebar I see that they take on the
>> id# and text of the last entry in the database. I'm trying to make
>> the script get each of the rows, until there are no more, and echo
>> out the info I need for each row. Please can someone tell me where
>> I'm going wrong?
>> (the variables spelling out the db connection information are in a
>> prepend file, and work.)
>
> I read that you already figured it out... thought I add a couple of
> general tips:
>
>> Thanks in advance,
>> Jack
>> <?php
>> $conn = mysql_connect($dbserver, $dbusername, $dbpassword);
>> if (!$conn) {
>
> if you don't intend to use the $conn var why initialize it?:
>
> mysql_connect($dbserver, $dbusername, $dbpassword) or die("Unable to
> connect to DB: " . mysql_error());
>
>> echo "Unable to connect to DB: " . mysql_error();
>> exit;
>> }
>> if (!mysql_select_db("$dbname")) {
>> echo "Unable to select mydbname: " . mysql_error();
>> exit;
>> }
>> $sql = "
>> SELECT *
>> FROM sidebar
>> ";
>> $sidebar = array();
>> $result = mysql_query($sql);
>> if (!empty($result)) {
>
> again if you are using $sql only in one place then there
> is no reason to not to do the following instead (given that
> the query itself is very short - i.e. legibility is not a problem):
>
> if ($result = mysql_query("SELECT * FROM sidebar")) {
>
>
>> while ($sidebar = mysql_fetch_assoc($result)) {
>> $id = $sidebar['sidebar_id'];
>> $linktext = $sidebar['headline'];
>
> sometimes it handy to initialize vars like the 2 above for
> readability...
> in this case you may consider that the expressions are very short and
> therefore
> you might want to skip creating the vars:
>
> $left_sidebar[] = "<li class='menu-item'>- <a class='sidebar-link'
> href='{$_SERVER['PHP_SELF']}?s={$sidebar['sidebar_id']}'
> title=\"{$sidebar['headline']}\">{$sidebar['headline']}</a></li>";
> >
>> /* Build sidebar.*/
>> $left_sidebar[] = "<li class='menu-item'>- <a
>> class='sidebar-link' href='{$_SERVER['PHP_SELF']}?s={$id}'
>> title=\"{$linktext}\">{$linktext}</a></li>";
>> }
>> }
>> else {}
>
> the preceding empty else statement if not required you can leave out
> the 'else {}' completely.
>
> have fun. :-)
>
>> mysql_free_result($result);
>> ?>
>> <html><body>
>> <ul><?php join("\n\n", $left_sidebar); ?></ul>
>> </body></html>
>
>
Navigation:
[Reply to this message]
|