DroidMatt
DroidMatt

Reputation: 183

Retrieving rows based on a substring on PHP-MySQL

<?php
//$query = $_POST['query'];
$query = 'TI';

$conn = mysql_connect($mysql_host, $mysql_user, $mysql_password);
mysql_select_db($mysql_database, $conn);

$q=mysql_query("SELECT * FROM productTbl WHERE productName = '$query%'");
while($e=mysql_fetch_assoc($q))
    $output[]=$e;

print(json_encode($output));
mysql_close();
?>

My user would have to key in a certain string into a textbox from Android and POST to my PHP. On the PHP side, how do I retrieve the rows according to the POST-ed string, let say the string 'TI' ? I tried this, but it returns null.

Upvotes: 0

Views: 113

Answers (3)

Vikram
Vikram

Reputation: 8333

for wildcards you have to use the like key word, something like:

<?php
//$query = $_POST['query'];
$query = 'TI';

$conn = mysql_connect($mysql_host, $mysql_user, $mysql_password);
mysql_select_db($mysql_database, $conn);

$q=mysql_query("SELECT * FROM productTbl WHERE productName like '$query%'");
while($e=mysql_fetch_assoc($q))
    $output[]=$e;

print(json_encode($output));
mysql_close();
?>

Upvotes: 0

botzko
botzko

Reputation: 630

Try to use this

$q=mysql_query("SELECT * FROM productTbl WHERE productName LIKE '" . $query . "%'");

Upvotes: 1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

Use LIKE:


$query = mysql_real_escape_string($query); //better to be safer
SELECT * FROM productTbl WHERE productName LIKE '$query%'

Upvotes: 2

Related Questions