Complete Course of PHP - PDO
Complete Course of PHP - PDO
Class 01 - Introduction
Today we will start our exclusive PDO (PHP Data Objects) course.
PDO has been dominating the market in the world of PHP programmers, and for this reason, it cannot
to fall behind, correct?
In this course we will learn how to make a CRUD (create | read | update | delete).
delete) complete with PDO, and more. We will also make comparisons with the primitive mode of
PHP, this way we will all address the differences between both.
What is the advantage of using PDO?
Imagine that you created a system using the primitive mode of PHP, and the type of database
the MYSQL was used.
After a long time, your client tells you that the database will now be of the ORACLE type.
Particularly, you would have to change several pages, right?
With PDO it's different, as it works with database drivers, that is, for
solve your client's problem using PDO, you just need to modify the file of
connection to the database, informing the desired driver.
With PDO, we can feel more secure regarding vulnerabilities, as with the use of
By doing so, we can avoid SQL Injection situations.
Are you enjoying it? Keep following the course, as this is just the beginning.
Would you like to buy an online course with us, but do not know our virtual campus? Visit:
http://www.escolacompleta.com/campus
Continuation… let's go to a quick introduction to PDO.
Introduction
PHP Data Objects (PDO) defines a lightweight interface in PHP. Each database driver that
implementing the PDO interface can expose specific resource data. Note that you cannot
execute any database functions using the PDO extension, by itself, you must use a
specific PDO driver database to access a database server.
PDO provides an abstract data access, which means that, regardless of which database
The data you are using, you use the same functions to issue queries and retrieve data (CRUD).
Lesson 02 - Connection with PDO
In this lesson, we will learn how to create a connection to the database using PDO, remembering
we will make comparisons between the primitive mode and PDO mode.
In fact, a primitive connection without using PDO would look like the example below:
<?php
localhost
root
pass
test_bank
if($connection){
mysql_select_db($bd) OR DIE ("Error selecting database:
.mysql_error());
?>
In a certain way, the primitive mode is less complex and faster to develop, however
there are disadvantages.
One of them is vulnerability;
Another issue is the famous spaghetti code;
And one more is the long time issue for changes in types of databases.
See now how to create your database connection using PDO, based on the example
above.
<?php
localhost
root
pass
test_bank
What does PDO ask for in the connection?
ex: PDO($dsn,$user,$pass);
but what is dsn?
database_type:host='your_host';dbname='your_database_name';
*/
mysql:host=
try{
return $connection;
}catch(PDOException $error){
?>
setAttribute – Defines an attribute in the declaration. To see the list of attributesclick here.
PDO::ATTR_ERRMODE - error report.
PDO::ERRMODE_EXCEPTION - Child attribute of the attribute ATTR_ERRMODE, this represents
an error generated by PDO.
Understanding the attributes
When you define an attribute in PDO, they have default values and unique children.
The syntax for using it works as follows:
setAttribute(attribute, attribute_child);
For this, see the list below, which sets the attributes and their outside children.
1. PDO::ATTR_CASE – column names force to a specific case.
oChildren of the attribute PDO::ATTR_CASE
o PDO::CASE_LOWER - Forces column names to lowercase.
oPDO::CASE_NATURAL - keep column names as returned by
database driver.
oPDO::CASE_UPPER - column names force to uppercase.
2. PDO::ATTR_ERRMODE – error reporting.
oChildren of the attribute PDO::ATTR_ERRMODE
o PDO::ERRMODE_SILENT - Just define error codes.
oPDO::ERRMODE_WARNING - Triggers a warning E_WARNING.
oPDO::ERRMODE_EXCEPTION - Throw exceptions.
3. PDO::ATTR_ORACLE_NULLS – (available with all drivers, and not just with the
Oracle): Conversion of null and empty strings.
oChildren of the attribute PDO::ATTR_ORACLE_NULLS
oPDO::NULL_NATURAL – No conversion.
oPDO::NULL_EMPTY_STRING - empty string is converted to NULL.
oPDO::NULL_TO_STRING – NULL is converted to an empty string.
There are many attributes and their counterparts, for this learn more on the official PHP website.clicking here.
Now that we know more about the attributes, we should learn about this line:
catch(PDOException $error){
What is PDOException?
It represents an error generated by PDO.
In this way, we are assigning o error generated by PDO à variable $error.
In this way, we should only call the error message using the variable $error.
Note that to display the generated error message, I used:
$error->getMessage();
while($linha_alunos = mysql_fetch_array($query)){
echo $linha_alunos['student_name'].'<br />';
?>
Simple, right?
Remember that we included the connection file from the last class.
If you did not attend the last classclick here.
Now that you know how data selection works using the primitive mode, we will now
do the same using PDO.
First, we will make a regular selection without using conditions (WHERE).
COMMON SELECTION WITH PDO
<?php
include_once("connection.php");
function list_students() {
try{
return $listar->fetchAll(PDO::FETCH_ASSOC);
else
catch(PDOException $error){
Error listing students:
}
}
list_students();
foreach($students as $student):
echo $student['student_name']."<br />";
endforeach;
?>
You could also use FETCH_OBJ instead of FETCH_ASSOC, however our foreach
it would be like this:
foreach($students as $student):
echo $student->student_name . "<br />";
endforeach;
function list_students() {
try{
return $listar->fetchAll(PDO::FETCH_OBJ);
}
}catch(PDOException $error){
Error listing students:
}
}
$students = list_students();
foreach($students as $student):
echo $student->student_name."<br />";
endforeach;
?>
<?php
include_once("connection.php"); // inclusion of the connection file from the class
past
function list_students_with_condition() {
try{
return $listar->fetch(PDO::FETCH_ASSOC);
else
}catch(PDOException $error){
Error listing students:
}
}
$students = list_students_with_condition();
foreach($students as $student):
echo $student['student_name'] . "<br />";
endforeach;
?>
Note that in the example above, I did not use fetchAll, but rather just fetch, because I am
wanting to return just a specific value stated in my 'condition'.
Remembering also that instead of using bindValue, we can also use bindParam, which will
return the same value, however you can also specify the type of the parameter (type)
the past and the size (length).
Example:
$listar->bindParam(":idade", $idade, PDO::PARAM_INT, 3);
In this way, I am specifying that the value passed is of the integer type (PARAM_INT), and the size is
3. That is, there is no person older than 3 digits, correct? (Please do not include the
mummies in this roll).
And for string types? How would it be?
In the above example, I am informing that the parameter student_name is of the type
string(PARAM_STR) and the maximum length is 255 characters.
If you want to know more about bindParam'sclick here
Now, I will show a situation that many students have doubts about. The famous question mark.
When we pass parameters, we can also use the question mark, and right after it
position of the index that we intend to assign the current value.
Example:
<?php
include_once("connection.php");
function list_students_with_condition() {
try{
$idade = 15;
$listar = $connection->prepare("SELECT * FROM students WHERE age = ?");
$listar->bindValue(1,$age);
$listar->execute();
return $listar->fetch(PDO::FETCH_ASSOC);
else
}catch(PDOException $error){
Error listing students:
}
}
list_students_with_condition();
foreach($students as $student):
echo $student['student_name'] . "<br />";
endforeach;
?>
Note that the modified lines are the ones listed below:
$listar = $conexao->prepare("SELECT * FROM students WHERE age = ?");
However, the question remains. What if I wanted to pass two parameters in the condition? How
would it stay?
See the example below:
<?php
include_once("connection.php");
function list_students_with_condition() {
try{
$idade = 15;
Alberto
$listar->bindValue(2,$lastName);
$listar->execute();
return $listar->fetch(PDO::FETCH_ASSOC);
else
}catch(PDOException $error){
Error listing students:
}
}
students = list_students_with_condition();
foreach($students as $student):
echo $student['student_name'] . "<br />";
endforeach;
?>
Carlos
Alberto
mysql_query($sql);
if($query){
Student successfully registered!
else
Error registering student.
}
?>
<?php
include_once("connection.php");
Carlos
Alberto
try{
$cadastrar->bindValue(":name", $name);
$cadastrar->bindValue(":last_name", $last_name);
$cadastrar->execute;
if($cadastrar->rowCount() > 0){
}catch(PDOException $error){
Error registering student:
}
?>
Remembering that with the use of PDO, I did not need to put the parameter in quotes.
simple, as it was used in primitive mode.
See:
$cadastrar = $conexao->prepare("INSERT INTO students (first_name,last_name)");
VALUES (:first_name,:last_name);
else
Error registering student.
The question remains: But does rowCount not only work for selecting data?
Answer: No! The rowCount, in this case, is functioning like the old mysql_affected_rows, which
returns the number of affected rows.
In our case, 1 registration was successfully executed, resulting in the message 'Student
successfully registered!
Remember that we could also register using the question marks.
Example:
<?php
include_once("connection.php");
Carlos
Alberto
try{
$cadastrar->bindValue(1,$name);
$cadastrar->bindValue(2,$lastName);
$cadastrar->execute;
if($cadastrar->rowCount() > 0){
catch(PDOException $error){
Error registering student:
}
?>
<?php
include_once("connection.php");
Carlos
Alberto
$data = array(
$name
$sobrenome
);
try{
$register = $connection->prepare("INSERT INTO students (first_name, last_name)")
VALUES (:name,:surname)
foreach($data as $index => $value):
$cadastrar->bindValue(:$index, $value);
endforeach;
$cadastrar->execute;
if($cadastrar->rowCount() > 0) {
}catch(PDOException $error){
Error registering student:
}
?>
<?php
include_once("connection.php");
Carlos
Alberto
array(
$name
$lastname
);
try{
$cadastrar = $conexao->prepare("INSERT INTO students (first_name, last_name)")
VALUES (?,?)
foreach($data as $index => $value):
$cadastrar->bindValue($index, $value);
endforeach;
$cadastrar->execute;
if($cadastrar->rowCount() > 0){
}catch(PDOException $error){
Error registering student:
}
?>
It's simple, easy, and safe to use PDO to perform our INSERT, right?
$matricula = $_GET['matricula'];
DELETE * FROM students WHERE registration = '$registration'
mysql_query($sql);
if($query){
Student deleted successfully!
else
Could not delete the student.
}
?>
Do you remember how the primitive mode of PHP was used? Now, see the same using PDO.
DELETING USING PDO
<?php
include_once("connection.php");
try{
matricula = $_GET['matricula'];
$delete->execute();
if($deletar->rowCount() > 0){
Student deleted successfully!
else
Could not delete the student.
}
}catch(PDOException $error){
?>
try{
$matricula = $_GET['matricula'];
$deletar->execute();
else
It was not possible to delete the student.
}
}catch(PDOException $error){
?>
$matricula = $_POST['matricula'];
$name = $_POST['name'];
$lastName = $_POST['lastName'];
$lastName
WHERE
$matricula
";
$query = mysql_query($sql);
if($query){
Student updated successfully!
else
Error updating student.
}
?>
<?php
include_once("connection.php");/*Includes database connection file*/
$matricula = $_POST['matricula'];
$name = $_POST['name'];
$surname = $_POST['surname'];
last name
WHERE
:matricula
");
$atualizar->bindValue(':nome', $nome);
$atualizar->bindValue(":sobrenome", $sobrenome);
$atualizar->bindValue(":matricula", $matricula);
$atualizar->execute;
?>
<?php
include_once("connection.php");/*Includes database connection file*/
$matricula = $_POST['matricula'];
_POST['nome']
$surname = $_POST['surname'];
surname = ?
WHERE
enrollment = ?
$atualizar->bindValue(1,$name);
$atualizar->bindValue(2, $lastName);
$atualizar->bindValue(3, $matricula);
$updater->execute;
else
Error updating student.
}
?>
Question: Could we use arrays to make such an update? It would be great for making multiple.
data updates correct?
Yes, we can use arrays. And, yes, it would be great for multiple data manipulation.
EXAMPLE USING ARRAY – WITHOUT USING QUESTION MARKS.
<?php
include_once("connection.php");/*Includes database connection file*/
$matricula = $_POST['matricula'];
$name = $_POST['name'];
$lastName = $_POST['lastName'];
array(
$nome
$sobrenome
$matricula
);
:sobrenome
WHERE
:matricula
");
endforeach;
$atualizar->execute;
?>
$matricula = $_POST['matricula'];
$name = $_POST['name'];
$surname = $_POST['surname'];
array(
$name
2 => $lastname,
$matricula
);
last name = ?
WHERE
enrollment = ?
foreach($dados as $index => $value):
$atualizar->bindValue($index,$value);
endforeach;
$updater->execute;
else
Error updating student.
}
?>