I'm trying to make a select in php with pdo.
It's working with a lot of req but not when I'm using a like, example :
Query:
SELECT * FROM projets WHERE `identifiantProjetRattachement` LIKE "%PC13287%" ORDER BY "identifiantProjetDSR"
This is my php code :
<?php
function requette($requette,$table)
{
$bdd = new PDO('mysql:host=localhost;dbname=spb', 'root', '');
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='$table';";
$req = $bdd->query($sql);
$titres = array();
while($resultat = $req->fetch())
{
array_push($titres,$resultat['COLUMN_NAME']);
}
// ON A LES TITRES DONC ON PASSE AU CONTENU
$sql = $requette;
$req = $bdd->query($sql);
$retour = "";
$cpt = 0;
$nbLigne = 0;
while($resultat = $req->fetch())
{
$nbLigne++;
$retour .= "<tr><td class='boutonTouteLaCase' onclick='surlignerLigneProjets(this);'></td><td>$nbLigne</td>";
for($cpt=0;$cpt<count($titres);$cpt++)
{
if($titres[$cpt] != "id")
$retour .= "<td>".utf8_encode($resultat[$titres[$cpt]])."</td>";
}
$retour .= "</tr>";
}
echo $retour;
}
$requette = htmlentities($_POST['requette']);
$table = htmlentities($_POST['table']);
echo $requette."<br/>";
echo $table."<br/>";
echo requette($requette,$table);?>
Do you think it's an accent problem ? Or a problem due to a ' ?
PS : This req works on phpmyadmin.
Thanks for all.
The problem is that you are invalidating your own queries:
...
$requette = htmlentities($_POST['requette']);
$table = htmlentities($_POST['table']);
echo $requette."<br/>";
echo $table."<br/>";
echo requette($requette,$table);
Note that you are using htmlentities($requette)
and later you try to run that exact query:
$sql = $requette;
$req = $bdd->query($sql);
And that query will look like:
SELECT * FROM projets WHERE identifiantProjetRattachement
LIKE "%PC13287%" ORDER BY "identifiantProjetDSR"
For the example that you mentioned. An invalid query.
So you should only use htmlentities()
when you output your variable to the screen, but you should not change the variable itself:
// Don't do this:
// $requette = htmlentities($_POST['requette']);
// $table = htmlentities($_POST['table']);
// just do this:
echo htmlentities($requette)."<br/>";
echo htmlentities($table)."<br/>";
echo requette($requette,$table);
Apart from that I will assume that you only have access to this yourself as you are running user-provided sql queries directly so that would be very dangerous if an unauthorized user had access to that.