php - Using volley to retrieve data(multiple rows) from mysql -
i'm creating quiz app , have retrive question display.this php , java code.i'll store data in array.i'm not able fetch data sql table.
stringrequest stringrequest = new stringrequest(request.method.post,inserturl, new response.listener<string>() { @override public void onresponse(string response) { try { jsonarray=new jsonarray(response); jsonobject jsonobject=jsonarray.getjsonobject(0); for(int k=0;k<jsonarray.length();k++) { question[k]=jsonobject.getstring("question"); opta[k]=jsonobject.getstring("optiona"); optb[k]=jsonobject.getstring("optionb"); optc[k]=jsonobject.getstring("optionc"); optd[k]=jsonobject.getstring("optiond"); ans[k]=jsonobject.getstring("answers"); } } catch (jsonexception e) { e.printstacktrace(); } } }, new response.errorlistener() { @override public void onerrorresponse(volleyerror error) { toast.maketext(quiz.this,error.tostring(),toast.length_long ).show(); } }){ @override protected map<string, string> getparams() throws authfailureerror { map<string,string> params = new hashmap<string,string>(); params.put(item_course,data); return super.getparams(); } }; requestqueue requestqueue = volley.newrequestqueue(this); requestqueue.add(stringrequest);
this php code
<?php require 'initquiz.php'; global $connect; $response = array(); $course=$_post["course"]; $query = "select * questions course='$course'"; $result= mysqli_query($connect,$query) or die(mysqli_error($connect)); $response= array(); if (mysql_num_rows($result) > 0) { while ($row = mysql_fetch_array($result)) { $question = $row[0]; $optiona = $row[2]; $optionb= $row[3]; $optionc = $row[4]; $optiond= $row[5]; $answers= $row[6]; array_push($response,array("question"=>$question,"optiona"=>$optiona,"optionb"=>$optionb,"optionc"=>$optionc,"optiond"=>$optiond,"answers"=>$answers)); } } echo json_encode($response); ?>
issues code:
- you mixed
mysql_*
,mysqli_*
extension - your code vulnerable sql injection, use prepared statements
- your fetch simpler
- try avoid
select *
, instead select specific fields
try approach:
$response = []; if(isset( $_post["course"])){ $mysqli = new mysqli("host", "user", "password", "db"); if ($mysqli->connect_errno) { printf("connect failed: %s\n", $mysqli->connect_error); exit(); } $query = "select * questions course = ?"; if ($stmt = $mysqli->prepare($query)) { $stmt->bind_param("s", $_post["course"]); $stmt->execute(); while ($row = $stmt->fetch_assoc()) { $response['data'][] = $row; } $response['success'] = true; } $mysqli->close(); }else{ $response['data'] = 'no course sent'; $response['success'] = false; } echo json_encode($response);
Comments
Post a Comment