Here is something you (or are about to) know: Inserting a row in a SQL database table...
Basically, you every time need to mysql_connect, mysql_select_db, generate sql, mysql_query. But the data you are using is also related to each other. The generated SQL is related to the concrete mysql server/table.
So you could write a class that holds all that data together.
Code: Select all
class Table
{
// data that is unique for each instance
var $dbhost;
var $dbuser;
var $dbpass;
var $dbname;
var $table;
function insert($row)
{
// try to connect to the database
if (!$this->connect()) return false;
// build the query
$sql1 = "INSERT INTO " . $this->table . " (";
$sql2 = ") VALUES (";
foreach($row as $column => $value)
{
$sql1 .= "`$column`, ";
$sql2 .= "'" . mysql_real_escape_string($value) . "', ";
}
$sql1 = rtrim(", ");
$sql2 = rtrim(", ");
$query = $sql1 . $sql2 . ")";
// try to execute the query
if (!mysql_query($query))
{
return false;
}
// might want to retrieve the last_insert_id etc..
// everything went well
return true;
}
}
And now you have a project where you need to insert players...
Code: Select all
$table = new Table('localhost', 'user', 'pass', 'dbname');
$table->setTable('players');
$row = array('playername' => 'timvw', 'skills' => 1, 'email' => 'timvw@invalid.org');
$table->insert($row);
Or another project where you need to insert purchases
Code: Select all
$table = new Table('example.org', 'user', 'pass', 'dbname');
$table->setTable('purchases');
$row = array('product_id' => 'xqsdfa', 'qty' => 100, 'price' => '1200');
$table->insert($row);
It does not only makes life easier, because you don't have to keep the variables together, it also allows you to reuse code
Imagine the case where you would need to insert players and purchases at the same time.. You have to make sure the right dbhost, dbuser, dbpass, dbname are used for the generated SQL. This is an example where OOP can make things easier. (Although it's also very common to put them in a "struct" or "hash" and then have a function insert($dbdata, $row))
Probably, you want also to test if things are really doing what you expect from them, and then you will get fed up with always writing echo statements and commenting them out afterwards... And when you change something, you have to restart everyting... So you want to stop repeating that too...
In that case i suggest you have a look at
http://simpletest.sf.net which allows you to write unittests. Actually, it's another example of classes that you can (re)use to do common stuff (testing if your code does what it is supposed to do)