Issue with createQueryBuilder and MongoRegex - php

After several research for the createquerybuilder for mongodb, I cannot solve my issue.Can you please help me?
Here is the structure of the data :
“Field1” : { “Field2”: “value1a”,“Field3” : {“Field4” : “value2a”,”Field5” : “value3a”}}
“Field1” : { “Field2”: “value1b”,“Field3” : {“Field4” : “value2b”,”Field5” : “value3b”}}
“Field1” : { “Field2”: “value1c”,“Field3” : {“Field4” : “value2c”,”Field5” : “value3c”}}
How can I get the whole row where Field5 = value3a ?
I have proceeded with the below code but it doesn’t return me any record :
$keywords = "test";
$keywords_Array = explode(',',$keywords);
$nbKeyword = count($keywords_Array);
$odm = $this->get("doctrine mongodb");
$donnees = $odm->createQueryBuilder("MyBundle:MyCollection");
for($i=0; $i<$nbKeyword; $i++){
$search = new \MongoRegex('/"Field5":"'.$ keywords_Array [$i].'"/');
$donnees = $donnees->field("Field1")->equals(new \MongoRegex('/"Field3":"'.$search.'"/'));
}
$donnees = $donnees->getQuery()->execute();
Foreach($donnees as $ data)
{
$resp = $data->getResult();
}
Return $resp;
And another structure of data (here, the data is an array of values):
“Field1” : {“Field2”: [“value1”,”value2”,”value3”]}
How can I get the whole row where Field2 = value3 ?
It is the same as above with the below code, it doesn’t return me any record :
$keywords = "test";
$keywords_Array = explode(',',$keywords);
$nbKeyword = count($keywords_Array);
$odm = $this->get("doctrine mongodb");
$donnees = $odm->createQueryBuilder("MyBundle:MyCollection");
for($i=0; $i<$nbKeyword; $i++){
$donnees = $donnees-> field("Field1")->equals(new \MongoRegex('/"Field2":"'. $keywords_Array [$i].'"/i'));
}
$donnees = $donnees->getQuery()->execute();
Foreach($donnees as $ data)
{
$resp = $data->getResult();
}
Return $resp;
Thanks in advance

The issue is fixed.I post the solution just in case anyone has also the same problem.
For the first structure of data, the code should be like this :
$keywords = "test";
$keywords_Array = explode(',',$keywords);
$nbKeyword = count($keywords_Array);
$odm = $this->get("doctrine mongodb");
$donnees = $odm->createQueryBuilder("MyBundle:MyCollection");
for($i=0; $i<$nbKeyword; $i++){
$donnees = $donnees->field('Field1')->equals(new \MongoRegex('/"Field5":'.$keywords_Array [$i].'/'));
}
$donnees = $donnees->getQuery()->execute();
Foreach($donnees as $ data)
{
$resp = $data->getResult();
}
Return $resp;
And for the second structure of data,the code should be like this :
$keywords = "test";
$keywords_Array = explode(',',$keywords);
$nbKeyword = count($keywords_Array);
$odm = $this->get("doctrine mongodb");
$donnees = $odm->createQueryBuilder("MyBundle:MyCollection");
for($i=0; $i<$nbKeyword; $i++){
$keys = new \MongoRegex("/".$keywords_Array [$i]."/");
$donnees = $donnees->field("Field1")->in(array("Field2"=>$keys));
}
$donnees = $donnees->getQuery()->execute();
Foreach($donnees as $ data)
{
$resp = $data->getResult();
}
Return $resp;
Thank you.

Related

Using an If statement in PHP but not working

What I want to do is When I enter all my information (for client ID 199 in the picture) In my account being submit it, it goes into the database. BUT I want it to change to something and so i added an if statement
Here the code im adding to the existing code already at the BOTTOM of the code
if ($vpr_clid == 199) {
$vpr_cl_name = "Shelley Madsen And Associates";
}
if the ($vpr_clid = 199)
i want the clname to be "Shelley Madsen And Associates" then what is show in the table below instead of "Nice and White Smiles" (that an example of the results look like)
but when i chcek the database it not changing it and still show "Nice and White Smiles :(
I dont see any error, so it might be the placement of the code i have to put the IF statement in the huge php file? Dont know how to fix this issue
Thanks (the code below is the base code before i added the If statement)
I also insert the if statement before the function were called but still didnt work example
if ($vpr_clid == 199) {
$vpr_cl_name = "Shelley Madsen And Associates";
}
$result = InsertIntoPayReminder($link, $vars);
$result = GetVpr_Id($link, $vars);
<?php
session_start();
if ($_SESSION['company'] != "ACB") {
// redirect to the logout page
$redirect = 'logout.php';
include './includes/redirect.php';
}
class variables_obj {
var $vpr_plan = '';
var $vpr_id = '';
var $vpr_clid = '';
var $vpr_cl_name = '';
var $vpr_cl_phone = '';
var $vpr_call_start_date = '';
var $vpr_db_account = '';
var $vpr_db_fname = '';
var $vpr_db_mname = '';
var $vpr_db_lname = '';
var $vpr_rp_fname = '';
var $vpr_rp_mname = '';
var $vpr_rp_lname = '';
var $vpr_rp_address = '';
var $vpr_rp_city = '';
var $vpr_rp_state = '';
var $vpr_rp_zipcode = '';
var $vpr_rp_phonenum = '';
var $vpr_rp_phonetype = '';
var $vpr_date_entered = '';
var $newrecdt = '';
var $vpl_day_offset = '';
var $vpl_action = '';
var $vpr_promocode = '';
}
function ScrubPhone($old_phone_num) {
$phone_length = strlen($old_phone_num);
$new_phone_num = "";
for($i = 0; $i < $phone_length; $i = $i + 1) {
if(is_numeric($old_phone_num[$i])) {
$new_phone_num .= $old_phone_num[$i];
}
}
return $new_phone_num;
}
function ScheduleCreated($link, $vars) {
$query = "UPDATE v_payreminder SET vpr_schedule_created = '1' WHERE vpr_id='".$vars->vpr_id."'";
if (!mysql_query($query,$link)) {
die('Error: ' . mysql_error());
}
return true;
}
function CreateScheduleRow($link, $vars){
// echo "vpl_day_offset: ".$vars->vpl_day_offset."<br>";
// echo "vpl_action: ".$vars->vpl_action."<br>";
$plus_days = " +".$vars->vpl_day_offset." days";
// echo "plus days: ".$plus_days."<br>";
$date_offset = strtotime(date("Y-m-d", strtotime($vars->vpr_date_entered)).$plus_days);
$date_offset = date("Y-m-d", $date_offset);
// echo "date_offset: ".$date_offset."<br>";
// $date_offset = strtotime(date("Y-m-d",strtotime($vars->vpr_date_entered))." +".$vars->vpl_day_offset." days");
// $date_offset = strtotime(date("Y-m-d", strtotime($date)) . " +1 day");
// echo "date_offset: ".$date_offset."<br>";
$query = "INSERT INTO v_pr_schedule (
vpr_id,
vsc_plan,
vsc_date_entered,
vsc_action,
vsc_action_date,
vsc_status
) VALUES (
'$vars->vpr_id',
'$vars->vpr_plan',
'$vars->vpr_date_entered',
'$vars->vpl_action',
'$date_offset',
'VACT')";
//echo "query: ".$query."<br>";
if (!mysql_query($query,$link)) {
die('Error: ' . mysql_error());
}
return true;
}
function CreateSchedule($link, &$vars) {
// CREATE SCHEDULE
$query = " SELECT vpl_day_offset, vpl_action, vpl_condition
FROM v_plan
WHERE vpl_plan = '".$vars->vpr_plan."'";
// echo "query: ".$query."<br>";
$qresult = mysql_query($query);
if (!$qresult) {
print(mysql_error());
}
if ($qresult && mysql_num_rows($qresult) > 0 ) {
while ($row = mysql_fetch_array($qresult, MYSQL_ASSOC)) {
$vars->vpl_day_offset = $row['vpl_day_offset'];
$vars->vpl_action = $row['vpl_action'];
if ($row['vpl_condition'] == 'OO') {
CreateScheduleRow($link, $vars);
}
}
}
return true;
}
function InsertIntoPayReminder($link, &$vars) {
$vars->vpr_cl_name = strtr($vars->vpr_cl_name, "'", " ");
//echo "Client Name: ".$vars->vpr_cl_name."<br><br>";
//exit();
$sql="INSERT INTO v_payreminder (
vpr_clid,
vpr_cl_name,
vpr_cl_phone,
vpr_call_start_date,
vpr_db_account,
vpr_db_fname,
vpr_db_mname,
vpr_db_lname,
vpr_rp_fname,
vpr_rp_mname,
vpr_rp_lname,
vpr_rp_phonenum,
vpr_rp_phonetype,
vpr_rp_address,
vpr_rp_city,
vpr_rp_state,
vpr_rp_zipcode,
vpr_promo,
vpr_date_entered) VALUES (
'$vars->vpr_clid',
'$vars->vpr_cl_name',
'$vars->vpr_cl_phone',
'$vars->vpr_call_start_date',
'$vars->vpr_db_account',
'$vars->vpr_db_fname',
'$vars->vpr_db_mname',
'$vars->vpr_db_lname',
'$vars->vpr_rp_fname',
'$vars->vpr_rp_mname',
'$vars->vpr_rp_lname',
'$vars->vpr_rp_phonenum',
'$vars->vpr_rp_phonetype',
'$vars->vpr_rp_address',
'$vars->vpr_rp_city',
'$vars->vpr_rp_state',
'$vars->vpr_rp_zipcode',
'$vars->vpr_promocode',
'$vars->vpr_date_entered')";
if (!mysql_query($sql,$link)) {
die('Error2: ' . mysql_error());
}
return true;
}
function GetVpr_Id($link, &$vars) {
// Find out what vpr_id is
$query = "SELECT vpr_id FROM v_payreminder ";
$query .= "WHERE vpr_clid = '".$vars->vpr_clid."' AND vpr_date_entered = '".$vars->vpr_date_entered."'";
$qresult = mysql_query($query);
if (!$qresult) {
print(mysql_error());
}
if ($qresult && mysql_num_rows($qresult) > 0 ) {
$row = mysql_fetch_array($qresult, MYSQL_ASSOC);
$vars->vpr_id = $row['vpr_id'];
}
}
function InsertInActivity($link, $vars) {
// ENTER INTO ACTIVITY
$vaction_desc = 'PATIENT ENTERED';
$sql = "INSERT INTO v_pr_activity (
vpr_id,
va_plan,
va_action_dttm,
va_action_code,
va_action_desc,
va_disposition_code,
va_disposition_desc,
va_status_code,
va_status_desc
) VALUES (
'$vars->vpr_id',
'$vars->vpr_plan',
'$vars->vpr_date_entered',
'VINIT',
'$vaction_desc',
'SUCCESS',
'SUCCESS',
'VACT',
'ACTIVE'
)";
if (!mysql_query($sql,$link)) {
die('Error: ' . mysql_error());
}
}
include './includes/dblogin.php';
$vars = new variables_obj();
$vars->vpr_plan = 'VP01';
$vars->vpr_clid = $_SESSION['userid'];
//-------------------------------------------------------
// No commas can be in client name or they will
// mess up the Global Connect CSV file.
//-------------------------------------------------------
$vpr_cl_name = $_SESSION['username'];
$vpr_cl_name = str_replace(",", " ", $vpr_cl_name);
$vars->vpr_cl_name = $vpr_cl_name;
//-------------------------------------------------------
//-------------------------------------------------------
$vars->vpr_cl_phone = ScrubPhone($_SESSION['uphone']);
$vars->vpr_call_start_date = '0000-00-00';
$vars->vpr_db_account = $_POST['ndaccnum'];
$vars->vpr_db_fname = $_POST['ndfreqname'];
$vars->vpr_db_mname = $_POST['ndmname'];
$vars->vpr_db_lname = $_POST['ndlreqname'];
$vars->vpr_rp_fname = $_POST['ndrfreqname'];
$vars->vpr_rp_mname = $_POST['ndrmname'];
$vars->vpr_rp_lname = $_POST['ndrlreqname'];
$vars->vpr_rp_address = '';
$vars->vpr_rp_city = '';
$vars->vpr_rp_state = $_POST['ndrstatereqname'];
$vars->vpr_rp_zipcode = $_POST['ndrreqzipcode'];
$phonenumber = $_POST['1ndrreqphone'].$_POST['2ndrreqphone'].$_POST['3ndrreqphone'];
$vars->vpr_rp_phonenum = $phonenumber;
$vars->vpr_rp_phonetype = $_POST['treqphone'];
$vars->vpr_date_entered = date('Y-m-d H:i:s');
$vars->newrecdt = date('Ymd');
$vars->vpr_promocode = $_POST['promocode'];
// echo "vpr_plan: ".$vars->vpr_plan."<br>";
// echo "vpr_date_entered: ".$vars->vpr_date_entered."<br>";
// echo "newrecdt: ".$vars->newrecdt."<br>";
// echo "vpr_clid: ".$vars->vpr_clid."<br>";
// echo "vpr_id: ".$vars->vpr_id."<br>";
$result = InsertIntoPayReminder($link, $vars);
$result = GetVpr_Id($link, $vars);
$result = InsertInActivity($link, $vars);
$result = CreateSchedule($link, $vars);
$result = ScheduleCreated($link, $vars);
// echo "vpr_id: ".$vars->vpr_id."<br>";
mysql_close($link);
// redirect
$redirect = 'vpayremind.php';
include './includes/redirect.php';
?>
okay referencing the following lines..
if ( $vpr_clid == 199 ) {
$vpr_cl_name = "Shelley Madsen And Associates";
}
$result = InsertIntoPayReminder($link, $vars);
...and then:
function InsertIntoPayReminder($link, &$vars) {
$vars->vpr_cl_name = strtr($vars->vpr_cl_name, "'", " ");
so on and so forth... }
it doesnt seem as if you are actually setting the value of the class object. You seem to be setting some arbitrary php variable to the name you want, and then passing a totally different ' $vars ' object into the function. I don't see any reason to believe that the ' $vars ' you are passing into the function call contains the name value you want it to contain. You should be assigning the value of ' $vars ' before passing it in.
For instance:
if ( $vpr_clid == 199 ) {
$vars[ 'vpr_cl_name' ] = "Shelley Madsen And Associates";
}
then you can get rid of this line all together:
$vars->vpr_cl_name = strtr($vars->vpr_cl_name, "'", " ");

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

Laravel Request does not return result

I am using AWS and laravel 5.1.
I have two issues:
Most of the time API returns the expected result but sometimes server
doesn't return result for longer time. It might be due to the server
load(Although we don't have too much load on server).
Clients wait for few minutes and after that application crashes. Any
Advice.
If Client made an API request and before getting result, if device
loses internet connection. Server has process the data but unable to
deliver it to the client. how to handle this (Both in get as well as
post request)
Sample Code for first Part
public function psychometricResponses(Request $request)
{
$questionId=$request->get('questionId');
$answerId=$request->get('answerId');
$from = $request->has('from');
$userId = $request->has('id') ? $request->get('id') : 0;
$name = $request->has('name') ? $request->get('name') : '';
$email = $request->has('email') ? $request->get('email') : '';
$gender = $request->has('gender') ? $request->get('gender') : '';
$relationshipStatus = $request->has('relationshipStatus') ? $request->get('relationshipStatus') : '';
if($userId!=0){
$status = 1;
User::where('id',$userId)->update(['status'=>1]);
}else{
$status = 0;
}
$id = $this->calculatePersonality($questionId, $answerId, $userId, $from, $name, $email, $gender, $relationshipStatus);
return json_encode(['code'=>200,'message'=>"success",'response'=>array('personality'=>$this->_getPersonality($id),'psychometricId'=>$id,'status'=>$status)]);
}
public function calculatePersonality($questionId, $answerId, $userId, $from, $name, $email, $gender, $relationshipStatus)
{
//
$questionArray = explode(',', $questionId); //arraySize is 60
$answerArray = explode(',', $answerId); // //arraySize is 60
$this->questionAll = $this->_questionAll();
$personality = array('O'=>0,'C'=>0,'E'=>0,'A'=>0,'N'=>0);
for($i=0; $i<sizeof($answerArray);$i++){
$type = $this->_getQuestionType($questionArray[$i]);
if($type=='O'){
$personality['O'] = $answerArray[$i]=='1' ? $personality['O']+1 : $personality['O']-1;
}else if($type=='OR'){
$personality['O'] =$answerArray[$i]=='1' ? $personality['O']-1 : $personality['O']+1;
}else if($type=='C'){
$personality['C'] = $answerArray[$i]=='1' ? $personality['C']+1 : $personality['C']-1;
}else if($type=='CR'){
$personality['C'] = $answerArray[$i]=='1' ? $personality['C']-1 : $personality['C']+1;
}else if($type=='E'){
$personality['E'] = $answerArray[$i]=='1' ? $personality['E']+1 : $personality['E']-1;
}else if($type=='ER'){
$personality['E'] = $answerArray[$i]=='1'?$personality['E']-1 : $personality['E']+1;
}else if($type=='A'){
$personality['A'] = $answerArray[$i]=='1' ? $personality['A']+1 : $personality['A']-1;
}else if($type=='AR'){
$personality['A'] = $answerArray[$i]=='1' ? $personality['A']-1 : $personality['A']+1;
}else if($type=='N'){
$personality['N'] = $answerArray[$i]=='1'? $personality['N']+1 : $personality['N']-1;
}else if($type=='NR'){
$personality['N'] = $answerArray[$i]=='1' ? $personality['N']-1 : $personality['N']+1;
}
}
$mod = array();
$mod['O'] = abs($personality['O']);
$mod['C'] = abs($personality['C']);
$mod['E'] = abs($personality['E']);
$mod['A'] = abs($personality['A']);
$mod['N'] = abs($personality['N']);
arsort($mod);
$values = array_keys($mod);
$pTypeOne = $personality[$values[0]] < 0 ? $values[0].'R' : $values[0];
$pTypeTwo = $personality[$values[1]] < 0 ? $values[1].'R' : $values[1];
$pTypeThree = $personality[$values[2]] < 0 ? $values[2].'R' : $values[2];
$pTypeFour = $personality[$values[3]] < 0 ? $values[3].'R' : $values[3];
$pTypeFive = $personality[$values[4]] < 0 ? $values[4].'R' : $values[4];
$psychometricResponse = PsychometricResponse::create(array('typeA'=>$pTypeOne, 'valueA'=>$personality[$values[0]],'typeB'=>$pTypeTwo, 'valueB'=>$personality[$values[1]],
'typeC'=>$pTypeThree, 'valueC'=>$personality[$values[2]],'typeD'=>$pTypeFour, 'valueD'=>$personality[$values[3]],
'typeE'=>$pTypeFive, 'valueE'=>$personality[$values[4]],'questionId'=>$questionId,'answerId'=>$answerId, 'userId'=>$userId, 'from'=>$from,'name'=>$name,'email'=>$email, 'gender'=>$gender,'relationshipStatus'=>$relationshipStatus));
return $psychometricResponse->id;
}
private function _questionAll(){
$question = PsychometricQuestion::where('isActive',1)->get(['id','type']);
$result =array();
for($i=0;$i<sizeof($question);$i++){
$result[$question[$i]->id] = $question[$i]->type;
}
return $result;
}
private function _getQuestionType($id){
return $this->questionAll[$id];
}
private function _getPersonality($id){
$personality = PsychometricResponse::where('id',$id)->first(['typeA','typeB','typeC','typeD','typeE','valueA','valueB']);
$combined = array($personality->typeA,$personality->typeB);
sort($combined);
$combinedPersonality = PsychometricResult::where('type',$combined[0]."-".$combined[1])->first(['type','keyword','description','colorCode']); //Table PsychometricResult has 40 rows only.
$primaryPersonality = PsychometricResult::where('type',$personality->typeA)->first(['type','keyword','description','colorCode']);
$secondaryPersonality = PsychometricResult::where('type',$personality->typeB)->first(['type','keyword','description','colorCode']);
$permutation = $this->_getAllPermutation($personality);
$stylePersonality = PsychometricStyle::whereIn('type',$permutation)->get(['type','aspect','style','description']);
$primaryPercentage = round(abs($personality->valueA)/(abs($personality->valueA)+abs($personality->valueB)), 2);
$secondaryPercentage = 1 - $primaryPercentage;
return array('primaryPersonality'=>$primaryPersonality,'secondaryPersonality'=>$secondaryPersonality,'combinedPersonality'=>$combinedPersonality,
'styles'=>$stylePersonality,'primaryPercentage'=>$primaryPercentage,'secondaryPercentage'=>$secondaryPercentage);
}
private function _getAllPermutation($personality){
$combined = array($personality->typeA,$personality->typeB,$personality->typeC,$personality->typeD,$personality->typeE);
sort($combined);
$permutation = array();
for($i=0;$i<sizeof($combined);$i++){
for($j=$i+1;$j<5;$j++){
array_push($permutation,$combined[$i]."-".$combined[$j]);
}
}
return $permutation;
}

Cannot use object of type Entity\X as array

I have little problem, I have no idea what's wrong with my code :/
$ilosc = $_POST["ilosc"];
$recipe = new Recipe();
$em = $this->getDoctrine()->getManager();
$repository = $this->getDoctrine()->getRepository('MainBundle:Recipe');
$query = $repository->createQueryBuilder('p')->select('p.id')->where('p.nazwa = :nazwa AND p.adres = :adres')->setParameters(array('nazwa' => $_POST["nazwaprzepisu"], 'adres' => $_POST["adresprzepisu"]))->getQuery();
$test = $query->getResult();
$id = $test[0]['id'];
$idprod = $_POST['idprod'];
$iloscprod = $_POST['iloscprod'];
for ($i = 0; $i < $ilosc; $i++)
{
$ingredient = new Ingredient();
$repositorying = $this->getDoctrine()->getRepository('MainBundle:Ingredient');
$query = $repositorying->createQueryBuilder('p')->select('p')->where('p.przepis_id = :id AND p.produkt_id = :idprod')->setParameters(array('id' => $id, 'idprod' => $idprod[$i]))->getQuery();
$result = $query->getResult();
if(!$result)
{
$ingredient->setProduktId($idprod[$i]);
$ingredient->setPrzepisId($id);
$ingredient->setIlosc($iloscprod[$i]);
}
else
{
$nowailosc = $result[0]['ilosc'] + $iloscprod[$i];
$stareid = $result[0]['id'];
echo "kokoko";
}
$em->persist($ingredient);
$em->flush();
}
I have problem with those two lines:
$nowailosc = $result[0]['ilosc'] + $iloscprod[$i];
$stareid = $result[0]['id'];
I get an error:
"Fatal error: Cannot use object of type My\MainBundle\Entity\Ingredient as array in".
Somebody have idea what I am doing wrong?
Problem solved. I had to use:
$nowailosc = $result[0]->getIlosc() + $iloscprod[$i];
$stareid = $result[0]->getId();

Parse Json Encode Array PHP error

Here is my problem :
I have a PHP file, that should return multiple records,
everything worked fine... but, i don't know why, probably because of a little mistake somewhere... now it doesn't work anymore...
my Json_encode(my php) returns this :
{"1":{"id":"2222","name":"ERESRS"},"2":{"id":"1111","name":"LJLJM"}}
instead of simply :
[{"id":"2222","name":"ERESRS"},{"id":"1111","name":"LJLJM"}]
anybody had this issue before?
i already checked again and again my php file, and i don't find where this "false array" comes from...
thanks for help
Here is the js code :
$.ajax({
type : 'POST',
url : './php/getBenefListe.php',
data : {'id':idSoc},
error : function(){
alert('ERREUR MISE A JOUR DE LA LISTE');
},
success : function(response){
$("#benefListe").empty();
$('#benefListe').append($('<option>',{
value : '',
text : 'Choisissez dans la liste'
}));
alert("REPONSE : "+response);
var myData = JSON.parse(response);
for(var i=0;i<myData.length;i++){
var id = myData[i].id;
if(id-latestBenef > 0){
latestBenef = id;
}
var nom = myData[i].nom;
var prenom = myData[i].prenom;
var rue = myData[i].rue;
var numero = myData[i].num;
var boite = myData[i].bte;
var cp = myData[i].cp;
var loc = myData[i].loc;
if(rue!="" && numero!=""){
rue = rue+", "+numero;
}
if(cp!="" && loc!=""){
loc = "- "+cp+" "+loc;
}
var field = nom+" "+prenom+" ; "+rue+" "+boite+" "+loc;
$('#benefListe').append($('<option>',{
value : id,
text : field
}));
}
alert("B\351n\351ficiaire Ajout\351!");
$("#benefListe option[value="+latestBenef+"]").prop('selected',true);
$("#benefListe").change();
}
});
here is the php file called :
include "./functions.php";
if(isset($_POST['id']) && ($_POST['id']!='')){
$id = $_POST['id'];
$db = connectToDb('test');
$myArray = array();
$i = 0;
$getBenefIds = "SELECT DISTINCT IDPERSONNE FROM socrsp WHERE (IDSOCIETE = $id);";
$benefIds = $db->prepare($getBenefIds);
$benefIds->execute();
$count = $benefIds->rowCount();
if($count>0){
foreach($benefIds as $benefId){
$getBenef = "SELECT IDPERSONNE,NOM,PRENOM,ADRESSE,NUMERO,BTE,IDCOPOSTAL,CODEPAYS FROM personne WHERE IDPERSONNE = ".$benefId['IDPERSONNE'];
$myBenef = $db->prepare($getBenef);
$myBenef->execute();
foreach($myBenef as $benef){
if(!(is_numeric($benef['ADRESSE']))){
$myArray[$i]['id'] = $benef['IDPERSONNE'];
$myArray[$i]['nom'] = $benef['NOM'];
$myArray[$i]['prenom'] = $benef['PRENOM'];
$myArray[$i]['rue'] = '';
$myArray[$i]['num'] = '';
$myArray[$i]['rue'] = $benef['ADRESSE'];
$myArray[$i]['num'] = $benef['NUMERO'];
$myArray[$i]['bte'] = $benef['BTE'];
//RECUP CP ET LOCALITE
if((isset($benef['IDCOPOSTAL']) && ($benef['IDCOPOSTAL']!='0') && ($benef['IDCOPOSTAL']!='2913'))&&($benef['CODEPAYS']=="B")){
$whereQuery = "SELECT CODEPOSTAL,LIBLOCALITE FROM copostal WHERE IDCOPOSTAL = ".$benef['IDCOPOSTAL'];
$where = $db->prepare($whereQuery);
$where->execute();
foreach($where as $w){
$myArray[$i]['cp'] = $w['CODEPOSTAL'];
$myArray[$i]['loc'] = $w['LIBLOCALITE'];
}
}else if((isset($benef['IDCOPOSTAL']) && ($benef['IDCOPOSTAL']!='0'))&&($benef['CODEPAYS']!="B")){
$whereQuery = "SELECT CPEXTERNE,LOCEXTERNE FROM cpostext WHERE IDCPOSTEXT = ".$benef['IDCOPOSTAL'];
$where = $db->prepare($whereQuery);
$where->execute();
foreach($where as $w){
$myArray[$i]['cp'] = $w['CPEXTERNE'];
$myArray[$i]['loc'] = $w['LOCEXTERNE'];
}
}else{
$myArray[$i]['cp'] = '';
$myArray[$i]['loc'] = '';
}
$i++;
}else{
$i++;
}
}
}
}
echo json_encode($myArray);
$db = null;
}
It looks like you're setting manually the keys for the PHP array or editing it in some way. Compare the following results:
<?php
$a = ['hello', 'world'];
echo json_encode($a);
// ["hello","world"]
$b = [1 => 'hello', 2 => 'world'];
echo json_encode($b);
// {"1":"hello","2":"world"}
$b = ['hello', 'world', 'how', 'are', 'you'];
unset($b[2]);
echo json_encode($b);
// {"0":"hello","1":"world","3":"are","4":"you"}
As #amphetamachine suggest, a possible solution is this:
$b = [1 => 'hello', 2 => 'world'];
$b = array_values($b);
echo json_encode($b);
// ["hello","world"]
Another interesting test (your case):
<?php
$a = $b = [];
for ($i = 0; $i < 3; $i++) {
$a[$i] = "test";
if ($i != 1) {
$b[$i] = "test";
}
}
echo json_encode($a);
// ["test","test","test"]
echo json_encode($b);
// {"0":"test","2":"test"}
echo json_encode(array_values($b));
// ["test","test"]
From which, we can get that you do need that array_values() if you want to set not-consecutive array keys.

Categories