3

I've been searching and can't find out how to grab data from a MySQL database using JSON in iOS. Of course this will require a PHP middle-man, but how to do all of this seems unsearchable at this point.

Please could someone help?

Thank you!

1 Answer 1

1

depending on your php version you can json_encode() the results of your MySQL query, or (as in the below) you can hand craft the JSON.

then in your ios, use a parser (I use SBJSON) and it will convert the JSON into an array or dictionary (depending on how you use it)...I haven't used JSONKit so can't comment on that aspect

EDIT: Oh, actually, is that the 'direction' you meant (receive JSON)? or did you want to submit JSON from iOS to initiate the query?

<?php
//connect to DB       
$query = "SELECT * FROM table_name"; 
$result = mysql_query("$query");
echo "{\"results\":";
if($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
echo "[";
    echo "{\"field_one\":\"".$row["field_one"]."\",";
    echo "\"field_two\":\"".$row["field_two"]."\",";
    echo "\"field_three\":\"".$row["field_three"]."\",";
    echo "\"field_four\":\"".$row["field_four"]."\"";
    echo "}";
}
else{
echo "\"no\"}";
exit;
}
while($row = mysql_fetch_array($data,MYSQL_ASSOC)){
    echo ",{\"field_one\":\"".$row["field_one"]."\",";
    echo "\"field_two\":\"".$row["field_two"]."\",";
    echo "\"field_three\":\"".$row["field_three"]."\",";
    echo "\"field_four\":\"".$row["field_four"]."\"";
    echo "}";
}
echo "]}";
?>
Sign up to request clarification or add additional context in comments.

3 Comments

Great answer. Espacially with the handwritten JSON. I like it. :-D
Cheers, I need to send and receive data -- placing and viewing data from my iOS fields into and from the MySQL server. I'll have a read, I appreciate the help. Will reply once I've gone through this
thanks. The one drawback is that if your content has certain characters, you also have to escape or replace those with unicode like: function accentToUni($string){ $string=str_replace("\n","\\n",$string); $string=utf8_encode($string); $string=str_replace("ç","\\u00E7",$string); $string=str_replace("è","\\u00E8",$string); $string=str_replace("ä","\\u00E4",$string); return $string; } and then wrap each $row["n"] in that function

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.