1

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 ($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.

  1. Why it is storing same string two times? There is no any other row in db similar to the term nature.
  2. Why it is storing only first letter in the array? Shouln't it store "nature" instead of "n"?

Please help me fixing this.

2 Answers 2

7

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?

Sign up to request clarification or add additional context in comments.

Comments

3

use mysql_fetch_assoc instead of mysql_fetch_array

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.