Flix Flix - 4 years ago 128
Java Question

ANDROID&PHP - How to display JSONArray from MySql using PHP

The code that I use to displaying value of table into JSONArray below


include 'dbconfig.php';
$con = new mysqli($servername, $username, $password, $dbname);
if (mysqli_connect_errno())
echo "Failed to connect to MySQL: " . mysqli_connect_error();

$query = "select id,ask from pertanyaan";

$result = mysqli_query($con,$query);

$rows = array();
while($r = mysqli_fetch_array($result)) {
$rows[] =$r;
echo json_encode(array_values($rows));


and the JSONArray output is like this

[{"0":"1","id":"1","1":"pertanyaan ke 1","ask":"pertanyaan ke 1"},{"0":"2","id":"2","1":"pertanyaan ke 2","ask":"pertanyaan ke 2"},{"0":"3","id":"3","1":"pertanyaan ke 3","ask":"pertanyaan ke 3"},{"0":"4","id":"4","1":"pertanyaan ke 4","ask":"pertanyaan ke 4"},{"0":"5","id":"5","1":"pertanyaan ke 5","ask":"pertanyaan ke 5"}]

but everytime i try that URL to display in android, i got an error that say

Value <html><body<>script of type java.lang.String cannot be converted to JSONArray

but when i create new API with the same output here into android studio, its work fine,

did i use wrong code to encode JSON from PHP?

Answer Source


HttpURLConnection has no JavaScript support.

Your call

String req = "http://zxccvvv.cuccfree.com/send_data.php";
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

fails, because http://zxccvvv.cuccfree.com/send_data.php seems to use JavaScript to redirect to http://www.zxccvvv.cuccfree.com/send_data.php.


Call the redirect target directly to avoid the need for JavaScript:

String req = "http://www.zxccvvv.cuccfree.com/send_data.php";
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download