Page 1 sur 1

syntax mytsql

Posté : 09 sept. 2011, 11:31
par artotal
Bonjour,
j'ai une erreur de syntaxe mais je ne vois pas laquelle ,
SELECT * FROM profmusique WHERE codePostalProf LIKE '".$departement."%' 
		AND (instrumentPrincipalProf='".$_POST['instrumentRechercher']."' 
		OR discipline1Prof='".$_POST['instrumentRechercher']."' 
		OR discipline2Prof='".$_POST['instrumentRechercher']."'
		OR discipline3Prof='".$_POST['instrumentRechercher']."'
		OR discipline4Prof='".$_POST['instrumentRechercher']."') 
		AND mailProf NOT LIKE ('%mailEnAttente') 
		ORDER BY villeProf ASC
le message d'erreur de phpmyadmin

Code : Tout sélectionner

#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 'instrumentRechercher']."' OR discipline1Prof='".$_POST['instrumentRechercher'' at line 2
Merci

Re: syntax mytsql

Posté : 09 sept. 2011, 12:45
par Cyrano
S'il y a une apostrophe dans la valeur de $_POST['instrumentrechercher'], c'est normal. Ce code illustre bien comment faire pour ouvrir bien grand la porte à une injection SQL :mrgreen:

Suggestion de correction :
<?php
$instrument = mysql_real_escape_string($_POST['instrumentRechercher']);
$sql  = "SELECT * ".
        "FROM profmusique ".
        "WHERE codePostalProf LIKE '". $departement ."%' ".
        "  AND mailProf NOT LIKE ('%mailEnAttente') ".
        "  AND( ".
        "       instrumentPrincipalProf='". $instrument ."' ".
        "    OR discipline1Prof='". $instrument ."' ".
        "    OR discipline2Prof='". $instrument ."' ".
        "    OR discipline3Prof='". $instrument ."' ".
        "    OR discipline4Prof='". $instrument ."' ".
        ") ".
        "ORDER BY villeProf ASC";
À adapter bien entendu si tu n'utilises pas MySQL mais un autre SGBD puisque le problème sera le même. Autre option, utiliser PDO et une requête préparée, avec deux paramètres pour tes variables, ça va passer tout seul sans bobo.

Je te suggère aussi l'utilisation de var_dump pour voir de quoi a l'air la requête générée qui sera envoyée à ton SGBD :
echo("<pre>Requête SQl générée :\n");
var_dump($sql);
echo("</pre>\n");
C'est parfois fort instructif ;)