Doe Doe - 1 year ago 65
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:


table {
width: 100%;
border-collapse: collapse;
th {
border: 1px solid black;
padding: 5px;
th {
text-align: left;
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
} 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;
};"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);


<?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)); } ?>
<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>
<div id="txtHint"><b>Vedi qui i tipi ti marche:</b>
<table id='results'>
<?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>"; ?>
<?php mysqli_close($con); ?>


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 Source

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download