I just start to use php webservice.I want to take all data in 'urun' table just sending 'id' Here is my code and i dont know how to solve it.
if($_GET["function"] == "getUrun"){
if(isset($_GET["id"]) && $_GET["id"] != ""){
$id = $_GET["id"];
$kategoriid =$_GET["kategoriid"];
$urunadi =$_GET["urunadi"];
$urunfiyati =$_GET["urunfiyati"];
$aciklama =$_GET["aciklama"];
$where="";
$where = "id='".$id."' AND kategoriid='".$kategoriid."' AND urunadi='".$urunadi."' AND urunfiyati='".$urunfiyati."' AND aciklama='".$aciklama."'";
$result = mysql_query("SELECT * FROM urun WHERE ".$where."");
$rows = array();
if($r=mysql_fetch_assoc($result))
{
$rows[] = $result;
$data = json_encode($rows);
echo "{ \"status\":\"OK\", \"getUrun\": ".$data." }";
}else{
echo "{ \"status\":\"ERR: Something wrong hepsi\"}";}
}else{
echo "{ \"status\":\"ERR: Something wrongs hepsi\"}";}
}
It should be:
if ($result) {
$rows = array();
while ($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode(array('status' => 'OK', 'getUrun' => $rows));
} else {
echo json_encode(array('status' => 'ERR: Something wrong hepsi'));
}
You need to get all the results in an array, and then encode the whole thing. You should also use json_encode for the containing object, don't try to create JSON by hand.
Related
I'm trying to send an array of data from PHP to ajax. I'm using echo json_encode to do it. When I do that, I try 'console.log(data)' to see the response data but it not show anything. How can I get it to display the data? I really don't know what I'm missing here. I have this script:
var scard = $('#cardid').val();
$.ajax({
type: 'GET',
url: 'cardapi.php?scard=' + scard,
success: function (data) {
console.log($.parseJSON(data));
console.log(data);
}
});
And here is my code for cardapi.php
if(isset($_GET["scard"])){
$scard = $_GET["scard"];
$data = array();
$sql = "SELECT * FROM training_record WHERE cardref_no='$scard'";
$q = sqlsrv_query($conn, $sql);
while($rw = sqlsrv_fetch_array($q, SQLSRV_FETCH_ASSOC)){
array_push($data,[
"employee_no" => $rw["employee_no"],
"dept_id" => $rw["dept_id"],
"name_th" => $rw["name_th"],
"surname_th" => $rw["surname_th"],
"signed_status" => 1,
]);
}
echo json_encode($data);
}
So I try to follow this echo json_encode() not working via ajax call
It still not show anything. Please tell me why?
Thank you.
You may try the following:
Always check the result from the sqlsrv_query() execution.
Always try to use parameterized statements. Function sqlsrv_query() does both statement preparation and statement execution, and can be used to execute parameterized queries.
Check the result from the json_encode() call.
Fix the typing errors ("signed_status" => 1, should be "signed_status" => 1 for example).
Sample script, based on your code:
<?php
if (isset($_GET["scard"])) {
$scard = $_GET["scard"];
$data = array();
$sql = "SELECT * FROM training_record WHERE cardref_no = ?";
$params = array($scard);
$q = sqlsrv_query($conn, $sql, $params);
if ($q === false) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
while ($rw = sqlsrv_fetch_array($q, SQLSRV_FETCH_ASSOC)) {
$data[] = array(
"employee_no" => $rw["employee_no"],
"dept_id" => $rw["dept_id"],
"name_th" => $rw["name_th"],
"surname_th" => $rw["surname_th"],
"signed_status" => 1
);
}
$json = json_encode($data);
if ($json === false) {
echo json_last_error_msg();
exit;
}
echo $json;
}
?>
i want this json format in php but i unable to do this.
{
"couresList_PVP": [
{
"pvp_ad_chptr_id": "9",
"pvp_ad_chptr_un_id": "1526249608",
"pvp_ad_chptr_name": "54654",
"offer_chapter_PVP": [
{
"pvp_ad_chptr_offr_id": "4",
"pvp_ad_chptr_un_id": "1526249608",
"pvp_ad_chptr_offr_un_id": "Offer-1526249608"
},
{
"pvp_ad_chptr_offr_id": "3",
"pvp_ad_chptr_un_id": "1526249608",
"pvp_ad_chptr_offr_un_id": "Offer-1526249608"
}]
},]
}
my PHP code is here. how I will do this? I'll get JSON response but different array not in a single with the array in array.
$sql = mysqli_query($this->db,"SELECT * from `pvp_admin_chptr_list` order by pvp_ad_chptr_id desc");
if(mysqli_num_rows($sql) > 0){
while($res=mysqli_fetch_assoc($sql)){
$url=$this->site_url.'images_console/chapter_banner_console/'.$res['pvp_ad_chptr_banner'];
$video=$this->site_url.'video_console/'.$res['pvp_ad_chptr_video_name'];
$images=array('pvp_ad_chptr_banner'=>$url,'pvp_ad_chptr_video_name'=>$video);
$data['couresList_PVP'][]=array_merge($res,$images);
$ofr_sql = mysqli_query($this->db,"SELECT * from `pvp_admin_chptr_offers` where pvp_ad_chptr_un_id='$res[pvp_ad_chptr_un_id]' order by pvp_ad_chptr_offr_id desc");
if(mysqli_num_rows($ofr_sql) > 0){
while($ofr_res=mysqli_fetch_assoc($ofr_sql)){
$data['offer_chapter_PVP'][]=$ofr_res;
}
}else{
$data['offer_chapter_PVP'][]=array("status"=>"No Data FOund");
}
}
//$data2=array_merge($data['couresList_PVP'],$data['offer_chapter_PVP']);
//$data[]=array_push( $data['couresList_PVP'],$data['offer_chapter_PVP']);
//$data=
// If success everything is good send header as "OK" and user details
$this->response($this->json($data), 200);
}
you can use combination of array and then encode it in json. please check below code.
$response = array();
$responseObj = array();
$courseList = array();
$courseArr = array();
while($res=mysqli_fetch_assoc($sql)){
$courseList['pvp_ad_chptr_id'] = $res['id'];
$courseList['pvp_ad_chptr_un_id'] = $res['pvp_ad_chptr_un_id'];
$courseList['pvp_ad_chptr_name'] = $res['pvp_ad_chptr_name'];
$ofr_sql = mysqli_query($this->db,"SELECT * from `pvp_admin_chptr_offers` where pvp_ad_chptr_un_id='$res[pvp_ad_chptr_un_id]' order by pvp_ad_chptr_offr_id desc");
if(mysqli_num_rows($ofr_sql) > 0){
while($ofr_res=mysqli_fetch_assoc($ofr_sql)){
$courseList['offer_chapter_PVP'][]=$ofr_res;
}
}else{
$courseList[$i]['offer_chapter_PVP'][]=array("status"=>"No Data FOund");
}
$courseArr[] = $courseList;
}
$response['couresList_PVP'] = $courseArr;
$responseObj = $response;
echo '<pre>';
echo json_encode($responseObj);
echo '</pre>';
I am trying to display a single row data using mysqli.
The query is
$getfield = mysqli_query($con,"select name from as_users where user_id=34");
if (mysqli_num_rows($getfield) > 0)
{
while($rowpwd = mysqli_fetch_array($getfield))
{
echo $rowpwd['name'];
}
}
if I print then i get
echo '<pre>';
print_r(mysqli_fetch_array($getfield));
echo '</pre>';
Array
(
[0] => abc
[name] => abc
)
But getting the name inside the while loop doesn't work.
Any help is highly appreciated.
Just try this:
$getfield = mysqli_query($con,"select name from as_users where user_id=34");
if (mysqli_num_rows($getfield) > 0)
{
$rowpwd = mysqli_fetch_array($getfield)['name'];
echo $rowpwd;
}
OR
$getfield = mysqli_query($con,"select name from as_users where user_id=34");
if (mysqli_num_rows($getfield) > 0)
{
$rowpwd = mysqli_fetch_array($getfield);
echo $rowpwd['name'];
}
Try this:
$getfield = mysqli_query($con,"select name from as_users where user_id=34");
if (mysqli_num_rows($getfield) > 0)
$whatYouWant = array();
{
while($rowpwd = mysqli_fetch_array($getfield))
{
//echo $rowpwd['name'];
$whatYouWant[] = $rowpwd['name'];
}
}
echo '<pre>';
print_r($whatYouWant);
echo '</pre>';
Change:
mysqli_fetch_array
To: If you want key of row
mysqli_fetch_assoc
To:If you want index of row
mysqli_fetch_row
i used an exsiting code from a tutorial and need to change it.
The original code doesnt use an array, but i need it.
In my index.php i am calling the function with a tag:
else if ($tag == 'getinvbykost') {
$kstalt = $_POST['kstalt'];
$get = $db->GetInvByKost($kstalt);
if ($get != false) {
// echo json with success = 1
$response["success"] = 1;
$response["ean"] = $get["ean"];
$response["name"] = $get["name"];
$response["betriebsdatenalt"] = $get["betriebsdatenalt"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "nicht erfolgreich";
echo json_encode($response);
}
}
the function GetInvByKost($kstalt); is defined in DB_Functions.php.
the part is:
public function GetInvByKost($kstalt) {
$result = mysql_query("SELECT ean, name, betriebsdatenalt FROM geraete WHERE kstalt='$kstalt' AND accepted='0'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
while ($result = mysql_fetch_assoc($result)){
}
return $result;
//echo $result[1];
}
else {
// user not found;
return false;
}
}
the problem is, the function GetInvByKost returns an array.
the part in the index.php
$response["success"] = 1;
$response["ean"] = $get["ean"];
$response["name"] = $get["name"];
$response["betriebsdatenalt"] = $get["betriebsdatenalt"];
isnt made for an array, only for a single line.
how do i can get the values in the array to build my output?
mysql_fetch_assoc($result) returns a flat array. This means you can't access returned array by a key. So $get["ean"] is wrong and $get[1] is correct. You can access result of mysql_fetch_assoc($result) only by index, not key. You have SELECT ean, name, betriebsdatenalt... in your query, so index of "ean" is equal to 0, "name" is equal to 1 and so on. Therefore, 3 parts of your code should be change in this way:
`$get["ean"]` => ` $get[0]`
`$get["name"]` => `$get[1]`
`$get["betriebsdatenalt"]` => `$get[2]`
Update:
So, the index.php file should be like this:
else if ($tag == 'getinvbykost') {
$response = array();
$kstalt = $_POST['kstalt'];
$get = $db->GetInvByKost($kstalt);
if ($get != false) {
// echo json with success = 1
$response["success"] = 1;
$response["ean"] = $get[0];
$response["name"] = $get[1];
$response["betriebsdatenalt"] = $get[2];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "nicht erfolgreich";
echo json_encode($response);
}
}
if ( isset($_POST['update']) ){
$db=mysqli_connect("localhost","****","****","****");
$lasttime = isset($_POST['timestamp']) ? $_POST['timestamp'] : 0;
while (1){
sleep(1);
clearstatcache();
$mresult = mysqli_query($db,"SELECT * FROM tblchat WHERE msg_datetime > $lasttime");
if (!empty($mresult)){ break; }
}
$msgs = array();
while ($row = mysqli_fetch_object( $mresult )) { $msgs[] = $row; }
mysqli_free_result($mresult);
$response = array();
$response['msgs'] = $msgs;
echo json_encode($response);
flush();
mysqli_close($db);
exit();
}
The code is the server for a long polling connection with client. If update is requested, the while loops check for any new messages received after the timestamp sent with the update request. If found, it puts the result in an array and echo it back to the client.
The resulting output is something like this [msgs:[{msg_from:"",msg_to:"",msg:"",msg_datetime:""},{msg_from:"",msg_to:"",msg:"",msg_datetime:""}]]
The code works fine for the first time and send all the recent messages well encapsulated but then it again sends an empty array of messages. Please guide me.
solved the issue with mysqli_num_rows
if (mysqli_num_rows($mresult)){ $msgs = array(); while ($row = mysqli_fetch_object( $mresult )) { $msgs[] = $row; } mysqli_free_result($mresult); break; }
if (mysqli_num_rows($wresult)){ $writers = array(); while ($row = mysqli_fetch_object( $wresult )) { $writers[] = $row; } mysqli_free_result($wresult); break; }
thanks everyone for their help!