[php] connexion mysql - poo + pdo
voici ma petit classe php permettant de réaliser des requêtes SQL.
il faut biensure remplacer les informations 'MA_DATABASE', 'MON_LOGIN', 'MON_PASSWORD', 'MON_HOST', 'ma_Table' par vos propres données.
dal_sql.php
01.
<?php
02.
03.
class
dal_sql{
04.
05.
private
$db_data
=
''
;
06.
private
$db_log
=
''
;
07.
private
$db_pwd
=
''
;
08.
private
$db_host
=
''
;
09.
private
$pdo
;
10.
11.
public
function
__construct(
$db_data
=
'MA_BDD'
,
$db_log
=
'MON_LOGIN'
,
$db_pwd
=
'MON_PASSWORD'
,
$db_host
=
'localhost'
){
12.
$this
->db_data =
$db_data
;
13.
$this
->db_log =
$db_log
;
14.
$this
->db_pwd =
$db_pwd
;
15.
$this
->db_host =
$db_host
;
16.
}
17.
18.
private
function
Get_PDO(){
19.
if
(
$this
->pdo === null) {
20.
try {
21.
$pdo
=
new
PDO(
'mysql:host='
.
$this
->db_host.
';dbname='
.
$this
->db_data,
$this
->db_log,
$this
->db_pwd);
22.
$pdo
->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
23.
$this
->pdo =
$pdo
;
24.
}
25.
catch(PDOException
$e
){
26.
echo
'pb data base <br/>'
.
$e
;
27.
}
28.
}
29.
return
$this
->pdo;
30.
}
31.
32.
public
function
Get_Prepare(
$req_sql
,
$attributs
){
33.
$req
=
$this
->Get_PDO()->prepare(
$req_sql
);
34.
$req
->execute(
$attributs
);
35.
$datas
=
$req
->fetchAll(PDO::FETCH_OBJ);
36.
return
$datas
;
37.
}
38.
39.
public
function
Set_Prepare(
$req_sql
,
$attributs
){
40.
$req
=
$this
->Get_PDO()->prepare(
$req_sql
);
41.
$req
->execute(
$attributs
);
42.
return
$req
;
43.
}
44.
}
45.
46.
?>
ma_page.php
01.
<?php
02.
include
(
'dal_sql.php'
);
03.
04.
$db
=
new
dal_sql();
05.
// Récuperation de données
06.
$datas
=
$db
->Get_Prepare(
'SELECT * FROM ma_Table WHERE Champ1<> :Champ1 '
,
array
(
'Champ1'
=>
''
));
07.
echo
'<div>'
;
08.
foreach
(
$datas
as
$data
) :
09.
echo
$data
->Champ1.
'<br/>'
;
10.
echo
$data
->Champ2.
'<br/>'
;
11.
endforeach
;
12.
echo
'</div>'
;
13.
14.
// Insertion de donnée
15.
$datas
=
$db
->Set_Prepare(
'INSERT INTO ma_Table (Champ1,Champ2) VALUES (:Champ1,:Champ2) '
,
array
(
'Champ1'
=>
'test ch 01'
,
'Champ'
=>
'test ch 02'
, ));
16.
if
(
$datas
) {
17.
echo
'<div>Ok</div>'
;
18.
}
19.
else
{
20.
echo
'<div>Pas ok</div>'
;
21.
}
22.
?>