简体   繁体   中英

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.

Use LIKE:


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

尝试使用这个

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

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();
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM