November 18, 2008

Prado PHP Framework HOW TO 4 - MYSQL Everything (Almost)

In order to connect to a mysql server within your Prado application, first you need to define your Connection String in your application.xml file;
<module id="dbconnection" class="System.Data.TDataSourceConfig">
<database ConnectionString="mysql:host=YOURHOST;dbname=DBTOCONNECT" Username="YOURUSERNAME" Password="YOURPASSWORD" />
</module>


Then when you want to connect to your mysql server within one of your php file's, you just use this connection string;
$db_connection = $this->Application->Modules['dbconnection']->Database;
$db_connection->Active = true;


Then you are ready to go, first we preapare our query;
$sql_query = "";
$command = $connection->createCommand($sql);


Then run it as what it is;
------For select queries
$db_records = $command->query();

------For insert, update, delete queries
$command->execute();

After select queries, you can get the results by;
foreach($db_records as $key){
$key["row_name"];
}


And also if you are using InnoDB as your storage engine, you can use transactions and rollback from the states that throws exceptions. It's possible for MyISAM too but you must write down your own implementation that follows the running queries and when the time comes rollback them. Because when i searched for if MyISAM'll support transactions, i found that the programmers won't think anything about it because they developed them as they are, for higher speed and light applications MyISAM and for secured business applications InnoDB. If you want to look more for differences, you can look here. And here is how you can use transactions within your PHP code in Prado;

First we enclose our sql queries within try-catch block;
try{
}catch(Exception $ex){
}


Then after creating our connection object, we start transaction on it;
$transaction = $db_connection->beginTransaction();

At the end if some of our code fails and throws an exception, we rollback the operations in our catch block;
$transaction->rollBack();

And of course to close the connection;
$db_connection->Active = false;

Then our code now looks like;
$db_connection = $this->Application->Modules['dbconnection']->Database;
$db_connection->Active = true;
try{
$transaction = $db_connection->beginTransaction();
$sql_query = "";
$command = $connection->createCommand($sql);
$command->execute();
}catch(Exception $ex){
$transaction->rollBack();
}
$db_connection->Active = false;

Also you can enclose these code to another try catch block. It is good to see an Error Message instead of a whole Php-Prado Exception for our user's sake i think :)

No comments: