0

I have a table that with name of key_words with one column call keywords. i want to retrieve keywords from database as random and show in Meta Keywords in header for better SEO .
i found a code here that was written by "smdrager" and tank from him.his code works good but written as array. i changed it to connect database but does not works. it show all keywords in table and repeat keywords.
anybody can help me to achieve my goal? thanks all

function get_keywords(){
 // $keywords=array('keyword1','keyword2','keyword3','keyword4','keyword5'); written by "smdrager"
include('config.php');     // Connect to Database
$query = mysql_query("SELECT keywords FROM key_words");
$all_entries = array();
while ($result = mysql_fetch_array($query)) {
$all_entries[] = $result[1]; 
$keywords= $result;}

if (count($keywords)<10)
$max=count($keywords);
else
 $max=10;
$rand_keys = array_rand($keywords, $max);
foreach($rand_keys as $vals){
 $keyword[]=$keywords[$vals];
}
echo implode(", ", $keyword);
}
?>
unforgiven
  • 27
  • 6

1 Answers1

0

As you told that it show all keywords and repeat them them i suggest use

  SELECT DISTINCT `keyword` FORM `key_words` 

and if you don't want to fetch all results than use limit

 SELECT DISTINCT `keyword` FORM `key_words` LIMIT 10 

I suggest to you use a column selected set their values 0 if not set to any page or 1 for already set to the page than

SELECT DISTINCT `keyword` FORM `key_words` WHERE selected = `0` LIMIT 10 

please prefer mysqli or PDO for this .

gauravK
  • 197
  • 1
  • 2
  • 12
  • thanks for your attention,my issue is when i use query in stead of array code that i did remark, function "array_rand" dose not effect in code and shows all keywords. but when i use this code : `code $keywords=array('keyword1','keyword2','keyword3','keyword4','keyword 5');` some keywords show as random and works good. i saved some keywords in field of keyword as film,video art,video,comedy movie. why does code work with array but with query not ? please trim my code to work. it's vital for me. thanks again – unforgiven Jun 30 '16 at 13:10
  • @unforgiven because mysql_fetch_array() return single row as output try to print_r($result) than see – gauravK Jun 30 '16 at 13:15
  • with print_r output :`code [0] => film,video art,video,comedy, movie [keywords] => film,video art,video,comedy, movie `. what should i do now? i changed above code to use array .i use `code $all_entries = array();` – unforgiven Jun 30 '16 at 13:32
  • @unforgiven [see this i hope this will help](http://stackoverflow.com/questions/5229501/how-get-all-values-in-a-column-using-php) – gauravK Jun 30 '16 at 13:37
  • Dear @gauravK,thanks.with you link i solved this issue finally . thanks again – unforgiven Jun 30 '16 at 14:13