Doe Doe - 3 months ago 11
Ajax Question

Where like syntax error in mysql inside php file

I have made a dropdown menu where I let the user to chose a letter in html. Then according to this letter must be outputed all the names selected from my mysqli database which start with this letter. For this I use ajax and php. Here is my code:



html>

<head>
<title>Title</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table,
td,
th {
border: 1px solid black;
padding: 5px;
}
th {
text-align: left;
}
</style>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("results").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("POST", location.href, true); /*"presta_prova.php"*/
/* send the content-type header */
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

/* my mistake here, this should be like this rather than object literal. */
xmlhttp.send('q=' + str);

}
}
</script>
</head>

<body>
<?php $q=i ntval($_GET[ 'q']); echo "kjo eshte q: " . $q; $con=mysqli_connect( 'localhost', 'root', 'evolvia2016', 'presta_prova'); if (!$con) { die( 'Could not connect: ' . mysqli_error($con)); } ?>
<form>
<select name="users" onchange="showUser( this.value )">
<option value="">Scegliete una lettera:</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
</form>
<br>
<div id="txtHint"><b>Vedi qui i tipi ti marche:</b>
</div>
<table id='results'>
<tr>
<th>Marca</th>
<th>Descrizione</th>
</tr>
<?php $sql="SELECT * FROM presta_prova WHERE marca LIKE 'B%' " ; //$sql="SELECT * FROM presta_prova WHERE marca LIKE '$q%' " ; $result=mysqli_query($con,$sql); while($row=mysqli_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row[ "marca"] .
"</td>"; echo "<td>" . $row[ "descrizione"] . "</td>"; echo "</tr>"; } echo "</table>"; ?>
</table>
</body>
<?php mysqli_close($con); ?>

</html>





Everything is OK if instead of this line:

$sql="SELECT * FROM presta_prova WHERE marca LIKE '".$q%."' ";


I use this line:

$sql="SELECT * FROM presta_prova WHERE marca LIKE 'B%' ";


But I want the output not to be static and output all the names starting with B, but I want to output the names starting with the letter chosen by the user.
Have I done something wrong in this line syntax:

$sql="SELECT * FROM presta_prova WHERE marca LIKE '".$q%."' ";


Can someone help me to fix this error?Sorry but I'm new at ajax and php. Thanks!

Answer

The % character should be in your SQL statement, not in your PHP code.

$sql="SELECT * FROM presta_prova WHERE marca LIKE '".$q."%' ";