Bonjour ,

je fais le tutoriel sur la POO et Création de models en Php;
Et lorsque je fais un insert into j'obtiens le message d'erreur suivant :

Warning: PDO::exec(): SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '( name, position ) VALUES ( 'v1', 'v2')' at line 1 in C:\wamp\www\tuto_poo\models\Model.class.php on line 71

Les valeur V1 et V2 correspondent aux valeurs entrées dans le formulaire.

Voici mon code de la page model :

<?php
class Model 
{
    public $table;
    function read($fields = null)
    {
        global $db;
        if($fields == null)
        {
            $fields ='*';
        }
        $sql = 'SELECT '.$fields.' FROM '.$this->table.' WHERE id='.$this->id;
        $req = $db->query($sql) or die(); 
        $data = $req->fetch(PDO::FETCH_ASSOC);

        // on parcours le tableau $data
        foreach($data as $key => $value) 
        {
            $this->$key = $value;   
        }
    }
    //Fonction sauvegarde
    public function save($data)
    {
        global $db;
         // Si id existe déjà et n'est pas vide  
        if(isset($data'id']) && !empty($data'id']))
        {
            $sql ="UPDATE ".$this->table." SET ";
            foreach ($data as $key=>$value) 
            {
                if($key!="id")
                {
                    $sql .= "$key='".addslashes($value)."',";
                }
            }
            $sql = substr($sql,0,-1); 

            $sql .= " WHERE id=".$data'id'];
        echo $sql;}else
        {

            $sql ="INSERT INTO ".$this->table." SET(";
        unset($data"id"]); 
            foreach ($data as $key=>$value) 
            {
            $sql .= " $key,"; 
            }
            $sql = substr($sql,0,-1); 

            $sql .= " ) VALUES ( ";
                foreach ($data as $value) {
                    $sql .= " '".addslashes($value)."',";
                }
            $sql = substr($sql,0,-1);
            $sql .=")";

        echo $sql;}

        $db->exec($sql) or die();
        if(!isset($data'id']))
        {
            $this->id = $this->db->lastInsertId(); //on recupère le dernier id inseré
        }
        else
        {
            $this->id = $data'id'];
        }

    }

    //Permet de charger le model souhaité
    static function load($name)
    {
        require("$name.class.php");
        return new $name();
    }
}

L'autre solution, plus sure je le sais est de passer par une requete préparée, mais je me gardais ça pour la fin du tutoriel.

Merci d'avance =)

70 réponses


Xen0risDEV
Réponse acceptée

Bonjour,

<?php
require 'core.php' ;
$Category = Model::load('Category');
if(!empty($_POST)) {
    $ext = extract($_POST);
    $Category->save($ext);
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="theme/style.css" type="text/css" media="screen" />
</head>
<body>
<h1> La programation orientée objet </h1>
<form method="post" action="index.php">
    <?php 
        if(isset($_GET'id'])){
            $id = $_GET"id"]; 
            $data = $Category->read(array(
                'conditions' => array('id' => $id)
            ));         
            $name = $data[0]'name'];
            $position = $data[0]'position'];
        } else {
            $id = $name = $position = "";
        }
    ?>
    <input type="hidden" name="id" value="<?= $id ; ?>"/>
    <input type="text" name="name" value="<?= $name; ?>"/>
    <input type="text" name="position" value="<?= $position; ?>"/>
    <input type="submit" value="envoyer"/>
</form>
</body>
</html>

Cordialement. :)

Bonjour tenter cela :

<?php

class Model 
{   
    public $db;
    public $table;
    public $id;
    public $primaryKey = 'id';

    function read($fields = null)
    {

        if($fields == null)
        {
            $fields ='*';
        }
        $sql = 'SELECT '.$fields.' FROM '.$this->table.' WHERE id='.$this->id;
        $req = $this->db->query($sql) or die(); 
        $data = $req->fetch(PDO::FETCH_ASSOC);

        // on parcours le tableau $data

        foreach($data as $key => $value) 
        {
            $this->$key = $value;    
        }
    }

    //Fonction sauvegarde

    public function save($data) {
        $key = $this->primaryKey;
        $fields = array();
        $d = array(); 
        foreach($data as $k=>$v){
            if($k!=$this->primaryKey){
                $fields] = "$k=:$k";
                $d":$k"] = $v; 
            }elseif(!empty($v)){
                $d":$k"] = $v; 
            }
        }
        if(isset($data->$key) && !empty($data->$key)){
            $sql = 'UPDATE '.$this->table.' SET '.implode(',',$fields).' WHERE '.$key.'=:'.$key;
            $this->id = $data->$key; 
            $action = 'update';
        } else{
            $sql = 'INSERT INTO '.$this->table.' SET '.implode(',',$fields);
            $action = 'insert'; 
        }
        $pre = $this->db->prepare($sql); 
        $pre->execute($d);
        if($action == 'insert'){
            $this->id = $this->db->lastInsertId(); 
        }
    }

    //Permet de charger le model souhaité

    static function load($name)
    {
        require("$name.class.php");
        return new $name();
    }

}

Cordialement.

Bomber
Auteur

Ma variable $db ne peut pas être mise en public car elle n'est pas dans ma classe , c'est pour cela que je l'ai mise en global.
Faut il que je fasse ma connexion à la base de donnée dans un fonction __construct ?

car avec ton code en la déclarant en global j'obtiens les messages d'erreur:

Notice: Undefined property: Category::$db in C:\wamp\www\tuto_poo\models\Model.class.php on line 66

et

Fatal error: Call to a member function prepare() on a non-object in C:\wamp\www\tuto_poo\models\Model.class.php on line 66

la ligne 66 correspond à

$pre = $this->db->prepare($sql);
        $pre->execute($d);
Bomber
Auteur

j ai mis ma connexion à la base de donnée dans la fonction __construct,
et désormais lorsque je fais un Update, j ai les messages suivant ... :

Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in C:\wamp\www\tuto_poo\models\Model.class.php on line 102
Call Stack

Time Memory Function Location

1 0.0000 246840 {main}( ) ..\index.php:0
2 0.0200 288936 Model->save( ) ..\index.php:11
3 0.0200 291488 execute ( ) ..\Model.class.php:102

Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number in C:\wamp\www\tuto_poo\models\Model.class.php on line 102
Call Stack

Time Memory Function Location

1 0.0000 246840 {main}( ) ..\index.php:0
2 0.0200 288936 Model->save( ) ..\index.php:11
3 0.0200 291488 execute ( ) ..\Model.class.php:102

Warning: Invalid argument supplied for foreach() in C:\wamp\www\tuto_poo\models\Model.class.php on line 61
Call Stack

Time Memory Function Location

1 0.0000 246840 {main}( ) ..\index.php:0
2 0.0200 289768 Model->read( ) ..\index.php:34

Notice: Undefined property: Category::$name in C:\wamp\www\tuto_poo\index.php on line 35
Call Stack

Time Memory Function Location

1 0.0000 246840 {main}( ) ..\index.php:0

Notice: Undefined property: Category::$position in C:\wamp\www\tuto_poo\index.php on line 36
Call Stack

Time Memory Function Location

1 0.0000 246840 {main}( ) ..\index.php:0

Voici la class Model

class Model 
{
    public $conf = 'default'; // parametre de connection à choisir 
    public $db;
    public $table;
    public $id;

    public $primaryKey = 'id';

    public function __construct()
    {
        $conf = Config_bdd::$databases$this->conf];
        try
            {
             $pdo = new PDO('mysql:host='.$conf'host'].'; dbname='.$conf'dbname'], $conf'login'] , $conf'password']);
             $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);
             $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_OBJ);
             $this->db = $pdo;
            }
        catch(PDOException $e)
            {
                ('Erreur :'. $e->getMessage());
            }

    }

    function read($fields = null)
    {

        if($fields == null)
        {
            $fields ='*';
        }
        $sql = 'SELECT '.$fields.' FROM '.$this->table.' WHERE id='.$this->id;
        $req = $this->db->query($sql) or die();
        $data = $req->fetch(PDO::FETCH_ASSOC);

        // on parcours le tableau $data

        foreach($data as $key => $value)
        {
            $this->$key = $value;   
        }
    }

    //Fonction sauvegarde

    public function save($data) 
    {

        $key = $this->primaryKey;
        $fields = array();
        $d = array();
        foreach($data as $k=>$v)
        {
            if($k!=$this->primaryKey)
            {
                $fields] = "$k=:$k";
                $d":$k"] = $v;
            }elseif(!empty($v))
            {
                $d":$k"] = $v;
            }
        }
        if(isset($data->$key) && !empty($data->$key))
        {
            $sql = 'UPDATE '.$this->table.' SET '.implode(',',$fields).' WHERE '.$key.'=:'.$key;
            $this->id = $data->$key;
            $action = 'update';
        } 
        else
        {
            unset($data"id"]);
            $sql = 'INSERT INTO '.$this->table.' SET '.implode(',',$fields);
            $action = 'insert';
        }
        $pre = $this->db->prepare($sql);
        $pre->execute($d);
        if($action == 'insert')
        {
            $this->id = $this->db->lastInsertId();
        }
    }

Bonjour,

<?php
class Model 
{

    public $conf = 'default'; // parametre de connection à choisir 

    public $db;

    public $table;

    public $id;

    public $primaryKey = 'id';

    public function __construct(){

        $conf = Config_bdd::$databases$this->conf];

        try{
            $options = array(
                PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_OBJ
            );
            $pdo = new PDO('mysql:host='.$conf'host'].'; dbname='.$conf'dbname'], $conf'login'] , $conf'password'], $options);
            $this->db = $pdo;
        } catch(PDOException $e) {
            print('Erreur :'. $e->getMessage());
        }

    }

    function read($fields = null)
    {

        if($fields == null)
        {
            $fields ='*';
        }
        $sql = 'SELECT '.$fields.' FROM '.$this->table.' WHERE id='.$this->id;
        $req = $this->db->query($sql) or die();
        $data = $req->fetch(PDO::FETCH_ASSOC);

        // on parcours le tableau $data

        foreach($data as $key => $value)
        {
            $this->$key = $value;   
        }
    }

    //Fonction sauvegarde

    public function save($data) 
    {

        $key = $this->primaryKey;
        $fields = array();
        $d = array();

        foreach($data as $k=>$v)
        {
            if($k!=$this->primaryKey)
            {
                $fields] = "$k=:$k";
                $d":$k"] = $v;
            }elseif(!empty($v))
            {
                $d":$k"] = $v;
            }
        }
        if(isset($data->$key) && !empty($data->$key))
        {
            $sql = 'UPDATE '.$this->table.' SET '.implode(',',$fields).' WHERE '.$key.'=:'.$key;
            $this->id = $data->$key;
            $action = 'update';
        } 
        else
        {
            unset($data"id"]);
            $sql = 'INSERT INTO '.$this->table.' SET '.implode(',',$fields);
            $action = 'insert';
        }

        $pre = $this->db->prepare($sql);
        $pre->execute($d);

        if($action == 'insert')
        {
            $this->id = $this->db->lastInsertId();
        }
    }

Cordialement.

Bomber
Auteur

Toujours les mêmes erreurs à savoir :

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens' in C:\wamp\www\tuto_poo\models\Model.class.php on line 99

( ! ) PDOException: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in C:\wamp\www\tuto_poo\models\Model.class.php on line 99
Call Stack

Time Memory Function Location

1 0.0010 246840 {main}( ) ..\index.php:0
2 0.0220 289584 Model->save( ) ..\index.php:11
3 0.0220 291976 execute ( ) ..\Model.class.php:99

=/

Bonsoir, je vais regarde cela :)

Cordialement.

Bonjour, tenter ceci :

<?php
class Model {

    public $conf = 'default'; // parametre de connection à choisir 
    public $db;
    public $table;
    public $id; 
    public $primaryKey = "id";

    public function __construct(){

        $conf = Config_bdd::$databases$this->conf];

        try{
            $options = array(
                PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_OBJ
            );
            $pdo = new PDO('mysql:host='.$conf'host'].'; dbname='.$conf'dbname'], $conf'login'] , $conf'password'], $options);
            $this->db = $pdo;
        } catch(PDOException $e) {
            print('Erreur :'. $e->getMessage());
        }
    }

    function read($fields = null) {
        if($fields == null){
            $fields ='*';
        }
        $sql = 'SELECT '.$fields.' FROM '.$this->table.' WHERE id='.$this->id;
        $req = $this->db->query($sql) or die();
        $data = $req->fetch(PDO::FETCH_ASSOC);

        // on parcours le tableau $data

        foreach($data as $key => $value)
        {
            $this->$key = $value;   
        }
    }

    //Fonction sauvegarde

    public function save($data){
        $key = $this->primaryKey;
        $fields = array();
        $d = array(); 
        foreach($data as $k=>$v){
            if($k!=$this->primaryKey){
                $fields] = "$k=:$k";
                $d":$k"] = $v; 
            }elseif(!empty($v)){
                $d":$k"] = $v; 
            }
        }
        if(isset($data->$key) && !empty($data->$key)){
            $sql = 'UPDATE '.$this->table.' SET '.implode(',',$fields).' WHERE '.$key.'=:'.$key;
            $this->id = $data->$key; 
            $action = 'update';
        } else{
            $sql = 'INSERT INTO '.$this->table.' SET '.implode(',',$fields);
            $action = 'insert'; 
        }
        $pre = $this->db->prepare($sql); 
        $pre->execute($d);
        if($action == 'insert'){
            $this->id = $this->db->lastInsertId(); 
        }
    }  
    }

Cordialement.

Bomber
Auteur

Toujours les mêmes messages d'erreur ='(

Bonjour,

<?php
class Model {
    static $connections = array();
    public $conf = 'default'; // parametre de connection à choisir 
    public $table = false;
    public $db;
    public $primaryKey = "id";
    public $id;  

    public function __construct(){
        if($this->table === false) {
            $this->table = strtolower(get_class($this));
        }
        $conf = Config_bdd::$databases$this->conf];

        if(isset(Model::$connections$this->conf])) {
            $this->db = Model::$connections$this->conf];
            return true;
        }
        try{
            $options = array(
                PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_OBJ
            );
            $pdo = new PDO('mysql:host='.$conf'host'].';dbname='.$conf'dbname'], $conf'login'] , $conf'password'], $options);
            Model::$connections$this->conf] = $pdo;
            $this->db = $pdo;
        } catch(PDOException $e) {
            print('Erreur :'. $e->getMessage());
        }
    }

    function read($req = array()) {
        $sql = 'SELECT ';
        if(isset($req'fields'])) {
            if(is_array($req'fields'])) {
                $sql .= implode(', ', $req'fields']);
            } else {
                $sql .= $req'fields'];
            }
        } else {
            $sql .= '*';
        }
        $sql .= ' FROM '.$this->table. ' as '.get_class($this).' ';

        // Pour les jointures 
        if(isset($req'join'])) {
            foreach($req'join'] as $k => $v) {
                $sql .= 'LEFT JOIN '.$k.' ON '.$v.' ';
            }
        }
        // Pour les conditions
        if(isset($req'conditions'])) {
            $sql .= 'WHERE ';
            if(!is_array($req'conditions'])) {
                $sql .= $req'conditions'];
            } else {
                $cond = array();
                foreach($req'conditions'] as $k => $v) {
                    if(!is_numeric($v)) {
                        $v = '"'.@mysql_real_escape_string($v).'"';
                    }

                    $cond] = "$k=$v";
                } 
                $sql .= implode(' AND ', $cond);
            }
        }
        // Les ordres
        if(isset($req'order'])) {
            $sql .= ' ORDER BY '.$req'order'];
        }
        // Les limites
        if(isset($req'limit'])) {
            $sql .= ' LIMIT '.$req'limit'];
        }
        $pre = $this->db->prepare($sql);
        $pre->execute();
        return $pre->fetchAll(PDO::FETCh_OBJ);
    }

    //Fonction sauvegarde

    public function save($data){
        $key = $this->primaryKey;
        $fields = array();
        $d = array(); 
        foreach($data as $k=>$v){
            if($k!=$this->primaryKey){
                $fields] = "$k=:$k";
                $d":$k"] = $v; 
            }elseif(!empty($v)){
                $d":$k"] = $v; 
            }
        }
        if(isset($data->$key) && !empty($data->$key)){
            $sql = 'UPDATE '.$this->table.' SET '.implode(',',$fields).' WHERE '.$key.'=:'.$key;
            $this->id = $data->$key; 
            $action = 'update';
        } else{
            $sql = 'INSERT INTO '.$this->table.' SET '.implode(',',$fields);
            $action = 'insert'; 
        }
        $pre = $this->db->prepare($sql); 
        $pre->execute($d);
        if($action == 'insert'){
            $this->id = $this->db->lastInsertId(); 
        }
    }  
}

Cordialement.

Bomber
Auteur

Bonjour, Désormais je me retrouve avec ( ! ) Notice: Undefined property: Category::$name in C:\wamp\www\tuto_poo\index.php on line 35 Call Stack # Time Memory Function Location 1 0.0010 244512 {main}( ) ..\index.php:0 ( ! ) Notice: Undefined property: Category::$position in C:\wamp\www\tuto_poo\index.php on line 36 Call Stack # Time Memory Function Location 1 0.0010 244512 {main}( ) ..\index.php:0 la page de classe Category : [code]<?php class Category extends Model
{

var $table = 'categories';

}

$Category = new Category();

?>[/code] la page index : [code]<?php require 'core.php' ;

$Category = Model::load('Category');

if(!empty($_POST))
{
$Category->save($_POST); $_GET['id'] = $Category->id; } ?>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" href="theme/style.css" type="text/css" media="screen">

La programation orientée objet

<form method="post" action="index.php">
<?php if(isset($_GET['id']))
{
$id = $_GET["id"];
$Category->id=$id;
$Category->read();
$name = $Category->name;
$position = $Category->position;
}else
{
$id = $name = $position = "";
}

    ?&gt;

    <input type="hidden" name="id" value="&lt;?php echo $id ; ?&gt;">
    <input type="text" name="name" value="&lt;?php echo $name; ?&gt;">
    <input type="text" name="position" value="&lt;?php echo $position; ?&gt;">

    <input type="submit" value="envoyer">

</form>

Bonjour, class Category :

<?php 
class Category extends Model {
    var $table = 'categories';
    $data = $this->read();
    var_dump($data);
}

$Category = new Category();
Bomber
Auteur

Voici le message d'erreur affiché désormais

( ! ) Parse error: syntax error, unexpected '$data' (T_VARIABLE), expecting function (T_FUNCTION) in C:\wamp\www\tuto_poo\models\Category.class.php on line 4
Call Stack

Time Memory Function Location

1 0.0000 245136 {main}( ) ..\index.php:0
2 0.0010 283200 Model::load( ) ..\index.php:6

Bonjour, ses une grossière erreur de part pardonnez moi le bon code :

<?php
require 'core.php' ;
$Category = Model::load('Category');
 $data = $Category->read();
 var_dump($data);
if(!empty($_POST))
{
$Category->save($_POST);
$_GET'id'] = $Category->id;
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="theme/style.css" type="text/css" media="screen" />
</head>
<body>
<h1> La programation orientée objet </h1>
<form method="post" action="index.php">
<?php 
if(isset($_GET'id']))
{
$id = $_GET"id"]; 
$Category->id=$id;
$Category->read();
$name = $Category->name;
$position = $Category->position;
}else
{
$id = $name = $position = "";
}

?>
<input type="hidden" name="id" value="<?php echo $id ; ?>"/>
<input type="text" name="name" value="<?php echo $name; ?>"/>
<input type="text" name="position" value="<?php echo $position; ?>"/>
<input type="submit" value="envoyer"/>
</form>

</body>
</html>

<?php
require 'core.php' ;
$Category = Model::load('Category');
if(!empty($_POST)) {
    $Category->save($_POST);
    $_GET'id'] = $Category->id;
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="theme/style.css" type="text/css" media="screen" />
</head>
<body>
<h1> La programation orientée objet </h1>
<form method="post" action="index.php">
    <?php 
        if(isset($_GET'id'])){
            $data = $Category->read();
            $id = $_GET"id"]; 
            $Category->id = $id; 
            $name = $data->name;
            $position = $data->position;
        } else {
            $id = $name = $position = "";
        }
    ?>
    <input type="hidden" name="id" value="<?php echo $id ; ?>"/>
    <input type="text" name="name" value="<?php echo $name; ?>"/>
    <input type="text" name="position" value="<?php echo $position; ?>"/>
    <input type="submit" value="envoyer"/>
</form>
</body>
</html>

Cordialement.

Bomber
Auteur

j'obtiens un tableau avec tous les résultats de ma table.
Mais lorsque j'entre un id dans l'url ou même après la validation d'un insert lorsque c'est censé me retourner les valeur name et position dans mon formulaire (l'insert se fait correctement); il me reste les erreurs

( ! ) Notice: Undefined property: Category::$name in C:\wamp\www\tuto_poo\index.php on line 35
Call Stack

Time Memory Function Location

1 0.0000 245352 {main}( ) ..\index.php:0

( ! ) Notice: Undefined property: Category::$position in C:\wamp\www\tuto_poo\index.php on line 36
Call Stack

Time Memory Function Location

1 0.0000 245352 {main}( ) ..\index.php:0

Cordialement

Bonjour,

<?php
require 'core.php' ;
$Category = Model::load('Category');
if(!empty($_POST)) {
    $extracted = extract($_POST);
    $Category->save($extracted);
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="theme/style.css" type="text/css" media="screen" />
</head>
<body>
<h1> La programation orientée objet </h1>
<form method="post" action="index.php">
    <?php 
        if(isset($_GET'id'])){
            $data = $Category->read();
            $id = $_GET"id"]; 
            $name = $data->name;
            $position = $data->position;
        } else {
            $id = $name = $position = "";
        }
    ?>
    <input type="hidden" name="id" value="<?php echo $id ; ?>"/>
    <input type="text" name="name" value="<?php echo $name; ?>"/>
    <input type="text" name="position" value="<?php echo $position; ?>"/>
    <input type="submit" value="envoyer"/>
</form>
</body>
</html>

Cordialement.

Bomber
Auteur

Encore des messages d'erreurs :

( ! ) Notice: Trying to get property of non-object in C:\wamp\www\tuto_poo\index.php on line 29
Call Stack

Time Memory Function Location

1 0.0000 244336 {main}( ) ..\index.php:0

( ! ) Notice: Trying to get property of non-object in C:\wamp\www\tuto_poo\index.php on line 30
Call Stack

Time Memory Function Location

1 0.0000 244336 {main}( ) ..\index.php:0

correspond à

$name = $data->name;
            $position = $data->position;

Bonjour,

<?php
require 'core.php' ;
$Category = Model::load('Category');
if(!empty($_POST)) {
    $extracted = extract($_POST);
    $Category->save($extracted);
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="theme/style.css" type="text/css" media="screen" />
</head>
<body>
<h1> La programation orientée objet </h1>
<form method="post" action="index.php">
    <?php 
        if(isset($_GET'id'])){
            $data = $Category->read();
            $id = $_GET"id"]; 
            $name = $data'name'];
            $position = $data'position'];
        } else {
            $id = $name = $position = "";
        }
    ?>
    <input type="hidden" name="id" value="<?php echo $id ; ?>"/>
    <input type="text" name="name" value="<?php echo $name; ?>"/>
    <input type="text" name="position" value="<?php echo $position; ?>"/>
    <input type="submit" value="envoyer"/>
</form>
</body>
</html>

Cordialement.

Bomber
Auteur

Toujours des messages d'erreurs

( ! ) Notice: Undefined index: name in C:\wamp\www\tuto_poo\index.php on line 29
Call Stack

Time Memory Function Location

1 0.0000 244920 {main}( ) ..\index.php:0

( ! ) Notice: Undefined index: position in C:\wamp\www\tuto_poo\index.php on line 30
Call Stack

Time Memory Function Location

1 0.0000 244920 {main}( ) ..\index.php:0

néanmoins le $_GET récupère bien l'id

Bonjour,

<?php
require 'core.php' ;
$Category = Model::load('Category');
if(!empty($_POST)) {
    $extracted = extract($_POST);
    $Category->save($extracted);
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="theme/style.css" type="text/css" media="screen" />
</head>
<body>
<h1> La programation orientée objet </h1>
<form method="post" action="index.php">
    <?php 
        if(isset($_GET'id'])){
            $data = $Category->read(array());
            $id = $_GET"id"]; 
            $name = $data'name'];
            $position = $data'position'];
        } else {
            $id = $name = $position = "";
        }
    ?>
    <input type="hidden" name="id" value="<?php echo $id ; ?>"/>
    <input type="text" name="name" value="<?php echo $name; ?>"/>
    <input type="text" name="position" value="<?php echo $position; ?>"/>
    <input type="submit" value="envoyer"/>
</form>
</body>
</html>

Cordialement.

Bomber
Auteur

Exactement la même erreur, rien ne change.

Bonjour,

<?php
require 'core.php' ;
$Category = Model::load('Category');
if(!empty($_POST)) {
    $extracted = extract($_POST);
    $Category->save($extracted);
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="theme/style.css" type="text/css" media="screen" />
</head>
<body>
<h1> La programation orientée objet </h1>
<form method="post" action="index.php">
    <?php 
        if(isset($_GET'id'])){
            $id = $_GET"id"]; 
            $data = $Category->read(array(
                'conditions' => array('id' => $id)
            ));         
            $name = $data->name;
            $position = $data->position;
        } else {
            $id = $name = $position = "";
        }
    ?>
    <input type="hidden" name="id" value="<?php echo $id ; ?>"/>
    <input type="text" name="name" value="<?php echo $name; ?>"/>
    <input type="text" name="position" value="<?php echo $position; ?>"/>
    <input type="submit" value="envoyer"/>
</form>
</body>
</html>

Cordialement.

Bonsoir, Sujet résolu ?

Cordialement.

Bomber
Auteur

Désolé je n'avais pas eu le temps de revenir,

Non, lorsque je passe directement l'id dans l'url j'obtiens l'erreur :

( ! ) Notice: Trying to get property of non-object in C:\wamp\www\tuto_poo\index.php on line 31
Call Stack

Time Memory Function Location

1 0.0010 244608 {main}( ) ..\index.php:0

( ! ) Notice: Trying to get property of non-object in C:\wamp\www\tuto_poo\index.php on line 32
Call Stack

Time Memory Function Location

1 0.0010 244608 {main}( ) ..\index.php:0

Sinon lors d'insert into j'obtiens ces erreurs:

( ! ) Warning: Invalid argument supplied for foreach() in C:\wamp\www\tuto_poo\models\Model.class.php on line 128
Call Stack

Time Memory Function Location

1 0.0000 246920 {main}( ) ..\index.php:0
2 0.0120 299168 Model->save( ) ..\index.php:7

( ! ) Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1' in C:\wamp\www\tuto_poo\models\Model.class.php on line 154
( ! ) PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 in C:\wamp\www\tuto_poo\models\Model.class.php on line 154

Cordialement

Bonjour,

<?php
require 'core.php' ;
$Category = Model::load('Category');
if(!empty($_POST)) {
    $extracted = extract($_POST);
    $Category->save($extracted);
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="theme/style.css" type="text/css" media="screen" />
</head>
<body>
<h1> La programation orientée objet </h1>
<form method="post" action="index.php">
    <?php 
        if(isset($_GET'id'])){
            $id = $_GET"id"]; 
            $data = $Category->read(array(
                'conditions' => array('id' => $id)
            ));         
            $name = $data'name'];
            $position = $data'position'];
        } else {
            $id = $name = $position = "";
        }
    ?>
    <input type="hidden" name="id" value="<?php echo $id ; ?>"/>
    <input type="text" name="name" value="<?php echo $name; ?>"/>
    <input type="text" name="position" value="<?php echo $position; ?>"/>
    <input type="submit" value="envoyer"/>
</form>
</body>
</html>

À la ligne 31 et 32, le "data->[str]" n'et pas un objet et donc il faut le passée comme cela "$data'STR']".

Cordialement.

Bomber
Auteur

Toujours des erreurs :

( ! ) Warning: Invalid argument supplied for foreach() in C:\wamp\www\tuto_poo\models\Model.class.php on line 128
Call Stack

Time Memory Function Location

1 0.0000 247256 {main}( ) ..\index.php:0
2 0.0110 299528 Model->save( ) ..\index.php:7

( ! ) Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1' in C:\wamp\www\tuto_poo\models\Model.class.php on line 154
( ! ) PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 in C:\wamp\www\tuto_poo\models\Model.class.php on line 154
Call Stack

Time Memory Function Location

1 0.0000 247256 {main}( ) ..\index.php:0
2 0.0110 299528 Model->save( ) ..\index.php:7
3 0.0120 301008 execute ( ) ..\Model.class.php:154

Cordialement

Bonjour,

<?php
require 'core.php' ;
$Category = Model::load('Category');
if(!empty($_POST)) {
    $Category->save($_POST);
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="theme/style.css" type="text/css" media="screen" />
</head>
<body>
<h1> La programation orientée objet </h1>
<form method="post" action="index.php">
    <?php 
        if(isset($_GET'id'])){
            $id = $_GET"id"]; 
            $data = $Category->read(array(
                'conditions' => array('id' => $id)
            ));         
            $name = $data'name'];
            $position = $data'position'];
        } else {
            $id = $name = $position = "";
        }
    ?>
    <input type="hidden" name="id" value="<?php echo $id ; ?>"/>
    <input type="text" name="name" value="<?php echo $name; ?>"/>
    <input type="text" name="position" value="<?php echo $position; ?>"/>
    <input type="submit" value="envoyer"/>
</form>
</body>
</html>

Cordialement.

Bomber
Auteur

L insert fonctionne bien, mais je ne récupère pas les champs envoyés (le remplissage à la suite de l'envoie) .

Et lorsque je passe l'id dans l'url j'obtiens

( ! ) Notice: Undefined index: name in C:\wamp\www\tuto_poo\index.php on line 30
Call Stack

Time Memory Function Location

1 0.0000 244184 {main}( ) ..\index.php:0

( ! ) Notice: Undefined index: position in C:\wamp\www\tuto_poo\index.php on line 31
Call Stack

Time Memory Function Location

1 0.0000 244184 {main}( ) ..\index.php:0

Cordialement

Bomber
Auteur

J ai ajouté à la fin de ma fonction read de ma class Model :

$data = $pre->fetchAll(PDO::FETCH_OBJ);
       // on parcours le tableau $data

        foreach($data as $key => $value)
        {
            $this->$key = $value;  
        }

au lieu de :

return $pre->fetchAll(PDO::FETCH_OBJ);

Du coup le message d'erreur disparait mais je ne récupère pas plus les champs rempli .

Bonjour,

Index.php :

<?php
require 'core.php' ;
$Category = Model::load('Category');
if(!empty($_POST)) {
    $ext = extract($_POST);
    $Category->save($ext);
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="theme/style.css" type="text/css" media="screen" />
</head>
<body>
<h1> La programation orientée objet </h1>
<form method="post" action="index.php">
    <?php 
        if(isset($_GET'id'])){
            $id = $_GET"id"]; 
            $data = $Category->read(array(
                'conditions' => array('id' => $id)
            ));         
            $name = $data'name'];
            $position = $data'position'];
        } else {
            $id = $name = $position = "";
        }
    ?>
    <input type="hidden" name="id" value="<?php echo $id ; ?>"/>
    <input type="text" name="name" value="<?php echo $name; ?>"/>
    <input type="text" name="position" value="<?php echo $position; ?>"/>
    <input type="submit" value="envoyer"/>
</form>
</body>
</html>

Model.class.php :

<?php
class Model {
    static $connections = array();
    public $conf = 'default'; // parametre de connection à choisir 
    public $table = false;
    public $db;
    public $primaryKey = "id";
    public $id;  

    public function __construct(){
        if($this->table === false) {
            $this->table = strtolower(get_class($this));
        }
        $conf = Config_bdd::$databases$this->conf];

        if(isset(Model::$connections$this->conf])) {
            $this->db = Model::$connections$this->conf];
            return true;
        }
        try{
            $options = array(
                PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_OBJ
            );
            $pdo = new PDO('mysql:host='.$conf'host'].';dbname='.$conf'dbname'], $conf'login'] , $conf'password'], $options);
            Model::$connections$this->conf] = $pdo;
            $this->db = $pdo;
        } catch(PDOException $e) {
            print('Erreur :'. $e->getMessage());
        }
    }

    function read($req = array()) {
        $sql = 'SELECT ';
        if(isset($req'fields'])) {
            if(is_array($req'fields'])) {
                $sql .= implode(', ', $req'fields']);
            } else {
                $sql .= $req'fields'];
            }
        } else {
            $sql .= '*';
        }
        $sql .= ' FROM '.$this->table. ' as '.get_class($this).' ';

        // Pour les jointures 
        if(isset($req'join'])) {
            foreach($req'join'] as $k => $v) {
                $sql .= 'LEFT JOIN '.$k.' ON '.$v.' ';
            }
        }
        // Pour les conditions
        if(isset($req'conditions'])) {
            $sql .= 'WHERE ';
            if(!is_array($req'conditions'])) {
                $sql .= $req'conditions'];
            } else {
                $cond = array();
                foreach($req'conditions'] as $k => $v) {
                    if(!is_numeric($v)) {
                        $v = '"'.@mysql_real_escape_string($v).'"';
                    }

                    $cond] = "$k=$v";
                } 
                $sql .= implode(' AND ', $cond);
            }
        }
        // Les ordres
        if(isset($req'order'])) {
            $sql .= ' ORDER BY '.$req'order'];
        }
        // Les limites
        if(isset($req'limit'])) {
            $sql .= ' LIMIT '.$req'limit'];
        } 
        $pre = $this->db->prepare($sql);
        $pre->execute();
        return $pre->fetchAll(PDO::FETCH_OBJ);
    }

    //Fonction sauvegarde

    public function save($data){
        $key = $this->primaryKey;
        $fields = ];
        $d = ]; 
        foreach($data as $k => $v){
            if($k != $this->primaryKey) {
                $fields] = "$k=:$k";
                $d":$k"] = $v; 
            } elseif(!empty($v)) {
                $d":$k"] = $v; 
            }
        }
        if(isset($data->$key) && !empty($data->$key)){
            $sql = 'UPDATE '.$this->table.' SET '.implode(',',$fields).' WHERE '.$key.'=:'.$key;
            $this->id = $data->$key; 
            $action = 'update';
        } else{
            $sql = 'INSERT INTO '.$this->table.' SET '.implode(',',$fields);
            $action = 'insert'; 
        }
        $pre = $this->db->prepare($sql); 
        $pre->execute($d);
        if($action == 'insert'){
            $this->id = $this->db->lastInsertId(); 
        }
    }  
}

Cordialement.

Bomber
Auteur

Je retombe sur l'erreur

( ! ) Notice: Undefined index: name in C:\wamp\www\tuto_poo\index.php on line 30
Call Stack

Time Memory Function Location

1 0.0000 244184 {main}( ) ..\index.php:0

( ! ) Notice: Undefined index: position in C:\wamp\www\tuto_poo\index.php on line 31
Call Stack

Time Memory Function Location

1 0.0000 244184 {main}( ) ..\index.php:0

Cordialement

Bonjour,

<?php
require 'core.php' ;
$Category = Model::load('Category');
if(!empty($_POST)) {
    $ext = extract($_POST);
    $Category->save($ext);
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="theme/style.css" type="text/css" media="screen" />
</head>
<body>
<h1> La programation orientée objet </h1>
<form method="post" action="index.php">
    <?php 
        if(isset($_GET'id'])){
            $id = $_GET"id"]; 
            $data = $Category->read(array(
                'conditions' => array('id' => $id)
            ));         
            $name = $data->name;
            $position = $data->position;
        } else {
            $id = $name = $position = "";
        }
    ?>
    <input type="hidden" name="id" value="<?= $id ; ?>"/>
    <input type="text" name="name" value="<?= $name; ?>"/>
    <input type="text" name="position" value="<?= $position; ?>"/>
    <input type="submit" value="envoyer"/>
</form>
</body>
</html>

Cordialement.

Bomber
Auteur

De nouveau des erreurs

( ! ) Notice: Trying to get property of non-object in C:\wamp\www\tuto_poo\index.php on line 31
Call Stack

Time Memory Function Location

1 0.0010 245232 {main}( ) ..\index.php:0

( ! ) Notice: Trying to get property of non-object in C:\wamp\www\tuto_poo\index.php on line 32
Call Stack

Time Memory Function Location

1 0.0010 245232 {main}( ) ..\index.php:0

Cordialement

Bonjour,

<?php
require 'core.php' ;
$Category = Model::load('Category');
if(!empty($_POST)) {
    $ext = extract($_POST);
    $Category->save($ext);
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="theme/style.css" type="text/css" media="screen" />
</head>
<body>
<h1> La programation orientée objet </h1>
<form method="post" action="index.php">
    <?php 
        if(isset($_GET'id'])){
            $id = $_GET"id"]; 
            $data = $Category->read(array(
                'conditions' => array('id' => $id)
            ));         
                        var_dump($data);
            //$name = $data->name;
            //$position = $data->position;
        } else {
            $id = $name = $position = "";
        }
    ?>
    <input type="hidden" name="id" value="<?= $id ; ?>"/>
    <input type="text" name="name" value="<?= $name; ?>"/>
    <input type="text" name="position" value="<?= $position; ?>"/>
    <input type="submit" value="envoyer"/>
</form>
</body>
</html>

Que retourne le tableaux ?

Cordialement.

Bomber
Auteur

Il me retourne les valeurs correspondantes dans la table.

Cordialement

Bonjour, pouvez-vous me le mettre dans les balise [code][\code] ? Cordialement.

Bomber
Auteur
array (size=1)
  0 => 
    object(stdClass)[4]
      public 'id' => string '16' (length=2)
      public 'name' => string 'Jeux video' (length=10)
      public 'position' => string '12' (length=2)

Voila

Bomber
Auteur

C'est bon ca fonctionne nikel,
pourquoi on se retrouve avec le [0] a mettre devant ?

Bonjour, ont ce retrouve avec le 0 car ses un deuxième tableau qui à été pris en compte.

Cordialement.

Bomber
Auteur

C'est ici que ça ce fait ?

$data = $Category->read(array(
                'conditions' => array('id' => $id)
            ));

Pourquoi un 0 , ce peut il qu' il y ai plusieurs tableaux ?
si oui comment savoir lequel appeler ?

Bonjour, le zéro et dû effectivement à ce tableau qui prends en premier un tableau, et pour c'es conditions un deuxième tableau, pour y remédier au zéro il faut faire une fonction qui permet de créer un tableau nommé et de l'extraire sur sont nom donnée.

exemple :

CategoryController.php

$this->loadModel('category');
$data = $Category->read(array(
    'conditions' => array('id' => $id)
));
$d'data'] = array($data);
$this->set($d);

ainsi il suifferais de faire un print($data'positions']);...

Cordialement.

Bomber
Auteur

En fait ce n'est pas bon, en effet j'ai de nouveau une erreur lors du save :

( ! ) Warning: Invalid argument supplied for foreach() in C:\wamp\www\tuto_poo\models\Model.class.php on line 118
Call Stack

Time Memory Function Location

1 0.0000 247080 {main}( ) ..\index.php:0
2 0.0100 298752 Model->save( ) ..\index.php:7

( ! ) Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1' in C:\wamp\www\tuto_poo\models\Model.class.php on line 144
( ! ) PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 in C:\wamp\www\tuto_poo\models\Model.class.php on line 144
Call Stack

Time Memory Function Location

1 0.0000 247080 {main}( ) ..\index.php:0
2 0.0100 298752 Model->save( ) ..\index.php:7
3 0.0100 300216 execute ( ) ..\Model.class.php:144

Cordialement

Bonsoir,

<?php
require 'core.php' ;
$Category = Model::load('Category');
if(!empty($_POST)) {
    $Category->save(
        'name' => $_POST'name'],
        'position' => $_POST'position']
        ]);
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="theme/style.css" type="text/css" media="screen" />
</head>
<body>
<h1> La programation orientée objet </h1>
<form method="post" action="index.php">
    <?php 
        if(isset($_GET'id'])){
            $id = $_GET"id"]; 
            $data = $Category->read(array(
                'conditions' => array('id' => $id)
            ));         
            $name = $data[0]->name;
            $position = $data[0]->position;
        } else {
            $id = $name = $position = "";
        }
    ?>
    <input type="hidden" name="id" value="<?= $id ; ?>"/>
    <input type="text" name="name" value="<?= $name; ?>"/>
    <input type="text" name="position" value="<?= $position; ?>"/>
    <input type="submit" value="envoyer"/>
</form>
</body>
</html>

Cordialement.

Bomber
Auteur

Le save se fait bien,
néanmoins je ne récupère pas le dernier id entré en bdd et lors de l'update c'est un insert avec un un nouvel id qui se fait ...

Cordialement

Bonjour,

<?php
require 'core.php' ;
$Category = Model::load('Category');
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="theme/style.css" type="text/css" media="screen" />
</head>
<body>
<h1> La programation orientée objet </h1>
<form method="post" action="index.php">
    <?php 
        if(isset($_GET'id'])){
            $id = $_GET"id"]; 
            if(!empty($_POST)) {
                $Category->save(
                    'id' => $id,
                    'name' => $_POST'name'],
                    'position' => $_POST'position']
                    ]);
            }
            $data = $Category->read(array(
                'conditions' => array('id' => $id)
            ));         
            $name = $data[0]->name;
            $position = $data[0]->position;
        } else {
            $id = $name = $position = "";
        }
    ?>
    <input type="hidden" name="id" value="<?= $id ; ?>"/>
    <input type="text" name="name" value="<?= $name; ?>"/>
    <input type="text" name="position" value="<?= $position; ?>"/>
    <input type="submit" value="envoyer"/>
</form>
</body>
</html>

Cordialement.

Bomber
Auteur

Ça n'entre même plus les données en insert ni en update, mais je les récupérè bien en entrant l'id dans l'url.
Cordialement

Bonjour, voici mais deux fonction personnel que j'ai fait lors d'un série de tutoriel :

<?php
    function save($db, $data) {
        $key = $this->pID;
        $fields = ];
        $d = ];
        foreach($data as $k => $v) {
            if($k != $this->pID) {
                $fields] = "$k=:$k";
                $d":$k"] = $v;
            } elseif(!empty($v)) {
                $d":$k"] = $v;
            }
        }
        $sql = 'INSERT INTO '.$db.' SET '.implode(',', $fields);
        $pre = $this->db->prepare($sql);
        $pre->execute($d);
        $this->id = $this->db->lastInsertId();
    }
    function update($db, $id, $data) {
        $key = $this->pID;
        $fields = ];
        $d = ];
        foreach($data as $k => $v) {
            if($k != $this->pID) {
                $fields] = "$k=:$k";
                $d":$k"] = $v;
            } elseif(!empty($v)) {
                $d":$k"] = $v;
            }
        }
        $sql = 'UPDATE '.$db.' SET '.implode(',', $fields).' WHERE '.$key.'=:'.$key;
        $pre = $this->db->prepare($sql);
        $pre->execute($d);
    }
//pID = primaryKey à modifier
?>

Ainsi pour un update :

$Database->update('Nom de la table', 'id du poste', 
                        'nom du champs de table' => 'donnee envoyez depuis un $_POST'   
                    ]);

Pour un insert :

$Database->save('Nom de la table', 
                        'nom du champs de table' => 'donnee envoyez depuis un $_POST'   
                    ]);

Cordialement.

Bomber
Auteur

je viens de faire un print_r($pre) avant l'execute lors d'un update et j'obtiens la requete suivante :

PDOStatement Object ( [queryString] => INSERT INTO categories SET name=:name,position=:position )

l'id n'est pas pris en compte , pourquoi ?

Bonjour, je ne sais pas trop.. ses assez étrange pour t'en il et bien appelé ?

Cordialement.

Bomber
Auteur

Qu'est ce qui est appelé ?
l'id ? Sa valeur apparait bien dans le formulaire lorsque j'examine l’élément.

Mais lorsque je valide mon update j'obtiens
la requete insert into et du coup le message d'erreur

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens' in C:\wamp\www\tuto_poo\models\Model.class.php on line 148
( ! ) PDOException: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in C:\wamp\www\tuto_poo\models\Model.class.php on line 148

Bonsoir, ça fait la même chose que moi, tenter les deux fonction que je vous et donnez plus en haut pour essayer :).

Cordialement.

Bomber
Auteur

Ou placez vous ces deux lignes

Ainsi pour un update

$Database->update('Nom de la table', 'id du poste', 
        'nom du champs de table' => 'donnee envoyez depuis un $_POST'   
    ]);

Pour un insert :

$Database->save('Nom de la table', 
        'nom du champs de table' => 'donnee envoyez depuis un $_POST'

Bonjour, à l'index.php

Cordialement.

Bomber
Auteur

Ca ne change rien;
On va laisser tomber la, et je vais re re re re reprendre de 0 X-)
Merci quand même

Cordialement

Bonsoir, faite juste le update vous avez besoin que d'update ?
Sinon voici pour vous :

<?php
require 'core.php' ;
$Category = Model::load('Category');
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="theme/style.css" type="text/css" media="screen" />
</head>
<body>
<h1> La programation orientée objet </h1>
<form method="post" action="index.php">
    <?php 
        if(isset($_GET'id'])){
            $id = $_GET"id"]; 
            if(!empty($_POST)) {
                $Category->save('category', $id, 
                    'id' => $id,
                    'name' => $_POST'name'],
                    'position' => $_POST'position']
                    ]); // Inseration
            }
            $data = $Category->read(array(
                'conditions' => array('id' => $id)
            ));         
            $name = $data[0]->name;
            $position = $data[0]->position;
        } else {
            $id = $name = $position = "";
        }
    ?>
    <input type="hidden" name="id" value="<?= $id ; ?>"/>
    <input type="text" name="name" value="<?= $name; ?>"/>
    <input type="text" name="position" value="<?= $position; ?>"/>
    <input type="submit" value="envoyer"/>
</form>
</body>
</html>

Et donc nous nous voulons INSERT / UPDATE alors voici :

<?php
require 'core.php' ;
$Category = Model::load('Category');
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="theme/style.css" type="text/css" media="screen" />
</head>
<body>
<h1> La programation orientée objet </h1>
<form method="post" action="index.php">
    <?php 
        if(isset($_GET'id'])){
            $id = $_GET"id"]; 
            if(!empty($_POST)) {
                if(empty($id)) { // L'id et vide alors ont insert
                    $Category->save('category', 
                        'id' => $id,
                        'name' => $_POST'name'],
                        'position' => $_POST'position']
                        ]);
                } else { // Id remplie donc ses update
                    $Category->update('category', $id, 
                        'id' => $id,
                        'name' => $_POST'name'],
                        'position' => $_POST'position']
                        ]);
                }
            }
            $data = $Category->read(array(
                'conditions' => array('id' => $id)
            ));         
            $name = $data[0]->name;
            $position = $data[0]->position;
        } else {
            $id = $name = $position = "";
        }
    ?>
    <input type="hidden" name="id" value="<?= $id ; ?>"/>
    <input type="text" name="name" value="<?= $name; ?>"/>
    <input type="text" name="position" value="<?= $position; ?>"/>
    <input type="submit" value="envoyer"/>
</form>
</body>
</html>

Cordialement.

Bomber
Auteur

Cela ne fonctionne pas non plus ^^

Bonjour, vous avez bien mis les deux fonction que je vous et donnée dans la class Model ? ^^

Cordialement.

Bonsoir,

Model.class.php

<?php
class Model {
    static $connections = array();
    public $conf = 'default'; // parametre de connection à choisir 
    public $table = false;
    public $db;
    public $primaryKey = "id";
    public $id;  

    public function __construct(){
        if($this->table === false) {
            $this->table = strtolower(get_class($this));
        }
        $conf = Config_bdd::$databases$this->conf];

        if(isset(Model::$connections$this->conf])) {
            $this->db = Model::$connections$this->conf];
            return true;
        }
        try{
            $options = array(
                PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_OBJ
            );
            $pdo = new PDO('mysql:host='.$conf'host'].';dbname='.$conf'dbname'], $conf'login'] , $conf'password'], $options);
            Model::$connections$this->conf] = $pdo;
            $this->db = $pdo;
        } catch(PDOException $e) {
            print('Erreur :'. $e->getMessage());
        }
    }

    function read($req = array()) {
        $sql = 'SELECT ';
        if(isset($req'fields'])) {
            if(is_array($req'fields'])) {
                $sql .= implode(', ', $req'fields']);
            } else {
                $sql .= $req'fields'];
            }
        } else {
            $sql .= '*';
        }
        $sql .= ' FROM '.$this->table. ' as '.get_class($this).' ';

        // Pour les jointures 
        if(isset($req'join'])) {
            foreach($req'join'] as $k => $v) {
                $sql .= 'LEFT JOIN '.$k.' ON '.$v.' ';
            }
        }
        // Pour les conditions
        if(isset($req'conditions'])) {
            $sql .= 'WHERE ';
            if(!is_array($req'conditions'])) {
                $sql .= $req'conditions'];
            } else {
                $cond = array();
                foreach($req'conditions'] as $k => $v) {
                    if(!is_numeric($v)) {
                        $v = '"'.@mysql_real_escape_string($v).'"';
                    }

                    $cond] = "$k=$v";
                } 
                $sql .= implode(' AND ', $cond);
            }
        }
        // Les ordres
        if(isset($req'order'])) {
            $sql .= ' ORDER BY '.$req'order'];
        }
        // Les limites
        if(isset($req'limit'])) {
            $sql .= ' LIMIT '.$req'limit'];
        } 
        $pre = $this->db->prepare($sql);
        $pre->execute();
        return $pre->fetchAll(PDO::FETCH_OBJ);
    }

    //Fonction sauvegarde

function save($db, $data) {
        $key = $this->primaryKey;
        $fields = ];
        $d = ];

        foreach($data as $k => $v) {
            if($k != $this->primaryKey) {
                $fields] = "$k=:$k";
                $d":$k"] = $v;
            } elseif(!empty($v)) {
                $d":$k"] = $v;
            }
        }

        $sql = 'INSERT INTO '.$db.' SET '.implode(',', $fields);

        $pre = $this->db->prepare($sql);
        $pre->execute($d);

        $this->id = $this->db->lastInsertId();

    }

    function update($db, $id, $data) {
        $key = $this->primaryKey;
        $fields = ];
        $d = ];

        foreach($data as $k => $v) {
            if($k != $this->primaryKey) {
                $fields] = "$k=:$k";
                $d":$k"] = $v;
            } elseif(!empty($v)) {
                $d":$k"] = $v;
            }
        }

        $sql = 'UPDATE '.$db.' SET '.implode(',', $fields).' WHERE '.$key.'=:'.$key;

        $pre = $this->db->prepare($sql);
        $pre->execute($d);
    } 
}

index.php

<?php
require 'core.php' ;
$Category = Model::load('Category');
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="theme/style.css" type="text/css" media="screen" />
</head>
<body>
<h1> La programation orientée objet </h1>
<form method="post" action="index.php">
    <?php 
        if(isset($_GET'id'])){
            $id = $_GET"id"]; 
            if(!empty($_POST)) {
                if(empty($id)) { // L'id et vide alors ont insert
                    $Category->save('category', 
                        'id' => $id,
                        'name' => $_POST'name'],
                        'position' => $_POST'position']
                        ]);
                } else { // Id remplie donc ses update
                    $Category->update('category', $id, 
                        'id' => $id,
                        'name' => $_POST'name'],
                        'position' => $_POST'position']
                        ]);
                }
            }
            $data = $Category->read(array(
                'conditions' => array('id' => $id)
            ));         
            $name = $data[0]->name;
            $position = $data[0]->position;
        } else {
            $id = $name = $position = "";
        }
    ?>
    <input type="hidden" name="id" value="<?= $id ; ?>"/>
    <input type="text" name="name" value="<?= $name; ?>"/>
    <input type="text" name="position" value="<?= $position; ?>"/>
    <input type="submit" value="envoyer"/>
</form>
</body>
</html>

Je viens de tester et tout et fonctionnel :) !

Cordialement.

Bomber
Auteur

Oui j'ai tout fait correctement il me semble,
mais ça ne fonctionne toujours pas.... -.-"

Bonsoir, qu'elle et votre version PHP ?

Cordialement.

Bomber
Auteur

la 5.5.12

Bonsoir, pouvez vous m'envoyez l'archive de votre site local que je jette un coup d'oeil ainsi qu'avec la BDD (base de donnée) que je fasse des test et que je puisse trouvé le vrai soucis ?

Cordialement.

Bomber
Auteur

Je veux bien mais comment je vous l'envoie ?

BOnsoir, par e-mail si vous le souhaitez : xen0ris@outlook.fr

Cordialement.

Bomber
Auteur

c'est envoyé

Cordialement

Bonsoir, alors voilà j'ai pas mal avancez et pas mal d'erreur effectivement, certaine chose n'allais pas j'ai terminé de fixé le problème je vous envois ça.

Cordialement.

Bonsoir,
petit fixe au niveau de l'index (Car ça n'update pas le bonne article je vérifie actuellement) :

<?php
require 'inc/includes.php' ;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="theme/style.css" type="text/css" media="screen" />
</head>
<body>

<h1> La programation orientée objet </h1>
<?php
    $Category = Model::load('Category'); // Ont charger "Category.class.php"
    if(isset($_GET'id'])) { // Un id à été appeller alors ont lie les donnée lié à cette ID
        $gID = $_GET'id'];
        $data = $Category->read(array(            
            'conditions' => array('id' => $gID)
        ));
        // var_dump($data);

        $id = $data[0]->id;
        $name = $data[0]->name;
        $position = $data[0]->position;
        if($_POST) {
            extract($_POST);   
            $Category->update('categories', $id, array(
                'id' => $id,
                'name' => $name,
                'position' => $position
            )); // On update (mettre à jours) les donnée postée via l'id
        }
    } else {
        $id = NULL; // Valeur par défaut: vide
        $name = NULL; // Valeur par défaut: vide
        $position = NULL; // Valeur par défaut: vide  

    }
    // Ont vérifie si il y à un envoi de formulaire
    if($_POST) {
        if(!empty($_POST)) { // Si poste n'es pas vide
            $Category->save('categories', array(
                'name' => $_POST'name'],
                'position' => $_POST'position']
            )); // On sauvegarde dans la base de donnée le nom et la position envoyez
        }
    }
?>
<form method="POST">
    <input type="hidden" name="id" value="<?= $id ; ?>">
    <input type="text" name="name" value="<?= $name; ?>">
    <input type="text" name="position" value="<?= $position; ?>">

    <input type="submit" value="envoyer"/>
</form>

</body>
</html>

Cordialement.

Bonjour stp j'ai besoin ton aide j'ai une probleme o niveau de chargement mon site chargement de mon site très lente plz aide moi c'est koi la solution voila le site j'attends votre reponse cordialement www.mprice.ma

Bonjour stp j'ai besoin ton aide j'ai une probleme o niveau de chargement mon site chargement de mon site très lente plz aide moi c'est koi la solution voila le site j'attends votre reponse cordialement www.mprice.ma

Bonjour, Najat contactez-moi par e-mail: xen0ris@outlook.fr

Cordialement.