sqlite vers sql

Mammouth du PHP | 790 Messages

20 déc. 2011, 16:25

tranquillement ça avance et je pense comprendre...
j'ai donc 2 table, une qui enregistre les moyennes pour l'affichage et l'autre qui enregistre 1 votes par champs avec toutes les infos utiles pour n'autoriser qu'un votes par personne.

quand on enregistre un nouvel individu, aucun vote n’existe donc a l’affichage de sa page, une requete crée un premier champ dans chaque table pour permettre l’affichage...

voila le code:
                try
                {
                    //connexion
                    $dbh = new PDO('mysql:host='.$PARAM_hote.';dbname='.$PARAM_nom_bd, $PARAM_utilisateur, $PARAM_mot_passe);
                    $dbh->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                    // protection de la chaine chien pour une requete
                    $this->chien = $dbh->quote($vote_chien);

                    // js cherche si le chien a le vote avec l'ip admin
                    $vote_chien_check = $dbh->query("SELECT id FROM vote WHERE ip_user='admin' AND id_chien=$this->chien LIMIT 0, 1");
                                   
                    // si $vote_chien_check est vide
                    if(empty($vote_chien_check))
                    {
                        // je crée un premier vote dans la table vote
                        $dbh->exec("INSERT INTO vote (id_question, id, ip_user, id_chien, note) 
                                     VALUES ('1', '1', 'admin', $this->chien, '')");
                        // je crée un premier vote dans la table moyenne_votes
                        $dbh->exec("INSERT INTO moyenne_votes (id_chien, id_question, nb_votes, moyenne) 
                                                       VALUES ($this->chien, '1', '', '')");                        
                        
                    } 
                    
                    // ???                    
                    else 
                    {
                        $this->average = $vote_chien_check->fetchColumn(1);
                    }

                    // ???
                    $this->votes = ($dbh->query("SELECT nb_votes FROM moyenne_votes WHERE id_chien=$this->chien")->fetchColumn()-1);
		}catch( PDOException $exception ){
				die($exception->getMessage());
		}
		$dbh = NULL;		
	}

mon soucis la c'est la vérification de $vote_chien_check, si je met un "if(!empty($vote_chien_check))" le système semble marcher mais chaque fois que j'actualise la page, les champs sont créer de nouveaux et les votes augmentes et si je met "if(empty($vote_chien_check))" ce qui me parait plus correct la rien ne marche ???
Les fautes de grammaire et d'orthographe contenu dans mes postes sont sous copyright, vous pouvez les utiliser pour un usage personnelle mais vous ne devrez en aucun cas les utiliser a des fins commercial sans une autorisation écrite de ma part.

Mammouth du PHP | 790 Messages

22 déc. 2011, 13:20

bon, j'ai réussi quelques modifs mais ce create table me pose problème, je vous fait vois le code d'origine:
<?php
class rating{

	public $average = 0;
	public $votes;
	public $status;
	public $table;
	private $path;
	
	function __construct($table){
		try{
			$pathinfo = pathinfo(__FILE__);
			$this->path = realpath($pathinfo['dirname']) . "/database/ratings.sqlite";
			$dbh = new PDO("sqlite:$this->path");
			$this->table = $dbh->quote($table);
			// check if table needs to be created
			$table_check = $dbh->query("SELECT * FROM $this->table WHERE id='1'");
			if(!$table_check){
				// create database table
				$dbh->query("CREATE TABLE $this->table (id INTEGER PRIMARY KEY, rating FLOAT(3,2), ip VARCHAR(15))");
				$dbh->query("INSERT INTO $this->table (rating, ip) VALUES (0, 'master')");				
			} else {
				$this->average = $table_check->fetchColumn(1);
			}
			$this->votes = ($dbh->query("SELECT COUNT(*) FROM $this->table")->fetchColumn()-1);
		}catch( PDOException $exception ){
				die($exception->getMessage());
		}
		$dbh = NULL;		
	}

	function set_score($score, $ip){
		try{
			$dbh = new PDO("sqlite:$this->path");
			$voted = $dbh->query("SELECT id FROM $this->table WHERE ip='$ip'");
			if(sizeof($voted->fetchAll())==0){
				
				$dbh->query("INSERT INTO $this->table (rating, ip) VALUES ($score, '$ip')");
				$this->votes++;
				
				//cache average in the master row
				$statement = $dbh->query("SELECT rating FROM $this->table");
				$total = $quantity = 0;
				$row = $statement->fetch(); //skip the master row
				while($row = $statement->fetch()){
					$total = $total + $row[0];
					$quantity++;
				}
				$this->average = round((($total*20)/$quantity),0);
				$statement = $dbh->query("UPDATE $this->table SET rating = $this->average WHERE id=1");
				$this->status = '(thanks!)';
			} else {
				$this->status = '(already scored)';
			}
			
		}catch( PDOException $exception ){
				die($exception->getMessage());
		}
		$dbh = NULL;
	}
}

function rating_form($table){
	$ip = $_SERVER["REMOTE_ADDR"];
	if(!isset($table) && isset($_GET['table'])){
		$table = $_GET['table'];
	}
	$rating = new rating($table);
	$status = "<div class='score'>
				<a class='score1' href='?score=1&table=$table&user=$ip'>1</a>
				<a class='score2' href='?score=2&table=$table&user=$ip'>2</a>
				<a class='score3' href='?score=3&table=$table&user=$ip'>3</a>
				<a class='score4' href='?score=4&table=$table&user=$ip'>4</a>
				<a class='score5' href='?score=5&table=$table&user=$ip'>5</a>
			</div>
	";
	if(isset($_GET['score'])){
		$score = $_GET['score'];
		if(is_numeric($score) && $score <=5 && $score >=1 && ($table==$_GET['table']) && isset($_GET["user"]) && $ip==$_GET["user"]){
			$rating->set_score($score, $ip);
			$status = $rating->status;
		}
	}
	if(!isset($_GET['update'])){ echo "<div class='rating_wrapper'>"; }
	?>
	<?php print_r($rating);?>
	
	<div class="sp_rating">
		<div class="rating">Rating:</div>
		<div class="base"><div class="average" style="width:<?php echo $rating->average; ?>%"><?php echo $rating->average; ?></div></div>
		<div class="votes"><?php echo $rating->votes; ?> votes</div>
		<div class="status">
			<?php echo $status; ?>
		</div>
	</div>
	<?php
	if(!isset($_GET['update'])){ echo "</div>"; }
}

if(isset($_GET['update'])&&isset($_GET['table'])){
	rating_form($_GET['table']);
}
?>
si je fait un <?php print_r($rating);?>, j'obtiens:
rating Object ( [average] => 80.0 [votes] => 1 [status] => [table] => '1' [path:rating:private] => C:\wamp\www\vote\rating/database/ratings.sqlite )
rating Object ( [average] => 0.0 [votes] => 0 [status] => [table] => '2' [path:rating:private] => C:\wamp\www\vote\rating/database/ratings.sqlite )
rating Object ( [average] => 100.0 [votes] => 1 [status] => [table] => '3' [path:rating:private] => C:\wamp\www\vote\rating/database/ratings.sqlite )


et le code modifié pour mon systeme:
<?php
class rating{

    public $average = 0;
    public $votes;
    public $status;
    public $table;

function __construct($table)
{
    $hote='localhost';           
    $nom_bd='aaaa';
    $utilisateur='root';             
    $mot_passe='';        

    try
    {   
        //connexion
        $dbh = new PDO('mysql:host='.$hote.';dbname='.$nom_bd, $utilisateur, $mot_passe);
        $dbh -> setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this->table = $dbh->quote($table);	

        // recherche si un champ pour ce chien et cette question existe
        $table_check = $dbh->query("SELECT id_chien FROM vote WHERE id_chien=$this->table AND id_question='1'");
        $dnn = $table_check->fetch();	

        // test si $dnn contient un id_chien
        if(empty($dnn)) 
        {
            // je crée un premier vote dans la table vote
            $dbh->exec("INSERT INTO vote (id_question, id, ip_user, id_chien, note) VALUES ('1', '1', 'systeme', $this->table, '')");				
            // je crée un premier vote dans la table moyenne_votes pour enregistrer les moyennes
            $dbh->exec("INSERT INTO moyenne_votes (id_chien, id_question, nb_votes, moyenne) VALUES ($this->table, '1', '', '')"); 
        } 
        else 
        {
            $this->average = $table_check->fetchColumn(1);
        }
        
        // calcul du nombre de votes
        $this->votes = ($dbh->query("SELECT COUNT(*) FROM vote WHERE id_chien=$this->table")->fetchColumn()-1);

    }
        catch( PDOException $exception )
    {
        die($exception->getMessage());
    }
    $dbh = NULL;		
}





function set_score($score, $ip)
{
    try
    {
        //connexion
        $dbh = new PDO('mysql:host='.$hote.';dbname='.$nom_bd, $utilisateur, $mot_passe);
        $dbh -> setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        // recherche id vote avec (id-chien + id_question + ip_user)
	$voted = $dbh->query("SELECT id FROM votes WHERE id_chien=$this->table AND ip='$ip'");
	$dnn_2 = $voted->fetch();	
        
        // si cette combinaison n'existe pas
        if(empty($dnn)) {
				
	// j'insert le vote
        $dbh->exec("INSERT INTO vote (id_question, id, ip_user, rating, id_chien) VALUES ('1', '1', '.$ip.', $score, $this->table)");
	$this->votes++;
		
        // ???
	$statement = $dbh->query("SELECT rating FROM vote WHERE id_chien=$this->table");
	$total = $quantity = 0;
	$row = $statement->fetch();
	while($row = $statement->fetch())
        {
            $total = $total + $row[0];
            $quantity++;
	}
	$this->average = round((($total*20)/$quantity),0);
        $statement = $dbh->exec("UPDATE vote SET rating=$this->average WHERE id_chien=$this->table");
        $this->status = '(thanks!)';
	} 
        else 
        {
            $this->status = '(already scored)';
	}
			
	}catch( PDOException $exception ){
            die($exception->getMessage());
	}
	$dbh = NULL;
	}
   }

function rating_form($table){
	$ip = $_SERVER["REMOTE_ADDR"];
	if(!isset($table) && isset($_GET['table'])){
		$table = $_GET['table'];
	}
	$rating = new rating($table);
	$status = "<div class='score'>
				<a class='score1' href='?score=1&table=$table&user=$ip'>1</a>
				<a class='score2' href='?score=2&table=$table&user=$ip'>2</a>
				<a class='score3' href='?score=3&table=$table&user=$ip'>3</a>
				<a class='score4' href='?score=4&table=$table&user=$ip'>4</a>
				<a class='score5' href='?score=5&table=$table&user=$ip'>5</a>
			</div>
	";
	if(isset($_GET['score'])){
		$score = $_GET['score'];
		if(is_numeric($score) && $score <=5 && $score >=1 && ($table==$_GET['table']) && isset($_GET["user"]) && $ip==$_GET["user"]){
			$rating->set_score($score, $ip);
			$status = $rating->status;
		}
	}
	if(!isset($_GET['update'])){ echo "<div class='rating_wrapper'>"; }
	?>


	<div class="sp_rating">
		<div class="rating">Rating:</div>
		<div class="base"><div class="average" style="width:<?php echo $rating->average; ?>%"><?php echo $rating->average; ?></div></div>
		<div class="votes"><?php echo $rating->votes; ?> votes</div>
		<div class="status">
			<?php echo $status; ?>
		</div>
	</div>
	<?php
	if(!isset($_GET['update'])){ echo "</div>"; }
}

if(isset($_GET['update'])&&isset($_GET['table'])){
	rating_form($_GET['table']);
}

?>
et si je fait:<?php print_r($rating);?>, j'obtiens:

rating Object ( [average] => [votes] => 0 [status] => [table] => '1' )
rating Object ( [average] => [votes] => 0 [status] => [table] => '2' )
rating Object ( [average] => [votes] => 0 [status] => [table] => '3' )

j'arrive pas a m'en sortir, quelqu'un peut il m'aidé svp ? #-o
Les fautes de grammaire et d'orthographe contenu dans mes postes sont sous copyright, vous pouvez les utiliser pour un usage personnelle mais vous ne devrez en aucun cas les utiliser a des fins commercial sans une autorisation écrite de ma part.