0

I'm posting a JSONArray.toString() to a php file. The JSONArray contains a set of id values. I want to make a mysql query that only returns rows that have an id contained in the jsonarray. My method below isn't working. Is there another way?

$jsonarray= $_POST["ids"];
$query = mysql_query("SELECT * FROM table WHERE id IN $jsonarray")or die(mysql_error());
1
  • That's because the JSONArray.toString() probably ends up with [1, 2, 3, 4] thus the query is not valid. You should decode the json using json_decode and then implode the result with comma... Commented Dec 5, 2012 at 16:18

2 Answers 2

5

It'd help if we had an example of the JSON array, however, you should decode the JSON array into a comma separated list to use with IN.

$jsonarray = $_POST["ids"];
$ids = implode(",", json_decode($jsonarray,true));

$query = mysql_query("SELECT * FROM table WHERE id IN ($ids)")or die(mysql_error());


Also, you should be using mysqli or PDO_MySQL for new development:

It is recommended to use either the mysqli or PDO_MySQL extensions. It is not recommended to use the old mysql extension for new development. A detailed feature comparison matrix is provided below. The overall performance of all three extensions is considered to be about the same. Although the performance of the extension contributes only a fraction of the total run time of a PHP web request. Often, the impact is as low as 0.1%.

Related Reading:

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

1 Comment

I would add to your answer that it is better to use mysqli or PDO as mysql_ API is discouraged and will be deprecated.
0

echo out the contents of $jsonarray and you will see the error when you check the syntax of the MySQL query

2 Comments

actually I think the user would learn a lot more by doing this but I accept it was a bit vague. he/she will paste in code from @christains answer and not understand what they were doing wrong.
It's all OK, I agree with You, but this is not an answer to the question.

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.