You are on page 1of 14

Figura 1: Aprenda a efetuar as operações de CRUD com PHP e MySQL

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.

Listagem 1: Arquivo para gerar a tabela livro – script.sql

CREATE DATABASE biblioteca;

use biblioteca;

CREATE TABLE IF NOT EXISTS `livro` (

`id_livro` int(11) NOT NULL AUTO_INCREMENT,

`cod_livro` int(11) NOT NULL,

`nome_livro` varchar(150) NOT NULL,

`desc_livro` varchar(150) NOT NULL,

PRIMARY KEY (`id_livro`)

) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

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.

Listagem 2: Criando o arquivo conexao.php

//Variáveis de acesso Db

1
define('DB_SERVER', 'localhost');

define('DB_NAME', 'biblioteca');

define('DB_USERNAME', 'root');

define('DB_PASSWORD', '');

//inicio da classe de conexao

class Conexao {

var $db, $conn;

public function __construct($server, $database, $username, $password){

$this->conn = mysql_connect($server, $username, $password);

$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”:

Listagem 3: Bloco de código da função insert

/**

* Função para inserir dados na tabela

* @param array $dados Array contendo os dados a serem inseridos

* @param string $tabela tabela que será inserido os dados

2
*/

public function insert($tabela, $dados) {

foreach ($dados as $key => $value) {

$keys[] = $key;

$insertvalues[] = '\'' . $value . '\'';

$keys = implode(',', $keys);

$insertvalues = implode(',', $insertvalues);

$sql = "INSERT INTO $tabela ($keys) VALUES ($insertvalues)";

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:

Listagem 4: Arquivo index.php

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title></title>

3
</head>

<body>

<?php

require_once 'conexao.php';

$conexao = new Conexao(DB_SERVER, DB_NAME, DB_USERNAME, DB_PASSWORD);

$dados = array('cod_livro' => 01, 'nome_livro' => 'livro exemplo 01',


'desc_livro' => 'Livro de exemplo');

$insert = $conexao->insert('livro', $dados);

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”

Listagem 5: Função update

/**

* Função para alterar os dados da tabela

* @param string $tabela tabela onde será alterado os dados

4
* @param string $colunaPrimary nome da coluna chave primaria

* @param int $id id do dados a ser alterado

* @param array $dados dados que serão inserido

* @return boolean verdadeiro ou falso

*/

public function update($tabela, $colunaPrimay, $id, $dados) {

foreach ($dados as $key => $value) {

$sets[] = $key . '=\'' . $value . '\'';

$sets = implode(',', $sets);

$sql = "UPDATE $tabela SET $sets WHERE $colunaPrimay = '$id'";

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:

Listagem 6: Arquivo Update.php

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

5
<title></title>

</head>

<body>

<?php

require_once 'conexao.php';

$conexao = new Conexao(DB_SERVER, DB_NAME, DB_USERNAME, DB_PASSWORD);

$dados = array('cod_livro' => 01, 'nome_livro' => 'livro exemplo 03',


'desc_livro' => 'Livro de exemplo');

$insert = $conexao->update('livro', 'id_livro', 1, $dados);

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.

Listagem 7: Função select dentro de “Conexao.php”

/**

* Função de seleção dos registros da tabela

6
* @param string $tabela Description

* @param string $colunas string contendo as colunas separadas por


virgula para seleção, se null busca por todas *

*/

public function select($tabela, $colunas = "*") {

$sql = "SELECT $colunas FROM $tabela";

$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

Listagem 8: Conteúdo do arquivo select.php

/**

* Função de seleção dos registros da tabela

* @param string $tabela nome da tabela

* @param string $colunas string contendo as colunas separadas por


virgula para seleção, se null busca por todas *

*/

public function select($tabela, $colunas = "*") {

$sql = "SELECT $colunas FROM $tabela";

$result = $this->executar($sql);

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

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:

Listagem 9: Arquivo Select.php

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title></title>

</head>

<body>

<?php

require_once 'conexao.php';

$conexao = new Conexao(DB_SERVER, DB_NAME, DB_USERNAME, DB_PASSWORD);

$select = $conexao->select('livro');

foreach ($select as $livro) {

echo '================'.'</br>';

echo 'Id = '.$livro['id_livro'].'</br>';

8
echo 'Codigo = '.$livro['cod_livro'].'</br>';

echo 'Nome = '.$livro['nome_livro'].'</br>';

echo 'Descrição = '.$livro['desc_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‘.

create database test;


Then, we will create a new table in database ‘test’. Let us name the table as ‘users‘.

use test;

CREATE TABLE users (

id int(11) NOT NULL auto_increment,

name varchar(100) NOT NULL,

age int(3) NOT NULL,

email varchar(100) NOT NULL,

PRIMARY KEY (id)

);

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

You might also like