Jump to content

could this be done with a little less code?


jimmi8

Recommended Posts

hi,

this is a real basic question. Basically i use this code to query my database:

[code]$sql ="SELECT * FROM ENTRIES ORDER BY date_submitted";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);

while($row) {
$title = $row['title'];
$body = $row['body'];
...[/code]

Now i use this when im selecting more than one column from the table but i dont know what to do if im only selecting one column. I dont think i need as much code to achieve a query that just selects one or two columns. Could anyone point me in the right direction?

Hi andy,

thanks for the reply.
sorry i knew i was being really vague when i wrote this post! If i had the query:

SELECT title from entries order by date_submitted

how can i get the title in to a variable? i know i need the sql_query part but do i really need the whole fetch array and while loop? Ive got it working with this code but do really need it all?

[code]$sql ="SELECT title from entries order by date_submitted";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);

while($row) {
$title = $row['title'];
[/code]
...
You need to combine these two lines one all of your examples or your "while" statement will never terminate:
[code]<?php
$row = mysql_fetch_array($result);
while($row) {
?>[/code]
should be written as
[code]<?php
while ($row = mysql_fetch_assoc($result)) {
?>[/code]

Ken
Instead of doing something like this:
[code=php:0]$body = $row['body'];
echo $body;
[/code]


Just do this:
[code=php:0]echo $row['body'];[/code]



And here is a shortened version of everything:
[code=php:0]$result = mysql_query("SELECT title from entries order by date_submitted");
while ($row = mysql_fetch_assoc($result)) echo "Title: " . $row['title'] . "<br />";
[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.