When things are urgent, we all go with the spaghetti code. When they are not, well, some of us still do. Here comes the bad news: We shouldn’t.

If it’s about inserting records to database, most of the old tutorials go with the mysql extension functions such as mysql_connect() and/or mysql_query() which actually have been sitting at the center of the security issues, for example the most popular one: SQL injection.

PHP’s got a lot more clear recently. As of PHP version 5.5.0, using good old mysql extension functions cause a warning that the methods are now deprecated and the one simple should use mysqli functions or PDO instead. It was a recommendation, now it became a must.

In this short tutorial series, I will try to explain how I use PDO in my OOP classes and also will share codes of a small example.

After the 5 tutorials, you’ll be able to:

Insert single row

Do rollback in failure cases

Insert multiple rows

Update multiple rows

Select rows

All with PDO.

1. Inserting Single Row

There are some ways of executing SQL queries with PDO. If you have your SQL statement prepared with params bound to (not recommended), you can use PDO’s exec() function. If you want to use placeholders in your query (PDO uses either ? or :paramName) and then bind parameters (recommended), you can use PDO’s prepare(), bindParam() and execute() methods (in this order). I’ll go with the second.

Since we are going with OOP, it’s a good idea to keep the basic PDO connection code in a class like Connection.

Connection class contains a WOUF (write-once-use-forever) code so there's no need to memorise it. I know I didn't. (Btw, I just made up WOUF)

In our classes, we’ll store a private variable for database connections which is an instance of the Connection class. Line 7 and 8 contains some adjustments for PDO where you can find details here. I’d recommend keeping them like this but you can find discussions on Stack Overflow and make your own decision according to your case.

Now that our connection class is ready, we can write a record function to our custom object.

In this tutorial, I have an object named Object (TY, Captain Obvious) which has two attributes: id and name. They are stored in a database table named... "table". (I like to keep things simple.)

You can find the SQL query to create DB and table and other PHP codes in the repo that I'm going to share at the end of the tutorial.

First of all, we need to create a Connection instance object in our class. Best place to create this instance variable is our class’ __constructor method.

As you can see in line 4, our INSERT statement is pretty much the same with an SQL command but it has a placeholder. If I was adding two columns, I’d keep adding placeholders like (?,?). Each one is represented by index (starting from 1).

One of the coolest thing about the PDO is that it handles value types by itself. If we were to use SQL queries directly, we would need to surround our strings with quotation marks. With PDO, all we need to do is just bind the string directly and it will put those marks.

After creating the formatted SQL string, I create a variable to store the PDO statement, I also prepare it with prepare() function to bind parameters in the next step. (line 6)

Now I’m ready to bind parameters to this PDO statement. Since the index of the “name” placeholder is 1, I will bind “name” value to param 1. (line 8)

That’s it. Now we can run this query with PDO’s execute() function which returns BOOLEAN and if it is true, set our object’s id to last insert ID.

That’s it for the first tutorial. Now you can insert rows one by one (yet) to database with PDO. You can find the code of this tutorial in the Github repo.

The next tutorial will be about rolling back changes which is ultimately important in such cases that the operation might be broken at some point and some of the records are inserted/updated, the rest are not. PDO can roll back the changes from a given point and it will.

This is an old script that I used to use for sending notifications. I don’t remember the source, on the other hand, it has been modified a couple of times already.

Even though I could manage to send notifications with this script, the Apple server was rejecting the connection after the amount reaches more than 50. It was usually getting cut off around 70. So it needs to get some management for not sending in a loop, like threading or whatever.

FeedBack is important. Usually, end-users struggle to clarify their problems. And you might be unreachable for a phone call or remote connection.

That causes a huge need of visualization. First solution that appears in mind is to capture the current screen of user.

However, when I tried to implement that, it wasn’t so easy as I expected. Some old ways offer ActiveX but it seems too outdated. Since there’s a bridge needed between client side and server, JS libraries are the best way.

There’s a great library, html2canvas. It is told to be reverse-engineered version of Google Plus’ way of taking screenshots.

When I first discovered this library, it took me a while to use for simplest implementation. I just wanted to visualize a div element. However, there was no single page to tell the whole path to follow, thus I had to combine various sources.

Here’s how you can easily use for taking a screenshot of a div:

1- Import libraries
There are 3 libraries to import:

jquery.js

html2canvas.js

jquery.plugin.html2canvas.js

You can download html2canvas and html2canvas jQuery plugin from this link.
Note: The source link contains html2canvas v0.40. I recommend you to check for a newer version and use it instead from official html2canvas site.

I have used jquery.min.js v1.7.1 but you can try other versions. For this jQuery library, use this link.
Here’s first lines of code:

3- Create a button and a hidden form
This part is important. In order to save the image to server, we need to pass captured image data with a form field.
In 4th step, you’ll see JavaScript code that writes the image data to hidden field and posts the form.

* This tutorial uses html2canvas v0.4.0 – 30.1.2013. It has a new release, v0.4.1 – 7.9.2013, can be downloaded from here. Though avaliability of newer versions haven’t been tested with the code above.

* Some people have declared that they had issues with checkbox/radiobutton states on the captured image. Stu has shared his code to capture these elements with their states. I haven’t tried by myself but people who face problem about this may get some opinion from his comment.

When we work with date and/or time values in MySQL, it’s always easy to use built-in MySQL functions such as NOW(), DATE_ADD(), TIMESTAMP() etc… Now imagine you have to pass date/time values to MySQL from PHP variables. First time I tried that, it didn’t work out so easy for me.

Yes, if you simply take one column value and use it again, you have no problem. But here’s an example that you take date and time from MySQL column, add 1 seconds to that value and use it in query again:

//Here's just stuff in order to get a datetime value from MySQL DB.
$query = "SELECT TOP 1 `date` FROM `table`";
$result = mysql_query($query, $db_link);
$date_time_val = "";
if ($result) {
while($row = mysql_fetch_assoc($result)) {
//Here we get the value.
$date_time_val = $row["date"];
}
}
//Now we add one second to this value and use it again.
//First, use it for generating a DateTime variable from PHP library.
$time = new DateTime($date_time_val);
//If you need current time in PHP, you can use this:
//$time = new DateTime(date("Y-m-d H:i:s"));
//Add one second,
$time->modify("+1 seconds");
//You can not use it as it is
//You need to convert to a string in MySQL datetime format.
$time_string = $time->format("Y-m-d H:i:s");
//Now you're free to use in your query
$query_new = "SELECT * FROM `table` WHERE `date` = '".$time_string."' ";