Professional Documents
Culture Documents
Quando falamos em sistemas web nos dias de hoje é impossível não pensar em um cliente
consumindo dados salvos em uma base, por tanto é imprescindível que um desenvolvedor tenha
o conhecimento para tratar os dados utilizados pelo cliente através da programação.
Para entendermos como funciona o tratamento dos dados, vamos criar um cadastro de livros,
onde o cliente poderá: ver os livros cadastrados, editar e inserir novos livros no banco. O famoso
CRUD (create/read/update/delete).
Seguindo uma lógica de implementação, iremos primeirmamente partir pela criação do banco de
dados.
use biblioteca;
Executando o código acima, criamos nosso banco denominado “biblioteca” e nossa tabela
denominada “livro”, na qual vamos armazenar os dados dos livros.
Para que possamos iniciar a abstração dos dados, vamos criar uma classe denominada Conexao,
onde definimos todas as transações que serão feitas e os dados para acesso ao servidor MySQL.
//Variáveis de acesso Db
1
define('DB_SERVER', 'localhost');
define('DB_NAME', 'biblioteca');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
class Conexao {
$this->db = mysql_select_db($database,$this->conn);
...
No código acima, temos a definição dos parâmetros de acesso à base de dados, a criação da
classe “Conexao” e seu respectivo construtor. No construtor, abrimos a conexão com a função do
MySQL, mysql_connect, passando o servidor, nome do usuário e a senha como parâmetro. Em
seguida, selecionamos a tabela que iremos trabalhar usando a função mysql_select_db, passando
como parâmetro o nome da tabela e a conexão atual.
Dando início ao nosso CRUD, vamos criar nossa função insert no arquivo “conexao.php”:
/**
2
*/
$keys[] = $key;
return $this->executar($sql);
A função de “insert” recebe como parâmetro o nome da tabela e os dados que serão inseridos na
mesma na forma de array. O foreach separa o nome da coluna da tabela na variável “Keys” e os
seus respectivos valores em “insertValues”, logo após usando o comando implode, inserimos as
virgulas entre os dados.
Vamos testar se o que fizemos até agora está funcionando? Para isso vamos criar um arquivo
“index.php” contendo o seguinte código:
<!DOCTYPE html>
<html>
<head>
<title></title>
3
</head>
<body>
<?php
require_once 'conexao.php';
if($insert == true){
echo 'inserido';
?>
</body>
</html>
Após criarmos o arquivo index.php, colocar na pasta do seu servidor e acessar através do
browser, deverá aparecer a mensagem “inserido”. Acessando o banco de dados podemos conferir
que as informações estão realmente lá!
Nosso próximo passo é alterar a informação que acabamos de inserir. Para tal, vamos criar a
função update dentro do arquivo “conexao.php”
/**
4
* @param string $colunaPrimary nome da coluna chave primaria
*/
return $this->executar($sql);
A função de update é muito parecida com a de insert, a diferença é que na formação da query
passamos o id do registro a ser alterado, assim como a coluna da chave primária.
Agora vamos testar? O procedimento vai ser idêntico ao que fizemos para o insert. Agora vamos
criar um arquivo chamado update.php e inserir o seguinte código:
<!DOCTYPE html>
<html>
<head>
5
<title></title>
</head>
<body>
<?php
require_once 'conexao.php';
if($insert == true){
echo 'alterado';
?>
</body>
</html>
Para executar, o mesmo procedimento, no browser acesse o nome do arquivo e se ocorrer tudo
bem deverá aparecer a mensagem “alterado”. Você pode modificar os dados dentro do array e
verificar no banco as alterações sendo realizadas.
Avançando com nosso CRUD, vamos visualizar quais registros temos na nossa base através da
função “select”, vamos abstrair os dados do banco e visualizá-los em tela.
/**
6
* @param string $tabela Description
*/
$result = $this->executar($sql);
return mysql_fetch_assoc($result);
Função bem simples para a seleção dos dados. São passados apenas dois parâmetros: o nome da
tabela e as colunas a serem selecionadas.
Para testar, vamos criar um arquivo chamado select.php e alimentá-lo com o seguinte código
/**
*/
$result = $this->executar($sql);
7
$return[] = $row;
return $return;
Uma simples classe que varre os registros na nossa base de dados. O laço While vai em todas as
linhas da tabela e salva seus registros em um array. Para visualizar os dados da sua tabela vamos
criar um arquivo “select.php” e inserir o código abaixo:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
require_once 'conexao.php';
$select = $conexao->select('livro');
echo '================'.'</br>';
8
echo 'Codigo = '.$livro['cod_livro'].'</br>';
echo '================'.'</br>';
?>
</body>
</html>
Para testar, acesse o arquivo através do browser e se ocorrer tudo bem você verá seus registros na
tela.
Como vimos, é bastante simples persistir e acessar dados em uma base MySQL utilizando PHP.
Então, finalizamos aqui este breve artigo. Até a próxima.
The other benefit of PDO is error handling feature using exceptions. PDO functions can be written using try/catch block. The exceptions are
logged in a log file and a user friendly error message is displayed on screen.
PDO also supports prepared statements and stored procedures. The major benefit of prepared statements is that you just need to prepare a
query once and then it can be run multiple times with the same or different parameters. The other benefit is that prepared statements are
quoted automatically by the driver. Hence, preventing SQL injection attack to the system/application.
In the past, I had written an article on creating a Simple CRUD System using PHP & MySQL. That article/tutorial uses MySQLi extension
driver for accessing the database. In this article, we will be creating the same system but using PDO extension driver to access database.
Here is a step-by-step guide on creating a CRUD system using PHP & MySQL with PDO:
First of all, we will create a new MySQL database. Let us name the database as ‘test‘.
use test;
);
9
Now, we will create a config.php file which contains database connection code. This code connects to the MySQL database. This file is
included in all PHP pages where database connection is necessary.
config.php
In below code, the database host name is localhost where username=root and password=root. The database test has been
selected.
<?php
1
2 $databaseHost = 'localhost';
3 $databaseName = 'test';
4 $databaseUsername = 'root';
5 $databasePassword = 'root';
6
7 try {
8 // http://php.net/manual/en/pdo.connections.php
9 $dbConn = new PDO("mysql:host={$databaseHost};dbname={$databaseName}", $databaseUsername,
10 $databasePassword);
11
12 $dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Setting Error Mode as
13 Exception
14 // More on setAttribute: http://php.net/manual/en/pdo.setattribute.php
15 } catch(PDOException $e) {
16 echo $e->getMessage();
17 }
18
?>
To add data into database, we need an html form.
add.html
1 <html>
2 <head>
3 <title>Add Data</title>
4 </head>
5
6 <body>
7 <a href="index.php">Home</a>
8 <br/><br/>
9
10 <form action="add.php" method="post" name="form1">
11 <table width="25%" border="0">
12 <tr>
13 <td>Name</td>
14 <td><input type="text" name="name"></td>
15 </tr>
16 <tr>
17 <td>Age</td>
18 <td><input type="text" name="age"></td>
19 </tr>
20 <tr>
21 <td>Email</td>
22 <td><input type="text" name="email"></td>
23 </tr>
24 <tr>
25 <td></td>
26 <td><input type="submit" name="Submit" value="Add"></td>
27 </tr>
28 </table>
29 </form>
30 </body>
31 </html>
Form action on add.html is add.php. It means that the submitted form data will go to add.php. In add.php, we do a simple validation of
checking if the entered name, email & age are empty or not. If they are all filled then the data will be inserted into database table.
10
add.php
1 <html>
2 <head>
3 <title>Add Data</title>
4 </head>
5
6 <body>
7 <?php
8 //including the database connection file
9 include_once("config.php");
10
11 if(isset($_POST['Submit'])) {
12 $name = $_POST['name'];
13 $age = $_POST['age'];
14 $email = $_POST['email'];
15
16 // checking empty fields
17 if(empty($name) || empty($age) || empty($email)) {
18
19 if(empty($name)) {
20 echo "<font color='red'>Name field is empty.</font><br/>";
21 }
22
23 if(empty($age)) {
24 echo "<font color='red'>Age field is empty.</font><br/>";
25 }
26
27 if(empty($email)) {
28 echo "<font color='red'>Email field is empty.</font><br/>";
29 }
30
31 //link to the previous page
32 echo "<br/><a href='javascript:self.history.back();'>Go Back</a>";
33 } else {
34 // if all the fields are filled (not empty)
35
36 //insert data to database
37 $sql = "INSERT INTO users(name, age, email) VALUES(:name, :age, :email)";
38 $query = $dbConn->prepare($sql);
39
40 $query->bindparam(':name', $name);
41 $query->bindparam(':age', $age);
42 $query->bindparam(':email', $email);
43 $query->execute();
44
45 // Alternative to above bindparam and execute
46 // $query->execute(array(':name' => $name, ':email' => $email, ':age' => $age));
47
48 //display success message
49 echo "<font color='green'>Data added successfully.";
50 echo "<br/><a href='index.php'>View Result</a>";
51 }
52 }
53 ?>
54 </body>
55 </html>
Data from database is fetched and displayed in index.php file. This is our homepage. This file also contains a link to add data. On every
row of displayed data, there is also a link to edit and delete data. Below is a sample image of our homepage:
11
index.php
<?php
1
//including the database connection file
2
include_once("config.php");
3
4
//fetching data in descending order (lastest entry first)
5
$result = $dbConn->query("SELECT * FROM users ORDER BY id DESC");
6
?>
7
8
<html>
9
<head>
10
<title>Homepage</title>
11
</head>
12
13
<body>
14
<a href="add.html">Add New Data</a><br/><br/>
15
16
<table width='80%' border=0>
17
18
<tr bgcolor='#CCCCCC'>
19
<td>Name</td>
20
<td>Age</td>
21
<td>Email</td>
22
<td>Update</td>
23
</tr>
24
<?php
25
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
26
echo "<tr>";
27
echo "<td>".$row['name']."</td>";
28
echo "<td>".$row['age']."</td>";
29
echo "<td>".$row['email']."</td>";
30
echo "<td><a href=\"edit.php?id=$row[id]\">Edit</a> | <a href=\"delete.php?id=$row[id]\" onClick=\"return
31
confirm('Are you sure you want to delete?')\">Delete</a></td>";
32
}
33
?>
34
</table>
35
</body>
36
</html>
Each row of data can be edited separately. Row ID is passed in the URL of edit.php. ID uniquely identifies the data entry.
While adding data, we had two files: add.html and add.php. While editing data, I have kept the entire thing in a single edit.php file. Edit
form in HTML and database update code in PHP are present in the same file.
In the code below, at first a single row entry of data is fetched based on the id. The fetched data is displayed in the edit form. When user
edits the data and submits the form, then some simple validation is done for empty data. When everything is correct, then that particular
entry of data is updated in database.
edit.php
1 <?php
2 // including the database connection file
12
3 include_once("config.php");
4
5 if(isset($_POST['update']))
6 {
7 $id = $_POST['id'];
8
9 $name=$_POST['name'];
10 $age=$_POST['age'];
11 $email=$_POST['email'];
12
13 // checking empty fields
14 if(empty($name) || empty($age) || empty($email)) {
15
16 if(empty($name)) {
17 echo "<font color='red'>Name field is empty.</font><br/>";
18 }
19
20 if(empty($age)) {
21 echo "<font color='red'>Age field is empty.</font><br/>";
22 }
23
24 if(empty($email)) {
25 echo "<font color='red'>Email field is empty.</font><br/>";
26 }
27 } else {
28 //updating the table
29 $sql = "UPDATE users SET name=:name, age=:age, email=:email WHERE id=:id";
30 $query = $dbConn->prepare($sql);
31
32 $query->bindparam(':id', $id);
33 $query->bindparam(':name', $name);
34 $query->bindparam(':age', $age);
35 $query->bindparam(':email', $email);
36 $query->execute();
37
38 // Alternative to above bindparam and execute
39 // $query->execute(array(':id' => $id, ':name' => $name, ':email' => $email, ':age' => $age));
40
41 //redirectig to the display page. In our case, it is index.php
42 header("Location: index.php");
43 }
44 }
45 ?>
46 <?php
47 //getting id from url
48 $id = $_GET['id'];
49
50 //selecting data associated with this particular id
51 $sql = "SELECT * FROM users WHERE id=:id";
52 $query = $dbConn->prepare($sql);
53 $query->execute(array(':id' => $id));
54
55 while($row = $query->fetch(PDO::FETCH_ASSOC))
56 {
57 $name = $row['name'];
58 $age = $row['age'];
59 $email = $row['email'];
60 }
61 ?>
62 <html>
63 <head>
64 <title>Edit Data</title>
65 </head>
66
67 <body>
68 <a href="index.php">Home</a>
69 <br/><br/>
70
71 <form name="form1" method="post" action="edit.php">
72 <table border="0">
73 <tr>
74 <td>Name</td>
75 <td><input type="text" name="name" value="<?php echo $name;?>"></td>
76 </tr>
77 <tr>
78 <td>Age</td>
79 <td><input type="text" name="age" value="<?php echo $age;?>"></td>
80 </tr>
81 <tr>
13
82 <td>Email</td>
83 <td><input type="text" name="email" value="<?php echo $email;?>"></td>
84 </tr>
85 <tr>
86 <td><input type="hidden" name="id" value=<?php echo $_GET['id'];?>></td>
87 <td><input type="submit" name="update" value="Update"></td>
88 </tr>
89 </table>
90 </form>
91 </body>
92 </html>
Each row of data can be deleted separately. Row ID is passed in the URL of delete.php. ID uniquely identifies the data entry. After
deletion, the user is redirected to homepage (index.php).
delete.php
1 <?php
2 //including the database connection file
3 include("config.php");
4
5 //getting id of the data from url
6 $id = $_GET['id'];
7
8 //deleting the row from table
9 $sql = "DELETE FROM users WHERE id=:id";
10 $query = $dbConn->prepare($sql);
11 $query->execute(array(':id' => $id));
12
13 //redirecting to the display page (index.php in our case)
14 header("Location:index.php");
15 ?>
14