I want to select some data from db and store in an array. Suppose I have a column "keyword" in my db table. I want to select all rows where keyword column is like "nature".
I am trying following code:
<?
$term= "nature";
$arr = array();
$sql = "select keyword from keywords where keyword LIKE '%$term%'";
$result = mysql_query($sql) or die(mysql_error());
$rows = mysql_fetch_array($result);
foreach 开发者_C百科($rows as $row){
array_push($arr, $row['keyword']);
}
print_r($arr); //output: Array ( [0] => n [1] => n )
?>
So the result from db should return only one keyword 'nature' which i need to store in array.
- Why it is storing same string two times? There is no any other row in db similar to the term nature.
- Why it is storing only first letter in the array? Shouln't it store "nature" instead of "n"?
Please help me fixing this.
Should be something like
$term = "nature";
$arr = array();
$sql = "select keyword from keywords where keyword LIKE '%$term%'";
$result = mysql_query($sql) or die(mysql_error());
while( $row = mysql_fetch_assoc( $result ) ) {
arr[] = $row[ 'keyword' ];
}
In your solution you only fetch the first record from the result-set as numeric indexed array.
Btw - you are aware that a LIKE-query starting with a wildcard cannot make use of any index?
use mysql_fetch_assoc
instead of mysql_fetch_array
精彩评论