开发者

How to select results from a MySQL DB using Strpos instead of a While statement?

开发者 https://www.devze.com 2023-03-06 06:51 出处:网络
I开发者_JS百科 have been using the PHP function strpos to find results containing the characters of a string from a DB:

I开发者_JS百科 have been using the PHP function strpos to find results containing the characters of a string from a DB:

User Types: Hel
Results: Hello, Hell, Helli, Hella

I have it basically query the entire table:

$result = mysql_query("SELECT * FROM Events");

And then ran a while statement to see which of the results contain the characters of the input:

while($row = mysql_fetch_array($result))
 {

    $pos = strpos($row['Title'], $q);
        if ($pos === false) {
        } else {
            echo $row['Title'];
        }
  }

And to find the number of results, I was using:

$n = $n++

Inside of the while statement.

I know you can use:

$num_rows = mysql_num_rows($result);

To find the number of results if you are only selecting those values from the database, but do I have to use this while statement to find the number of results that match the strpos function? Or can I put the strpos in to the Select From query?

Any help is greatly appreciated,

Taylor


This seems highly inefficient. Why wouldn't you simply let the database do the searching for you?

$result = mysql_query("SELECT * FROM Events WHERE Title LIKE '" . addslashes($q) . "%'");

Then just loop through the results.


You could update your SQL to something like

SELECT * 
FROM Events
WHERE Title LIKE '{your_string}%'

Make sure to filter for sql injection though.


You can use the LIKE statement:

SELECT * FROM Events WHERE field1 LIKE '%something%'

Where the special % characters say "Anything of any length"; so we're searching for something (or nothing), then the string, then something (or nothing.) For example, searching for %f% will match foo, off, and affirmative.

Just as general advice, I recommend that you use php's MySQLi class; it's an improved version (hence the i), and provides prepared statements, so you won't have to worry too much about SQL injections.

0

精彩评论

暂无评论...
验证码 换一张
取 消