I'm trying to bind two parameters received with AJAX into a prepared statement, using both of them as terms for a comparison. When I try to use both of them the query goes wrong, while if I remove the one obtained by a select it works. Is the select a possible reason of the failure? Because in the page in which I perform the query, the string arrives correctly, with its correct value.
$.ajax({
url:"ricerca.php",
type: "GET",
data: { azione:"ricerca",
tcr1:$("#testoPrimoCampo").val(),
cr1:$("#primoCampoRicerca").val(),
tcr2:$("#testoSecondoCampo").val(),
cr2:$("#secondoCampoRicerca").val(),
ordinamento: ord},
success:function(result){
alert(result);
$("#risRicerca").html(result);
},
error: function(richiesta,stato,errori){
$("#divElenco").html("<strong>Chiamata fallita:</strong>"+stato+" "+errori);
}
});
<form action="ricerca.php" method="GET">
<fieldset>
<legend>Ricerca calciatori</legend>
<select id="primoCampoRicerca" name="primoCampoRicerca">
<option value="codicecalciatore">Codice</option>
<option value="cognomenome">Cognome e nome</option>
<option value="squadra">Squadra</option>
<option value="ruolo">Tipo</option>
<option value="valore">Valore</option>
</select>
</fieldset>
</form>
<div id = "risRicerca"></div>
ricerca.php
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = '';
/*** database name ***/
$database_name = 'esempio';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$database_name", $username, $password);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
if (isset($_GET['azione'])) {
if (!empty($_GET['tcr1']) && $_GET['tcr1']!='') {
try {
echo($_GET["cr1"]);
$sql = $dbh->prepare("SELECT * FROM calciatori WHERE ? = ?");
$sql->bindParam(1, $_GET['cr1']);
$sql->bindParam(2, $_GET['tcr1']);
$sql->execute();
echo '<table> <tr> <td>Codice</td> <td>Cognome e Nome</td> <td>Squadra</td> <td>Ruolo / Tipo</td> <td>Valore</td> </tr>';
$i = 0;
$res = $sql->fetchAll();
foreach ($res as $row){
$i=$i+1;
echo '<tr>';
echo '<td>' . $row['codicecalciatore'] . '</td>';
echo '<td>' . $row['cognomenome'] . '</td>';
echo '<td>' . $row['squadra'] . '</td>';
echo '<td>' . $row['ruolo'] . '</td>';
echo '<td>' . $row['valore'] . '</td>';
echo '</tr>';
}
echo '</table>';
echo("$i");
/*** close the database connection
$dbh = null;***/
}
catch(PDOException $e)
{
echo $e->getMessage();
}
} else {
echo("Campi vuoti");
$_SESSION['istruzione'] = '';
}
} else {
echo("Azione non settata");
$_SESSION['istruzione'] = '';
}
?>
Sorry if varialbes' names are in italian, I hope it won't be a problem, thank's.