Posts: 1,832
Location: Somewhere else entirely
|
PHP has these things built in, but you need to know the right SQL query to send to the database to get back what you want.To get one row out (rows are essentially a 'record', columns or fields are things like ID, title and so on.) you need to have some way of identifying that row, usually with the value of that rows ID column.
PHP Code:
$id =6 // the row you are looking for
$result = mysql_query("SELECT * FROM yourtable WHERE ID = $id");
$row = mysql_fetch_assoc($result);
foreach($row as $fieldname => $value) {
echo $fieldname . " has value ".$value."<br />";
}
Here, the mysql_query function sends the sql query you give it out to the database. What comes back is $result, something called a 'resource identifier'. All this means in this case is that $result is a piece of a dtabase table (the bit returned by your query). You can't simply echo $result, because it is stored in some special way. There are some more functions to get the values, and here I use mysql_fetch_assoc to get an array from $result. This array will be laid out as follows:
Code:
Array(
'ID' => 6,
'title' => 'Mr'
'age' => 34
'number_of_legs' => 2
)
The foreach loop just takes this array and prints it out in a nice way.
To get a whole column back, say to print out a list of first names, you need slightly different sql, and a more clever way of getting the data out of $result.
PHP Code:
$result = mysql_query("SELECT first_name FROM yourtable");
echo "List of first names:";
while($row = mysql_fetch_assoc($result)) {
echo $row['first_name'] . "<br />";
}
If the sql has no WHERE clause, it gives you all the records. In this query we specify we only want the first_name column. A while loop is used to get the results out this time. This time $result has multiple rows, and we need to do each one in sequence. Each time you call mysql_fetch_assoc on the same resource identifier, it moves on to the next row automatically. If there are no more rows left, mysql_fetch_assoc returns false and the while loop ends.
__________________
UPDATE 0beron SET talkupation = talkupation + lots WHERE post = 'helpful';
Please login or register to view this content. Registration is FREE (aka MSN handwriting for forums)
Last edited by 0beron; 09-20-2005 at 01:35 PM..
|