I am getting this error that runs fine on one of my servers with php 5.4 I transfered the code to a new server with php 5.5.9 and now I am getting this error:
Details
Type: ErrorException
Code: 8
Message: Undefined variable: propertylist
File: /var/www/subdomains/api/index.php
Line: 57
Trace
The code:
$app->get("/propertylist/", function () use ($app, $db) {
$app->response()->header("Content-Type", "application/json");
ob_start('ob_gzhandler');
$req = $app->request();
$bed = $req->get('bed');
$bath = $req->get('bath');
$city = $req->get('city');
$zip = $req->get('zip');
if($bed ==''){$bed=0;}
if($bath ==''){$bath=0;}
if($zip ==''){
$properties = $db->rets_property_listing_mrmls_resi->limit(2500,0)->where("Bedrooms >= ?", $bed)->where("City LIKE ?", "%$city%")->where("BathsTotal >= ?", $bath);
}else{
$properties = $db->rets_property_listing_mrmls_resi->limit(2500,0)->where("Bedrooms >= ?", $bed)->where("ZipCode LIKE ?", "%$zip%")->where("BathsTotal >= ?", $bath);
}
foreach ($properties as $property) {
$propertylist[] = array(
"MLSnumber" => $property["MLnumber"],
"ListPrice" => number_format($property["ListPrice"]),
"StreetNumber" => $property["StreetNumber"],
"StreetName" => $property["StreetName"],
"SqFt" => $property["SquareFootageStructure"],
"PropertyDescription" => summaryMode($property["PropertyDescription"],15),
"Bedrooms" => $property["Bedrooms"],
"BathsTotal" => $property["BathsTotal"],
"LO_Name" => $property["LO_Name"]
);
}
echo json_encode($propertylist);
});
You need create/define variable before use:
$app->get("/propertylist/", function () use ($app, $db) {
$app->response()->header("Content-Type", "application/json");
ob_start('ob_gzhandler');
$req = $app->request();
$bed = $req->get('bed');
$bath = $req->get('bath');
$city = $req->get('city');
$zip = $req->get('zip');
if($bed ==''){$bed=0;}
if($bath ==''){$bath=0;}
if($zip ==''){
$properties = $db->rets_property_listing_mrmls_resi->limit(2500,0)->where("Bedrooms >= ?", $bed)->where("City LIKE ?", "%$city%")->where("BathsTotal >= ?", $bath);
}else{
$properties = $db->rets_property_listing_mrmls_resi->limit(2500,0)->where("Bedrooms >= ?", $bed)->where("ZipCode LIKE ?", "%$zip%")->where("BathsTotal >= ?", $bath);
}
$propertylist = array(); //Create variable type array
foreach ($properties as $property) {
$propertylist[] = array(
"MLSnumber" => $property["MLnumber"],
"ListPrice" => number_format($property["ListPrice"]),
"StreetNumber" => $property["StreetNumber"],
"StreetName" => $property["StreetName"],
"SqFt" => $property["SquareFootageStructure"],
"PropertyDescription" => summaryMode($property["PropertyDescription"],15),
"Bedrooms" => $property["Bedrooms"],
"BathsTotal" => $property["BathsTotal"],
"LO_Name" => $property["LO_Name"]
);
}
echo json_encode($propertylist);
});
I think that version of PHP just changed the variables' scope, now it's more like you expect in other languages. If you define/create a variable in a block, it's not visible in the outer scope.
In your case, $propertylist is defined directly in the foreach block scope, hence it isn't visible to the rest of the code, causing the error.
As #Guilherme Nascimento suggested, you have to define it outside the loop.
That's said, in PHP is perfectly fine (but not recommended) to use a variable without instantiate it:
$var[] = 1;
// => array(1)
Related
I am working on a web app with php laravel framework. I'm also using framwork eloquent.
When i create a new "user" and i send it to my database the error with
$myValue->save();
This is the error:
"at HandleExceptions->handleError(8, 'Only variable references should be returned by reference',
'C:\\wamp64\\www\\project\\Fiq-spsslsj\\app\\Http\\Controllers\\DossierController.php', 97, array('request' => object(Request), 'employe' => object(employe)))
in DossierController.php line 97"
I've seen some similar problem but they are not quite really usefull (the problem in the other topics talk about code ingniter and common.php).
public function ajouter(Request $request){
$employe = new employe;
$employe->No_Employe = $request->input('No_Employe');
$employe->Nom = $request->input('Nom');
$employe->Prenom = $request->input('Prenom');
$employe->Email = $request->input('Email');
$employe->Adresse = $request->input('Adresse');
$employe->Date_Naissance = $request->input('Date_Naissance');
$employe->Titre_Emploi = $request->input('Titre_Emploi');
$employe->Telephone = $request->input('Telephone');
$employe->Annee_Embauche = $request->input('Annee_Embauche');
$employe->Present_Travail = $request->input('optTrav');
$employe->Sexe = $request->input('optSexe');
$employe->Fumeur = $request->input('optFum');
$employe->Langue = $request->input('Langue');
if (DB::table('liste_ville')->where('Nom_Ville','=',$request->input('Ville'))->get() != null)
{
$employe->Fk_Id_Ville = DB::table('liste_ville')->where('Nom_Ville','=',$request->input('Ville'))->value('Id_Ville');
}
else
{
$newVille = ucfirst($request->input('Ville'));
DB::table('liste_ville')->insertGetId(['Nom_Ville' => $newVille]);
$MoreVille = DB::table('liste_ville')->get();
foreach ($MoreVille as $key => $v)
{
if(strtolower($request->input('Ville')) === strtolower($v->Nom_Ville)){
$employe->Fk_Id_Ville = $v->Id_Ville;
break;
}
}
}
$employe->Code_Postal = $request->input('Code_Postal');
$employe->Actif = $request->input('optActif');
if (DB::table('provinces')->where('Nom_Province','=',$request->input('Province'))->get() != null) {
$employe->Fk_Id_Province =DB::table('provinces')->where('Nom_Province','=',$request->input('Province'))->value('Id_Province');
}
else
{
$newProv = ucfirst($request->input('Province'));
DB::table('provinces')->insertGetId(['Nom_Province' => $newProv]);
foreach ($provinces as $key => $p)
{
if(strtolower($request->input('Province')) === strtolower($p->Nom_Province)){
$employe->Fk_Id_Province = $p->Id_Province;
break;
}
}
}
$employe->save();
return redirect('/dossiers');
}
The code above is the code in my controller.
I hope you'll be able to help me.
Try this in your controller
return redirect()->to('/dossiers');
I have a problem with my message notification using email.Why is that it generates an error inside the foreach.
The error is this part "$all_ngo" Undefined variable: all_ngo.
$pend = AddRequest::where('ship_id','=',$ship_id)->get();
$all_ngo = [];
foreach ($pend as $id) {
array_push($all_ngo, $id->ngo_id);
}
$orga_email = Auth::User()->orgainfo->orga_email;
$staffName = Auth::User()->orgainfo->inchargelname.' '. Auth::User()->orgainfo->inchargefname;
$name = $scholars->scholar_fname.' '.$scholars->scholar_mname.' '.$scholars->scholar_lname;
$input = array(
'name' => $staffName,
'email' => $orga_email,
'msgs' => 'asd' .' '. $name.'. '.'Hoping for your favorable response. Thank you!'
);
Mail::send('emails.mailMessage', $input, function($message){
$message->from('Somename#gmail.com');
foreach ($all_ngo as $id3) {<-------Undefined variable: all_ngo
$user = User::find($id3);
$ngo_email2 = $user->ngo_email;
$message->to($ngo_email2)->subject('Request For Sponsorship');
}
});
Because $all_ngo is out of scope. You can solve this by adding a global $all_ngo; into the function:
Mail::send('emails.mailMessage', $input, function($message) {
global $all_ngo;
$message->from('Somename#gmail.com');
foreach ($all_ngo as $id3) {<-------Undefined variable: all_ngo
$user = User::find($id3);
$ngo_email2 = $user->ngo_email;
$message->to($ngo_email2)->subject('Request For Sponsorship');
}
});
or allow the anonymous function to access the variable:
Mail::send('emails.mailMessage', $input, function($message) use ($all_ngo) {
$message->from('Somename#gmail.com');
foreach ($all_ngo as $id3) {<-------Undefined variable: all_ngo
$user = User::find($id3);
$ngo_email2 = $user->ngo_email;
$message->to($ngo_email2)->subject('Request For Sponsorship');
}
});
Here is the code :
foreach ($test_scores as $score) {
switch ($score['name']) {
case 'LE-TOD':
$le_tod = $score['banding'];
$le_tod_desc = $score["result_desc"];
if($score['std_score'] == 0) {
$le_tod_small = $scoring['tod']['no_pref_bottom'];
}
else {
$le_tod_small = $scoring['tod']['pref_bottom'].$score['banding'];
}
break;
This is where I get the error message :
public static function generateLSPReportFile($dataInput, $auto_download = true)
{
$file_type = $dataInput['file_type'];
$test_type_id = $dataInput['test_type_id'];
$he_she = array('male' => 'He', 'female' => 'She');
$his_her = array('male' => 'his', 'female' => 'her');
$candidate = \Candidate::where('id',$dataInput['candidate_id'])->first();
if(!$candidate)
return;
$candidate = $candidate->toArray();
$candidate_name = $candidate['first_name'].' '.$candidate['last_name'];
$order = \Order::with('client')->find($dataInput['order_id']);
if(!$order)
return;
$client = $order->client;
$order = $order->toArray();
//for test dates
$order_candidate = \OrderCandidate::candidateId($dataInput['candidate_id'])->orderId($dataInput['order_id'])->first()->toArray();
$order_tests = \OrderCandidateTest::orderCandidateId($order_candidate['id'])
->status(\Config::get('kcg.candidate_test_status_taken'))
->testId($dataInput['test_id'])
->with(array('test' => function($query){
$query->select(['id', 'name', 'description', 'abbreviation']);
}));
$tests_scores = \OrderCandidateTestScore::orderId($dataInput['order_id'])
->candidateId($dataInput['candidate_id'])
->testId($dataInput['test_id'])
->with(array('test' => function($query){
$query->select(['id', 'name', 'description', 'test_type_id']);
}));
$test_type = TestType::find($test_type_id);
$test_scores = $tests_scores->orderBy('sequence_no')->get()->toArray();
$order_tests = $order_tests->get()->toArray();
if(!$order_tests)
return;
if(!$tests_scores)
return;
It posted an error : ErrorException Undefined offset: 2. I'm really not sure what's causing this.
What am I doing wrong here? Please help me. Thank you
Typically, the Undefined offset message would be triggered by trying to access an array key which doesn't exist.
It seems that your code example might not actually be showing the part that triggered the error... In your case, I would expect the code to show something like $var[2], where the array does not actually contain an index of 2.
See this other question for a clearer representation of what that error means.
i have this code:
$.getJSON('newMessageDetails', function (json)
{
var old_id = document.getElementById("td_id").value;
var messages_count = Object.keys(json).length;
console.log(messages_count);
console.log(json);
last_id = json[messages_count]["msgId"];
});
the json[messages_count]["msgId"] gives undefined in the console??
my newMessageDetails:
public function executeNewMessageDetails(sfWebRequest $request)
{
$profile_id = $this->getUser()->getAttribute('profile_id','zero');
$new_msgs = RcMessageBoxTablePeer::getNewMessages($profile_id);
$hr=2;
$i=1;
if (count($new_msgs) >= 1)
{
foreach ($new_msgs as $row)
{
$date = $row->getCreatedAt();
//$cd = strtotime($date);
//$newdate = date('Y-m-d H:i:s', mktime(date('h',$cd), date('i',$cd), date('s',$cd), date('m',$cd), date('d',$cd), date('Y',$cd)));
$subject = $row->getSubject();
$message = $row->getMessage();
$from = $row->getProfileIdFrom();
$id = $row->getId();
$uc_record = RcProfileTablePeer::getById($from);
$uc_from = $uc_record->getUniqueCode();
$output[$i] = array("td_date" => $date, "td_subject" => $subject, "td_from" => $uc_from, "td_message" => $message, "msgId" => $id , "i" => $i);
$i++;
}
return $this->renderText(json_encode($output));
}
}
console.log(json) gives:
5
list:98
Object
543: Object
544: Object
545: Object
546: Object
547: Object
i: 1
msgId: 547
td_date: "2011-11-29 11:33:05"
td_from: "CHARLIE000RC"
td_message: "tooltip show message test 2 id 547"
td_subject: "Freechat message"
can some-one explain please? dont know what im doing wrong though
thanks
Objects don't have a length property. try this.
var obj = jQuery.parseJSON(json);
obj.length();
or you can try this.
Object.keys(json).length;
If you would like a count of all keys you could rewrite it to this:
$.getJSON('newMessageDetails', function (json)
{
...;
var messages_count = Object.keys(json).length;
console.log(messages_count);
});
you should just iterate through the object and count . Thats the only way you can really know how many 'meaningful' objects you have in your object.
Can anyone tell me how to display the value of next from the code below?
In my user.php file i have next content:
class User {
protected $userID;
protected $useremail;
protected $userPassword;
public function __construct() {
$this->userID = preg_replace('#[^0-9]#i', '',
$_SESSION['user_id']);
$this->useremail = preg_replace('#[^A-Za-z0-9#_.-]#i', '',
$_SESSION['user']);
$this->userPassword = preg_replace('#[^A-Za-z0-9]#i', '',
$_SESSION['user_password']);
}
public function UserInfoQuery() {
$sql = "SELECT * FROM users WHERE id =
'$this->userID' AND email = '$this->useremail' AND
password = '$this->userPassword' LIMIT 1";
$res = mysql_query($sql) or die(mysql_error());
$userMatch = mysql_numrows($res);
if ($userMatch == 1) {
while($row = mysql_fetch_array($res)) {
$userData = array(
$userFirstname = $row['firstName'],
$userLastname = $row['lastName'],
$userBirthdate = $row['birthDate'],
$userSex = $row['sex'],
$userEmail = $row['email'],
$userCountry = $row['country'],
$userRegion = $row['region']);
}
}
return $userData;
}
}
In my index php file when I try:
$User = new User();
print_r($User->UserInfoQuery());
I have next results:
Array ( [0] => firstname [1] =>
lastname [2] =>
1990-11-23 [3] =>
male [4] =>
mail [5] =>
Srbija [6] => town )
How I can echo just the first and last names?
This:
array($userFirstname = $row['firstName'])
assigns the value of $row['firstName'] to the variable $userFirstname, then puts the result of the assignment (the value of $row['firstName']) into an array. It's the same as writing:
$userFirstname = $row['firstName'];
array($row['firstName']);
To declare an array with the key userFirstname, you need to write:
array('userFirstname' => $row['firstName'])
From here, you have a normal array you can access:
$userinfo = $User->UserInfoQuery();
echo $userinfo['userFirstname'];
This does seem somewhat clunky though, and honestly, you're not using objects very well here. You should save the data queried from the database into properties of the object, then use getters to access those properties one by one or all together. How to design a proper object is a little beyond the scope/point of this answer though.
You should have your array the following way:
$userData = array(
'Firstname' = $row['firstName'],
'lastname = $row['lastName'],
'birthdate = $row['birthDate'],
'sex = $row['sex'],
'email = $row['email'],
'country = $row['country'],
'region = $row['region']
);
}