Fri 18 Apr 2008
A Little Bit of SQL
Posted by Charles Clarkson under PHP, Programming
I ran across this piece of code in a program I am updating. The original author is a great game designer, but only a fair programmer. He also seems to have very limited experience with SQL.
-
if ( $grab == 'Ammo' ) {
-
-
if ( $num_rows != 0 ) {
-
if ( $fetch->location == $location ) {
-
mysql_query("UPDATE BF SET owner='$username', profit='0' WHERE country='$fetch->location' LIMIT 1");
-
$this->content .= "You got the Bullet Factory!";
-
}
-
}
-
}
When writing database applications, you need to be as good at writing queries as you are at writing code. Here's a rewrite:
-
if ( $grab == 'Ammo' ) {
-
-
if ( $fetch->location == $location ) {
-
-
"UPDATE BF SET owner='%s', profit='0' WHERE owner='None' AND country='%s'",
-
);
-
-
$this->content .= "You got the Bullet Factory!";
-
}
-
}
-
}
Now I use just one query. If the update is unsuccessful then no rows will be affected and I won't update the content. Whenever you do a query, check some data and then do an update, look for ways to have the database do the variable checking.
In this case, the author was comparing $fetch->location and $location, but first he was checking for a record where the country field matched $fetch->location. I took the innermost test and made it the outermost test. Now, $fetch->location, the country where the user is located and $location, the location of the Bullet Factory are compared first.
That test does not involve a database hit. I only hit the database if the locations match. Then I only hit it once. If no rows were updated, mysql_affected_rows() returns 0 and content is not appended.
Eventually, I will be writing an object for accessing the BF (Bullet Factory) table. Then this will be a method of that object. It might look something like this.
-
public function buyFactory($user_location, $username) {
-
-
if ( $this->location != $user_location ) {
-
return 0;
-
}
-
-
"UPDATE BF SET owner='%s', profit='0' WHERE owner='None' AND country='%s'",
-
);
-
-
}
No Responses to “ A Little Bit of SQL ”
Leave a Reply
You must be logged in to post a comment.