Quote:
quote:Originally posted by bruce.benamran
you should always avoid writing down a statement like "select * from table".
Let's say your table is maincat(id, name, isPublished).
you should always state "select id, name, isPublished from maincat..."
this way, you prevent yourself ( or others ) from having to rewrite code whenever the database would change. you really should get used to it by now already.
|
True, true. In fact, I generally don't have SQL calls floating around in my code. When harping on style, I always tell people to wrap all their SQL calls in accessor functions that returns data. That way, if the database changes at all, you at most would need to modify the SQL in your accessor functions and the rest of the site would continue to work.
This code:
$query = "SELECT id, username, email FROM users";
$result = mysql_query($query);
if ($result !== FALSE)
{
while ($row = mysql_fetch_array($result))
{
echo "User $row[username] ($row[id]): $row[email]\n";
}
}
Would actually be something more like:
// user.db.inc
<?php
require_once('db.inc'); // generic db wrappers
// returns an array of user data
function get_users()
{
$query = "SELECT id, username, email FROM users";
$result = db_query($query); // generic call
if($result === FALSE)
return FALSE;
$users = array();
while($row = db_fetch_array($result))
{
$users[] = array('id' => $row['id'],
'username' => $row['username'],
'email' => $row['email']);
}
return $users;
}
?>
<?php // main script
require_once('user.db.inc');
$users = get_users();
foreach($users as $user)
{
echo "User {$user['username']} ({$user['id']}): {$user['email']}\n";
}
Hope it all makes sense...! For those with a lot of time on their hands, you can read a couple of the older mailing-list archives where I go into this concept in detail:
http://p2p.wrox.com/archive/beginnin...2002-04/25.asp
http://p2p.wrox.com/archive/beginnin...2002-09/40.asp
Take care,
Nik
http://www.bigaction.org/