PHP Arrays between 2 Functions - php

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

Related

php call a class function in loop multiple time issue

I have an issue with one of API, where this API will create Order information. Each Order represents 1 buyer with multiple items. I want to loop the items in my API method. But, when I try to loop the function, it only stores the first array value, which is not what I want. I want to store a whole array of values to the Database.
Here is the API Code:
$s = $data->ItemIDs;
if($order->CreateOrderInfo()){
echo 'Order created successfully.';
echo "---";
for($i = 0; $i < sizeof($s); $i++){
$order->ItemCode = $s[$i];
$order->GetItemInfo();
if ($order->ItemCode != null){
$item_array = array(
'UserMememberNo' => $order->UserMememberNo,
'Image' => $order->Image,
'Description' => $order->Description,
'Price' => $order->Price,
'ItemBrand' => $order->ItemBrand,
'ItemModel' => $order->ItemModel
);
//GET DATA FOR ITEM TABLE
$order->ItemGUID = $data->ItemGUID;
$order->ItemName = $order->Description;
$order->ItemPrice = $order->Price;
$order->ItemQuantity = $data->ItemQuantity;
$order->ItemVariation1 = $data->ItemVariation1;
$order->ItemVariation2 = $data->ItemVariation2;
$order->ItemVariation3 = $data->ItemVariation3;
$order->ItemVariation4 = $data->ItemVariation4;
$order->ItemVariation5 = $data->ItemVariation5;
}
else{
echo json_encode('No item Found');
}
if($order->CreateItemInfo())
{
echo 'Item created';
}else{
echo 'Unable to create item';
echo '----';
}
}
if($order->CreateBuyerInfo()){
echo 'Buyer information created';
}else{
echo 'Unable to create buyer information';
}
Here is the model. This model is for inserting the values into the Database:
//CREATE FUNCTION FOR ITEM TABLE
public function CreateItemInfo() {
$sqlQuery = "INSERT INTO ".$this->item_info_table."
SET
GUID = :GUID,
ItemGUID = :ItemGUID,
ItemName = :ItemName,
ItemPrice = :ItemPrice,
ItemQuantity = :ItemQuantity,
ItemVariation1 = :ItemVariation1,
ItemVariation2 = :ItemVariation2,
ItemVariation3 = :ItemVariation3,
ItemVariation4 = :ItemVariation4";
$stmt = $this->conn->prepare($sqlQuery);
$this->GUID = htmlspecialchars(strip_tags($this->GUID));
$this->ItemGUID = htmlspecialchars(strip_tags($this->ItemGUID));
$this->ItemName = htmlspecialchars(strip_tags($this->ItemName));
$this->ItemPrice = htmlspecialchars(strip_tags($this->ItemPrice));
$this->ItemQuantity = htmlspecialchars(strip_tags($this->ItemQuantity));
$this->ItemVariation1 = htmlspecialchars(strip_tags($this->ItemVariation1));
$this->ItemVariation2 = htmlspecialchars(strip_tags($this->ItemVariation2));
$this->ItemVariation3 = htmlspecialchars(strip_tags($this->ItemVariation3));
$this->ItemVariation4 = htmlspecialchars(strip_tags($this->ItemVariation4));
$stmt->bindParam(":GUID", $this->GUID);
$stmt->bindParam(":ItemGUID", $this->ItemGUID);
$stmt->bindParam(":ItemName", $this->ItemName);
$stmt->bindParam(":ItemPrice", $this->ItemPrice);
$stmt->bindParam(":ItemQuantity", $this->ItemQuantity);
$stmt->bindParam(":ItemVariation1", $this->ItemVariation1);
$stmt->bindParam(":ItemVariation2", $this->ItemVariation2);
$stmt->bindParam(":ItemVariation3", $this->ItemVariation3);
$stmt->bindParam(":ItemVariation4", $this->ItemVariation4);
if($stmt->execute()) {
return true;
}
return false;
}
A screenshot below shows the issue, where only the first value of the array is successfully inserted to the Database.
Result of Database Insert

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

MYSQLi SELECT Fetch Object

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!

Php: loop breaks when call a method inside a while in a class

I have a problem in a class I can't solve, the loop breaks in getAlojamiento() when I call getImagenes() inside the while. In this case getAlojamiento() returns only one row, it should return all the rows. Here are the methods involved:
//THIS GETS THE ROWS FROM A TABLE AND RETURN AN ARRAY, IF $id IS SET, CHECKS IF id_asoc == $id
public function getImagenes($table, $id=false){
$return = '';
//checks if id id == true
if($id){
$sql="SELECT * FROM $table WHERE id_asoc = '$id' ORDER BY id DESC";
}else{
$id = '';
$sql="SELECT * FROM $table ORDER BY id DESC";
}
//this make the sql request (returns an array)
if(!$this->MySQLQuery($sql)){
$return = false;
}else{
if($this->dbNumberRows == 0){ //cheks if there are results
$return = false;
}else{ //if has results makes and fills an array
$items = array();
while($f = mysql_fetch_object($this->dbResults)){
$items[$f->id]['id'] = $f->id;
$items[$f->id]['id_asoc'] = $f->id_asoc;
$items[$f->id]['comentario'] = htmlentities($f->comentario);
$items[$f->id]['nombre'] = htmlentities($f->nombre);
}
$return = $items;
}
}
return $return;
}
//THIS GETS THE ROWS FROM A TABLE AND RETURN AN ARRAY
public function getAlojamiento($id=false){
$return = '';
//checks if id id == true
if($id){
$sql="SELECT * FROM tb_alojamiento WHERE id = '$id' LIMIT 1";
}else{
$id = '';
$sql="SELECT * FROM tb_alojamiento ORDER BY titulo ASC";
}
//this make the sql request (returns an array)
if(!$this->MySQLQuery($sql)){
$return = false;
}else{
if($this->dbNumberRows == 0){ //cheks if there are results
$return = false;
}else{ //if has results makes and fills an array
$items = array();
while($f = mysql_fetch_object($this->dbResults)){
$imagenes_arr = $this->getImagenes('tb_alo_imagenes', $f->id); //this is causing the break
$items[$f->id]['id'] = $f->id;
$items[$f->id]['titulo'] = $f->titulo;
$items[$f->id]['telefono'] = $f->telefono;
$items[$f->id]['descripcion'] = $f->descripcion;
$items[$f->id]['email'] = $f->email;
$items[$f->id]['url'] = $f->url;
$items[$f->id]['direccion'] = $f->direccion;
$items[$f->id]['ubicacion'] = $f->ubicacion;
$items[$f->id]['coordenadas'] = $f->coordenadas;
$items[$f->id]['disponibilidad'] = $f->disponibilidad;
$items[$f->id]['tarifas'] = $f->tarifas;
$items[$f->id]['servicios'] = $f->servicios;
$items[$f->id]['theme'] = $f->theme;
$items[$f->id]['premium'] = $f->premium;
$items[$f->id]['img_ppal_id'] = $f->img_ppal_id;
$items[$f->id]['imagenes'] = $imagenes_arr;
}
$return = $items;
}
}
return $return;
}
The problem is that you are using $this->dbResults for both queries. When you call getImagenes you are clobbering the dbResults in getAlojamiento.
A simple solution to avoid having the first mysql query affect other queries is to complete it first:
//first loop over the result set from first query
while($f = mysql_fetch_object($this->dbResults))
{
//note: no call to $this->getImagenes here!
$items[$f->id]['id'] = $f->id;
$items[$f->id]['titulo'] = $f->titulo;
....
}
//only now you fetch the images in a second pass
foreach( $items as $id => $item )
{
$items[$id]['imagenes'] = $this->getImagenes('tb_alo_imagenes', $id);
}
//return the complete $items array
$return = $items;
while($f = mysql_fetch_object($this->dbResults)){
$items[$f->id]['id'] = $f->id;
$items[$f->id]['id_asoc'] = $f->id_asoc;
$items[$f->id]['comentario'] = htmlentities($f->comentario);
$items[$f->id]['nombre'] = htmlentities($f->nombre);
}
$return[] = $items;
You're setting the array to be the single $items array. You need to add it to the $return array.

Categories