MYSQLi SELECT Fetch Object - php

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!

Related

getting error to display all record in php json

I am trying to display all records using jason in php.
but display all filed with null value.
I'm using postman for testing purpose.
I don't know what is the problem with that code. I getting null value only.
here is my code :
<?php
header('Content-Type: application/json');
$checkFields = "";
$REQUEST = $_SERVER['REQUEST_METHOD'];
if ($REQUEST == "POST")
{
include "DB/db.php";
$userlist = mysql_query("SELECT * FROM reg_services");
if(mysql_num_rows($userlist) > 0)
{
$p = 0;
$ph = array();
while($userlistdata = mysql_fetch_row($userlist))
{
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
$json = array("success" => 1, "All_User_List" => $ph);
$jsonarray = json_encode($json);
}
}
else
{
$json = array("success" => 0, "message" => "Invalid Request Type(Use POST Method)");
$jsonarray = json_encode($json);
}
echo $jsonarray;
?>
please help me if you are know what is the error in code.
just replace this code with old one
$p = 0;
$ph = array();
while($userlistdata = mysql_fetch_array($userlist))
{
$ph[$p] = array();
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
You need to tell PHP about arrays
while($userlistdata = mysql_fetch_row($userlist))
{
$ph[$p] = array(); // let PHP know it is an array
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
just replace this while loop condition with olde one.
while($userlistdata = mysql_fetch_array($userlist))
now it's work

fetching array from sql and checking with conditions

I need help...I'm trying to retrieve data from sql table and compare it with if statement for certain IDs and updating a variable accordinly. But it seems that the variable is not updating for some reason. Below is my code..
$query2 = "SELECT prcID, tProDone
FROM vw_fdwTracker
WHERE AgrNo = '$agreement'";
$result2= sqlsrv_query($conn, $query2);
if ($result2==false){
die( "<pre>".print_r(sqlsrv_errors(), true));
}
$current = 0;
while($id= sqlsrv_fetch_array($result2, SQLSRV_FETCH_ASSOC)){
//echo $id['prcID']." ". $id['tProDone'].'<br>';
if(($id['prcID']===3) && ($id['tProDone']===TRUE)){
$current=12.5;
}elseif(($id['prcID']===4) && ($id['tProDone']===TRUE)){
$current=25;
}elseif(($id['prcID']===5) && ($id['tProDone']===TRUE)){
$current=37.5;
}elseif(($id['prcID']===9) && ($id['tProDone']===TRUE)){
$current=50;
}elseif(($id['prcID']===10) && ($id['tProDone']===TRUE)){
$current=62.5;
}elseif(($id['prcID']===14) && ($id['tProDone']===TRUE)){
$current=75;
}elseif(($id['prcID']===12) && ($id['tProDone']===TRUE)){
$current=87.5;
}elseif(($id['prcID']===17) && ($id['tProDone']===TRUE)){
$current=100;
}else{
$current=0;
}
}
Try saving to an array so you know if it's working or not:
function getCurrentArr($agreement,$conn)
{
$query = "SELECT prcID, tProDone FROM vw_fdwTracker WHERE AgrNo = '$agreement'";
$result = sqlsrv_query($conn, $query);
if(!$result){
die( "<pre>".print_r(sqlsrv_errors(), true));
}
return $result;
}
function getCurrVal($value)
{
$return[3] = 12.5;
$return[4] = 25;
$return[5] = 37.5;
$return[9] = 50;
$return[10] = 62.5;
$return[14] = 75;
$return[12] = 87.5;
$return[17] = 100;
return (isset($return[$value]))? $return[$value] : 0;
}
$curr = array();
$result = getCurrentArr($agreement,$conn);
while($id= sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
if(!$id['tProDone']) {
$curr[] = 0;
continue;
}
$curr[] = getCurrVal($id['prcID']);
}
// See what this gets you for an array
// If what is in this array is what you expect, then
// make the $curr array the variable, but you will overwrite
// every time it loops, just keep that in mind
print_r($curr);
You don't need to define $current variable value at starting of code just do your code like below it will also work on loop
$id['prcID']=3;
$id['tProDone']=false;
if(($id['prcID']==3) && ($id['tProDone']==true)){
$current=12.5;
}else{
$current=0;
}
echo $current;

PHP Arrays between 2 Functions

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);
}
}

how to take data in mysql database with using php web service

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.

Json get value from table

I have a small code make this result :
{"nomdupharmacie":[{"pid":"71","name":"dft","longi":"9.010505676269531","lati":"34.1575970207261","matricule":"M65203124"},{"pid":"72","name":"erezrzer","longi":"7.529407627880573","lati":"34.63767601827405","matricule":"123"},{"pid":"73","name":"qsd","longi":"8.83832462131977","lati":"35.172592315800905","matricule":"333"}],"success":1}
with this php code :
// get all products from products table
$result = mysql_query("SELECT *FROM nomdupharmacie") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["nomdupharmacie"] = array();
$v = "12";
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["pid"] = $row["pid"];
$product["name"] = $row["name"];
$product["longi"] = $row["longitude"];
$product["lati"] = $row["latitude"];
$product["matricule"] = $row["personnel_number"];
// push single product into final response array
array_push($response["nomdupharmacie"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
i have to test for example :
$value = "555"
if $value exists in column of matricule so get alert
so the questionis how to make test if the value exists in the Matricule column or not ??
You should look into using PDO or ADOdb instead of mysql_query which is deprecated.
The only option is to compare manually like this:
1) create a function that receives an array x and value v to check
function isMatriculeInArray($x, $v)
{
foreach($x as $z)
{
if($z["matricule"] == $v)
{
return true;
}
}
return false;
}
2) check if matricule is in there
if(!isMatriculeInArray($response["nomdupharmacie"], $v)
{
array_push($response["nomdupharmacie"], $product);
}

Categories