Monday 16 July 2018

Getting the First Word of a String with MySQL

Getting the First Word of a String with MySQL

I was recently assigned the task of getting the first word from a field in a MySQL table. In my case it was getting the first part of a customers postcode. Following a quick look through the MySQL reference manual I was guided towards the SUBSTRING_INDEX()function. By using this function I was able to select the first part of the string by using an SQL query like so:

  1. SELECT SUBSTRING_INDEX(`postcode`, ' ', 1) AS postcodeOutward FROM `customers`  
Here I am passing the function three parameters; the table column name in question, the delimiter (in our case a space is being used), and the count of delimiters from the start of the string at which to stop at.
Should you want to loop through or use this information in PHP you can then do something like so:

  1. $query = "SELECT SUBSTRING_INDEX(`postcode`, ' ', 1) AS postcodeOutward FROM `customers`";  
  2. $result = mysql_query($queryor die(mysql_error());  
  3. while ($row=mysql_fetch_assoc($result)) {  
  4.     echo $row['postcodeOutward']."\n";  
  5. }  

0 comments:

Post a Comment