8797 sujets

Développement web côté serveur, CMS

Bonjour.
J'utilise des fonctions pour mes requêtes, et j'aimerais vos conseils pour sécuriser le sql et aussi faire de ces fonctions une classe pour accéder directement aux objets.
Par ex:

$page = new page;
$page->get_page($title);
echo "<h1>".$head->h1."</h1>";
$media = new media;
$media->get_media($id);
$media->get_iptc($media_id);

Je voudrais par la suite faire une autre classe pour mètre en forme les données avec un système de template.
Pour le moment voici les fonctions sql

<?php
include ('admin/conf.inc.php');

function get_author($id) {
	$con = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
	if ($id) {
		$sql = "SELECT * FROM creator WHERE id = '".$id."'";
		if ($result = $con->query($sql)) {
			$obj = $result->fetch_object();
			global $author;
			$loc = 
				htmlentities($obj->CiAdrCtry).", "
				.htmlentities($obj->CiAdrRegion).", "
				.htmlentities($obj->CiAdrCity);
			$author = array(
				'name'=>htmlentities($obj->creator),
				'location'=>$loc,
				'id'=>$obj->id
			);
		}
	$result->close();
	$con->close();
	}
}

function get_content($content) {
	$con = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
	if (mysqli_connect_errno()) {
		printf("Connexion impossible: %s\n", mysqli_connect_error());
	exit();
	}
	if(count($content) == '1') {
		$content = implode($content);
		$sql = "SELECT * FROM content WHERE id = '".$content."'";
	}
	if(count($content) > '1') {
		$content = "(".implode(", ", $content).")";
		$sql = "SELECT * FROM content WHERE id IN ".$content;
	}
	if (!$result = $con->query($sql)){
		printf("Le contenu demandé n'existe pas: \n",$con->error);
	}
	if ($result = $con->query($sql)){
		global $articles;
		$i = 0;
		while($obj = $result->fetch_object()) {
			$titre = utf8_encode($obj->titre);
			$chapeau = utf8_encode($obj->chapeau);
			$texte = utf8_encode($obj->texte);
			$articles[$i] = array('titre'=>$titre,'chapeau'=>$chapeau,'texte'=>$texte);
			$i++;
		}
		$result->close();
		$con->close();
	}
}

function get_page($title){
	$con = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
	if (mysqli_connect_errno()) {
		printf("Connexion impossible: %s\n", mysqli_connect_error());
	exit();
	}
	$sql = "SELECT * FROM page WHERE title = '".$title."'";
	if (!$con->query($sql)){
		printf("La page %s n'existe pas:\n",$con->error);
	}
	if ($result = $con->query($sql)){
		$obj = $result->fetch_object();
		global $head;
		$head = array(
			'title'=>htmlentities($obj->title),
			'h1'=>htmlentities($obj->h1),
			'head_title'=>htmlentities($obj->head_title),
			'commentaire'=>$obj->commentaire,
			'created'=>$obj->created,
			'modified'=>$obj->modified,
			'keywords'=>htmlentities($obj->keywords),
			'rel'=>$obj->rel,
			'content'=>explode(", ",$obj->content),
			'description'	=>htmlentities($obj->description),
			'author'=>$obj->author,
			'pages'=>$obj->pages,
			'type'=>$obj->type
		);
		$result->close();	
		get_author($head['author']);
		get_content($head['content']);
		$con->close();
	}
}

function get_media($id){
	$con = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
	if (mysqli_connect_errno()) {
		printf("Connexion impossible: %s\n", mysqli_connect_error());
	exit();
	}
	$sql = "SELECT * FROM media WHERE id = '".$id."'";
	if (!$con->query($sql)) {
		printf("Le média % n'existe pas\n",$con->error);
	}
	if ($result = $con->query($sql)){
		global $media;
		$obj = $result->fetch_object();
		$src = $obj->filepath.$obj->filename;
		$var = getimagesize($src);
		$size = $var['3'];
		$media = array(
			'id'=>$obj->id,
			'src'=>$src,
			'size'=>$size,
			'creator'=>$obj->creator,
			'iptc'=>$obj->iptc,
			'exif'=>$obj->exif
		);
		$result->close();
		$con->close();
	}
}
	
function get_iptc($id) {
	$con = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
	if (mysqli_connect_errno()) {
		printf("Connexion impossible: %s\n", mysqli_connect_error());
	exit();
	}
	$sql = "SELECT * FROM iptc WHERE id = '".$id."'";
	if (!$con->query($sql)) {
		printf("Il n'y a pas d\'informations iptc pour %\n",$con->error);
	}
	if ($result = $con->query($sql)){
		global $iptc;
		$obj = $result->fetch_object();
		$iptc = array(
			'titre'=>utf8_encode($obj->title),
			'sous titre'=>utf8_encode($obj->Headline),
			'description'	=>utf8_encode($obj->description),
			'sujet'	=>utf8_encode($obj->subject),
			'date'=>$obj->DateCreated,
			'lieu'=>utf8_encode($obj->Location),
			'ville'=>utf8_encode($obj->City),
			'région'=>utf8_encode($obj->State),
			'pays'	=>utf8_encode($obj->Country),
			'code pays'=>$obj->CountryCode,
			'crédit'=>utf8_encode($obj->credit),
			'droits'=>utf8_encode($obj->rights),
			'source'=>utf8_encode($obj->Source),
			'usage'=>utf8_encode($obj->UsageTerms),
			'instructions'=>utf8_encode($obj->Instructions),
			'transmission'=>utf8_encode($obj->TransmissionReference),
			'genre'=>utf8_encode($obj->IntellectualGenre),
			'code sujet'=>$obj->SubjectCode,
			'scène'=>$obj->Scene,
			'auteur'=>utf8_encode($obj->creator),
			'auteur de la description'=>utf8_encode($obj->CaptionWriter)
		);
		$result->close();
		$con->close();
	}
}
?>

Merci de me donner quelques conseils ou liens pour débuter avec les classes, afin de transformer ces fonctions en classe, les optimiser (par exemple je n'arrive pas à garder $con pour les fonctions qui s'enchainent), et y ajouter un système pour sécuriser les reqêtes à la base de donnée, j'avoue que je me perd un peu avec les $this->.
Modifié par cyrildphotos (01 May 2009 - 17:28)
Salut,

Ce que tu fais n'est pas une classe mais un série de fonctions, une classe permet justement de pouvoir modifier des variables avec plusieurs fonctions : http://www.manuelphp.com/php/keyword.class.php par exemple tu peux ainsi garder ta variable $con Smiley lol :

class Mysql {

   var $con;

   function connect() {
      $this->con = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
   }

   function get_content($content) {
      $this->con; //ta variable $con est maintenant disponible pour toutes tes fonctions dans ta classe
   }

}

Modifié par matmat (02 May 2009 - 01:31)
Oui, c'est pour cela que je veux transformer ces fonctions en class...
J'essaye ta méthode mais j'y arrive pas.
Je précise que j'utilise PHP Version 5.2.6
J'ai essayé en déclarant $title public, en déclarant les méthodes public ou private (sauf Page($title)).
Quelles sont les erreurs?

<?php
include('admin/conf.inc.php');
class Sql {
    var $title, $con, $page;
//  function __construct() {
//      $this->title    = mysql_escape_string($title);
//      $this->id_media = int($id_media);
//      $this->page = '';
//      $this->con = '';
//  }
    
    function Connexion() {
        $this->con = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
        if (mysqli_connect_errno()) {
            printf("Connexion impossible: %s\n", mysqli_connect_error());
        exit();
        }
    }
    
    function Get_Author() {
        if ($head['author']) {
            $sql = "SELECT * FROM creator WHERE id = '".$id."'";
            if ($result = $con->query($sql)) {
                $obj = $result->fetch_object();
                $loc = 
                    htmlentities($obj->CiAdrCtry).", "
                    .htmlentities($obj->CiAdrRegion).", "
                    .htmlentities($obj->CiAdrCity);
                $author = array(
                    'name'      =>htmlentities($obj->creator),
                    'location'  =>$loc
                );
            $result->close();
            }
        }
    }

    function Get_Content() {
        if (mysqli_connect_errno()) {
            printf("Connexion impossible: %s\n", mysqli_connect_error());
        exit();
        }
        if(count($head['content']) === '1') {
            $content = implode($page['content']);
            $sql = "SELECT * FROM content WHERE id = '".$content."'";
        }
        if(count($head['content']) > '1') {
            $content = "(".implode(", ", $page['content']).")";
            $sql = "SELECT * FROM content WHERE id IN ".$content;
        }
        if (!$result = $con->query($sql)){
            printf("Le contenu demandé n'existe pas: \n",$con->error);
        }
        if ($result = $con->query($sql)){
            $i = 0;
            while($obj = $result->fetch_object()) {
                $titre = utf8_encode($obj->titre);
                $chapeau = utf8_encode($obj->chapeau);
                $texte = utf8_encode($obj->texte);
                $articles[$i] = array('titre'=>$titre,'chapeau'=>$chapeau,'texte'=>$texte);
                $i++;
            }
            $result->close();
        }
    }

    function Get_Head($title){
        $sql = "SELECT * FROM page WHERE title = '".$title."'";
        if (!$result = $con->query($sql)){
            printf("La page %s n'existe pas:\n",$con->error);
        }
        if ($result = $con->query($sql)){
            $obj = $result->fetch_object();
            $this->head = $head;
            $head = array(
                'title'         =>  htmlentities($obj->title),
                'h1'            =>  htmlentities($obj->h1),
                'head_title'    =>  htmlentities($obj->head_title),
                'commentaire'   =>  $obj->commentaire,
                'created'       =>  $obj->created,
                'modified'      =>  $obj->modified,
                'keywords'      =>  htmlentities($obj->keywords),
                'rel'           =>  $obj->rel,
                'content'       =>  explode(", ",$obj->content),
                'description'   =>  htmlentities($obj->description),
                'author'        =>  $obj->author,
                'pages'         =>  $obj->pages
            );
            $result->close();
        }
    }
    
    function Page($title) {
        $this->Connexion();
        $this->Get_Head($title);
        $this->Get_Content();
        $this->Get_Author();
        $this->page = array(
            'head'      => $this->head,
            'author'    => $this->author,
            'articles'  => $this->articles
        );
        $con->close();
    }
}
?>

Je teste avec:

<?php
	include('lib/Sql.class.php');
	$page = new Sql;
	$page->Page("accueil");
	print_r($page->page);
?>

et j'ai comme erreur:
Notice: Undefined variable: con in /home/cyril/public_html/test.floue.net/lib/Sql.class.php on line 72
Fatal error: Call to a member function query() on a non-object in /home/cyril/public_html/test.floue.net/lib/Sql.class.php on line 72
Modifié par cyrildphotos (02 May 2009 - 13:54)
Merci Smiley biggrin
C'est bon ça marche comme ça...

<?php
include('admin/conf.inc.php');
class Sql {
    private $con; 
    public $page;
    
    private function Connexion() {
        $this->con = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
        if (mysqli_connect_errno()) {
            printf("Connexion impossible: %s\n", mysqli_connect_error());
        exit();
        }
    }
    
    private function Get_Author() {
        if ($this->head['author']) {
            $sql = "SELECT * FROM creator WHERE id = '".$this->head['author']."'";
            if ($result = $this->con->query($sql)) {
                $obj = $result->fetch_object();
                $loc = 
                    htmlentities($obj->CiAdrCtry).", "
                    .htmlentities($obj->CiAdrRegion).", "
                    .htmlentities($obj->CiAdrCity);
                $this->author = array(
                    'name'      =>htmlentities($obj->creator),
                    'location'  =>$loc
                );
            $result->close();
            }
        }
    }

    private function Get_Content() {
        $c = $this->head['content'];
        if(count($c) == '1') {
            $c = implode($c);
            $sql = "SELECT * FROM content WHERE id = '".$c."'";
        }
        if(count($c) > '1') {
            $c = "(".implode(", ",$c).")";
            $sql = "SELECT * FROM content WHERE id IN ".$c;
        }
        if (!$result = $this->con->query($sql)){
            printf("Le contenu demandé n'existe pas: \n",$this->con->error);
        }
        if ($result = $this->con->query($sql)){
            $i=0;
            while($obj = $result->fetch_object()) {
                $this->articles[$i] = array(
                    'titre'     =>  utf8_encode($obj->titre),
                    'chapeau'   =>  utf8_encode($obj->chapeau),
                    'texte'     =>  utf8_encode($obj->texte)
                );
                $i++;
            }
            $result->close();
        }
    }

    private function Get_Head($title){
        $sql = "SELECT * FROM page WHERE title = '".$title."'";
        if (!$result = $this->con->query($sql)){
            printf("La page %s n'existe pas:\n",$this->con->error);
        }
        if ($result = $this->con->query($sql)){
            $obj = $result->fetch_object();
            $this->head = array(
                'title'         =>  htmlentities($obj->title),
                'h1'            =>  htmlentities($obj->h1),
                'head_title'    =>  htmlentities($obj->head_title),
                'commentaire'   =>  $obj->commentaire,
                'created'       =>  $obj->created,
                'modified'      =>  $obj->modified,
                'keywords'      =>  htmlentities($obj->keywords),
                'rel'           =>  $obj->rel,
                'content'       =>  explode(", ",$obj->content),
                'description'   =>  htmlentities($obj->description),
                'author'        =>  $obj->author,
                'pages'         =>  $obj->pages
            );
            $result->close();
        }
    }
    
    public function Page($title) {
        $title = mysql_escape_string($title);
        $this->Connexion();
        $this->Get_Head($title);
        $this->Get_Content();
        $this->Get_Author();
        $this->page = array(
            'head'      => $this->head,
            'author'    => $this->author,
            'articles'  => $this->articles
        );
        $this->con->close();
    }
}
?>

On peut sûrement améliorer, n'hésitez pas à donner des conseils...
Merci encore.
Tu es en train de faire deux fois tes requêtes :
if (!$result = $this->con->query($sql)){
   printf("Le contenu demandé n'existe pas: \n",$this->con->error);
}
if ($result = $this->con->query($sql)){
   $i=0;
   while($obj = $result->fetch_object()) {
      $this->articles[$i] = array(
         'titre'     =>  utf8_encode($obj->titre),
         'chapeau'   =>  utf8_encode($obj->chapeau),
         'texte'     =>  utf8_encode($obj->texte)
      );
      $i++;
   }
   $result->close();
}

Tu peux faire :
if ($result = $this->con->query($sql)){
   $i=0;
   while($obj = $result->fetch_object()) {
      $this->articles[$i] = array(
         'titre'     =>  utf8_encode($obj->titre),
         'chapeau'   =>  utf8_encode($obj->chapeau),
         'texte'     =>  utf8_encode($obj->texte)
      );
      $i++;
    }
    $result->close();
}else{
   printf("Le contenu demandé n'existe pas: \n",$this->con->error);
}

Modifié par matmat (02 May 2009 - 17:58)