2

I´m trying using php to generate a set of "{URL.callback}" to use in javascript. By using database. Here is my code:

$sql="select * from search where keywords LIKE '$bb%' ORDER BY keywords ";  

     $result=mysql_db_query($dbname,$sql);

     echo $_GET["callback"] . "({ t:\"$t\", r:[";
    while ( $rs=mysql_fetch_array($result))    {
        $keywords=$rs[keywords];

         echo "" ."\"$keywords\"".","." ";
    }

echo"] })";

This is the code it returns:

({ t:"", r:["example1", "example2", "example3",] })

Everything seemed to be correct except the (,) in the end (after "example3") that I want to get rid. because it´s not correct and can not be use with that.

The question is: How to generate it correctly ? How to get rid the last (,) ?

6
  • I got the solution from "refp"...Now I´m very happy :))) Commented Dec 18, 2011 at 20:05
  • I also got the good solution from "Indranil", "Billy Moon" Thank you so much for help. Commented Dec 18, 2011 at 21:14
  • If you got the solution from @refp, then mark his answer as accepted (that little tick under vote count for his answer) :) Commented Dec 18, 2011 at 21:24
  • "Shoogle" is also give me the solution. Thank you again.. Commented Dec 18, 2011 at 21:32
  • Ahh now I know how to mark the answer that was correct. But every answers here are correct...So sad I can mark only one time :S BUt anyway want to say thank you for everybody ! Commented Dec 18, 2011 at 21:35

5 Answers 5

3

Instead of generating the JSON yourself use json_encode to do the heavy lifting for you.

$keywords = array ();

while ( $rs=mysql_fetch_array($result)) {
  $keywords[] = $rs['keywords'];
}

echo json_encode ($keywords);

Preferred solution

Though if you plan on using json_encode append $keywords to your other set of data and use json_encode on the whole structure.

$json_data = array (
  't' => '',
  'r' => array ()
);

while ( $rs=mysql_fetch_array($result)) {
  $json_data['r'][] = $rs['keywords'];
}

echo "(".json_encode ($json_data).")";

If you'd like to do it yourself there are a few (rather clean) options available, see the snippets below.


Append all retrieved keywords to an array and use join with ',' as delimiter to form a string after your while loop   $keyword_array = array ();

while ($rs=mysql_fetch_array($result))    {   
  $keywords=$rs[keywords];

  $keyword_array = "\"$keywords\"";
}

echo join (', ', $keywords);

Use mysql_num_rows before your while loop to get the number of rows in $result, and don't append a , when you are processing the last element.

$n_rows = mysql_num_rows ($result);

for ($i =1; $rs = mysql_fetch_array ($result); ++$i) {
  $keywords=$rs[keywords];

  echo "\"$keywords\"";

  if ($i != $n_rows)
    echo ", ";
}
Sign up to request clarification or add additional context in comments.

3 Comments

OHHHHHHHH MMMMMMMMYYYY GODDDDD I got it :) THANKS SO MUCH
@AleksanderPaitoon Please make sure to flag the post as accepted as that will mark your question as solved, and make me tremendously happy ;)
I´m very new here. I´ve tried to post at the end of my question above that I got the solution from you :))) And I clicked on flag and post that I got the solution from you refp. :))) Thank you so much.
1

Try this:

$output = '';
while ( $rs=mysql_fetch_array($result))    {
    $keywords=$rs[keywords];

     $output .= "" ."\"$keywords\"".","." ";
}
$output = substr($output, 0, -2);
echo $output;

2 Comments

to Indranil Thanks for help, but i still get the (,) in the end.
Your answer is also give the solution, I will post for you in the end of my question...Thank you so much for this
0

Solution

Create data structure (multi-dimensional array) within PHP and let json_encode() generate JS data structure.

Example

It could look like this:

$sql="select * from search where keywords LIKE '$bb%' ORDER BY keywords ";  
$result=mysql_db_query($dbname,$sql);

$data = array(
    't' => $t,
    'r' => array(),
);

while ( $rs=mysql_fetch_array($result)) {
    $data['r'][] = $rs['keywords'];
};

and then display it like that:

echo $_GET["callback"].'('.json_encode($data).');';

11 Comments

Thanks for your kindness. I actually got the solution from "refp" But I will try yours also wait....
@AleksanderPaitoon: You are welcome. I suggest you should follow his original solution to use json_encode() instead of manually creating JS representation of your data. It will do the job better and simplify your code at the same time.
Hi although I got the solution already but I want to say thank you that you also help me. I appreciate it. I also tried your code. Seemed like the (,) is gone. But I got the strange encode like this "u0e2b\u0e32\u0e04\u0e21 2553" Maybe I don´t know what to do more...I want to say thank you again :)
@AleksanderPaitoon: This is probably because there were some specials characters inside keywords. You can test how it works eg. here: codepad.org/LQQVQHjw.
Thanks Tadeck...Your answer is also give me the solution. I will post at the end of my question that you gave me the solution also :) Sorry that I was stupid but after I test it...worked fine...
|
0

Hope this works for you

$sql="select * from search where keywords LIKE '$bb%' ORDER BY keywords ";  

 $result=mysql_db_query($dbname,$sql);

 echo $_GET["callback"] . "({ t:\"$t\", r:[";
$keywords_print = array();
while ( $rs=mysql_fetch_array($result))    {
    $keywords=$rs[keywords];

     $keywords_print[] = "\"$keywords\"";
}
echo implode(",",$keywords_print);
echo"] })";

2 Comments

Thanks for your kindness. I actually got the solution from "refp" But I will try yours also wait....
Hi..Thanks for your answer. It also give me the solution... I will post at the end of my question tat you also help me find the solution.
0

I think the cleanest way, is to create an array of elements, then implode them with a , as separator.

// added initial `"`
echo $_GET["callback"] . "({ t:\"$t\", r:[\"";
while ( $rs=mysql_fetch_array($result))    {
    $keywords=$rs[keywords];
    $arr[] = $keywords;
}
echo implode('", "', $arr);
// added closing `"`
echo "\"] })";

4 Comments

Thanks for your kindness. I actually got the solution from "refp" But I will try yours also wait....
I will, with baited breath :)
I can tell you without executing the above that it sadly will not work, you are appending each $keywords to $arr but then using $keywords when you implode, probably a little bit of typo thingie!
Hi, Billy moon...I found that your answer is also give the solution for me...I will post at the end of my question that you also give the good solution for me.

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.