I’ve been asked to add a small AJAX feature to a clients site. Basically I have a MySQL table with 3 fields:
- id
- product
- name
The idea of the site is that the user starts typing the “name”, and the products show up after a couple of keystrokes. My query looks like this:
$query = mysql_query("SELECT product FROM mytable WHERE name LIKE '%".$search."%'");
Everything works, except when there is a space in the “name”. For example, if I have a name called “Coca Cola”, the script successfully lists the product when I type “Coca”, but as soon as I type the space, it no longer returns any rows.
I’ve searched everywhere for a solution. I understand that the space is interpreted as a separator of some kind, but can I get the database to interpret the space as … well … a space? If not, is there a better way of doing what I want to accomplish?
EDIT:
I ran it in PHPMyAdmin and it actually returns the correct results, which leads me to believe that it must be something in the PHP. Theres the full script:
$search = $_GET['search'];
$already_echoed = array();
if (!ereg('[^A-Za-z0-9]', $search) && strlen($search) > 2) {
$query = mysql_query("SELECT product FROM mytable WHERE name LIKE '%".$search."%'");
if (mysql_num_rows($query) > 0) {
echo '<h4>Suggestions:</h4><ul>';
while ($product = mysql_fetch_array($query)) {
if (!in_array($product['product'], $already_echoed)) {
$getProduct = mysql_query("SELECT name, shortname FROM products WHERE id='".$product['product']."'");
$product2 = mysql_fetch_array($getProduct);
echo '<li><a href="http://' . $product2['shortname'] . '.mydomain.com">' . $product2['name'] . '</a></li>';
$already_echoed[] = $product['product'];
}
}
echo '</ul>';
}
}
Looks like you’re excluding spaces from the allowed list of characters. I don’t speak much PHP and can’t be arsed to go look at the docs.