0

How can I grab data from a database using an mySQL query which will get all rows that start with a certain string, for example;

$string = 'WS';

mysql_query("SELECT * FROM `table` WHERE `name` STARTS WITH '$string'");

something like the above

Curtis
  • 2,646
  • 6
  • 29
  • 53
  • To follow the answer below, look into the % operator when using LIKE. It is a directional wildcard used exactly for this purpose. http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html – Kai Qing Sep 24 '13 at 17:07

2 Answers2

6

you mean LIKE

SELECT * FROM `table` WHERE `name` LIKE 'WS%'
John Woo
  • 258,903
  • 69
  • 498
  • 492
  • but that'll retrieve all results have **WS** in it's value, I only want the ones that have WS at the start – Curtis Sep 24 '13 at 17:07
  • no, that will only retrieve where they begin with WS and have absolutely anything following WS – Kai Qing Sep 24 '13 at 17:08
  • 2
    @Curtis That would only happen if you wrote `'%WS%'`. – Barmar Sep 24 '13 at 17:08
  • consider also parameterizing the value to avoid sql injection. [How to *prevent SQL injection* in PHP?](http://stackoverflow.com/questions/60174/how-to-prevent-sql-injection-in-php) – John Woo Sep 24 '13 at 17:11
0
SELECT * FROM `table` WHERE `name` LIKE 'WS%'

it will fetch only those values those have ws at the start...and not all values..try it once

Let me see
  • 5,063
  • 9
  • 34
  • 47