Jump to content

MySQL Query to Search City Name by First Letter


daveh33

Recommended Posts

I have a mysql database with a table which contains two fields -areaid,area

 

I am trying to return a set of results in a while statement which will get any records in my table which start with the letters A,B,C,D,E

 

This is my code..

 


$start="A";
$end="E";
$query=mysql_query("SELECT * FROM mytable WHERE area LIKE 'A%%%'");
while ($data=mysql_fetch_array($query)) {
$areaid=$data['areaid'];
$area=$data['area'];
echo "<a href=\"area.php?id=$areaid\">$area</a><br /><br />";
}

 

I know my query isn't quite right, but im not sure if this is the best way to do this?

 

Any help is appreciated

Link to comment
Share on other sites

ok you will need to form a where query string within a loop (i cannot work out an sql syntax for this);

 

eg:

 

<?php

$fieldname = "area";
$tablename = "mytable";

// alphabet string of characters for character position reference
$alphabet = "abcdefghijklmnopqrstuvwxyz";

$start="A";
$end="D";

// get alphabet charcter pos (start)
$substr_a = strpos($alphabet,strtolower($start));

// get alphabet character position (end)
$substr_b = strpos($alphabet,strtolower($end))+1;

// Create array of letters by getting all the letter from $start to $end and splitting the string every 1 character.
$Queries = str_split(substr($alphabet,$substr_a,$substr_b-$substr_a),1);

// Set count to save execution time by not putting in for loop argument
$x = count($Queries);

// Preset $where variable
$where = array();

// Loop to loop-thru each character in the $Queries array
For($i=0;$i<$x;$i++){

// Each loop add a where query to the array $where
$where[] = "UCASE($fieldname) LIKE '".strtoupper($Queries[$i])."%'";
}

// Implode the query array ($where) and into a string and insert " AND " between each array item in the string.
$where = "WHERE ".implode(" OR ",$where);

// resulting mysql statement
echo("SELECT * FROM $tablename ".$where);
?>

 

hope this helps,

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.