Displaying array content from function? - php

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

Related

PHP repeated results

I'm having hard time with this issue
I have multiple queries some data appear in other results...
$query = "SELECT * FROM `hotels`";
$result=mysqli_query($connect,$query);
if(mysqli_num_rows($result)>0) {
while($row=mysqli_fetch_array($result)) {
$hotelname = $row['hotel_name'];
$queryPhotos="SELECT * FROM hotel_photo WHERE hotel_id = ".$row['id']." ";
$resultPhotos=mysqli_query($connect,$queryPhotos);
while($rowPhotos=mysqli_fetch_assoc($resultPhotos)) {
$photos[] = array(
"imgUrl" => $rowPhotos['img_url'],
"hotel_id" => $rowPhotos['hotel_id']
);
}
$apiResult[] = array(
'hotel_name' => $hotelname,
'hotel_photos' => $photos,
);
}
header('Content-type: application/json');
echo json_encode($apiResult, JSON_NUMERIC_CHECK);
}
This is my hotel database
and my hotel_photos database
Why I'm still seeing 'hotel_id 1' in dubai hotel...?
Thank you so much for your help.
You aren't empting the $photos array in every new iteration for a new hotel. Hence, the previous results also exists in the array. You need to fix as below:
<?php
while($row = mysqli_fetch_array($result)) {
$hotelname = $row['hotel_name'];
$photos = []; // add this line

Array to string conversion - Laravel 5.6 Error

I am trying to update values in the DB using values from a JSON file:
Code:
$jsonData = file_get_contents($jsonFile);
$data = json_decode($jsonData, true);
//check if hospital exist
$name = explode(' ',trim($data['organisationUnits']['organisationUnit']['name']));
// echo $name[0];
$query = Hospital::where('h_name', 'LIKE' , '%' . $data['organisationUnits']['organisationUnit']['name'] . '%')->first();
if($query){
// echo "\n yupo";
$h_id = $query->id;
$h_slug = $query->h_slug;
$nr_orgUnit = $query->nr_orgUnit;
// echo $nr_orgUnit;
$updateHospital = Hospital::find($h_id);
$updateHospital->h_name = $data["organisationUnits"]["organisationUnit"]["name"];
$updateHospital->h_short_name = $data["organisationUnits"]["organisationUnit"]["shortName"];
$updateHospital->h_code = $data["organisationUnits"]["organisationUnit"]["code"];
$updateHospital->h_opening_date = $data["organisationUnits"]["organisationUnit"]["openingDate"];
$updateHospital->h_closed_date = $data["organisationUnits"]["organisationUnit"]["closedDate"];
$updateHospital->h_active = $data["organisationUnits"]["organisationUnit"]["active"];
$updateHospital->h_comment = $data["organisationUnits"]["organisationUnit"]["comment"];
$updateHospital->h_geo_code = $data["organisationUnits"]["organisationUnit"]["geoCode"];
$updateHospital->h_last_updated = $data["organisationUnits"]["organisationUnit"]["lastUpdated"];
$updateHospital->save();
} else {
// echo 'error';
}
JSON DATA:
{"organisationUnits":{
"organisationUnit":{
"id":"01",
"uuid":{
},
"name":"Isagehe Dispensary",
"shortName":"Isagehe Dispensary ",
"code":"17-04-0118",
"openingDate":"1990-01-01",
"closedDate":{
},
"active":"true",
"comment":{
},
"geoCode":{
},
"lastUpdated":{
}
}
}
}
when i try to run the code, i get the following error:
Array to string conversion (SQL: update `ag_hospitals` set `h_closed_date` = , `h_active` = true, `h_comment` = , `h_geo_code` = , `h_last_updated` = where `id` = 41)"
where might i be wrong?
Note i have also tried updating the following way:
$updateHospital = Hospital::where('id', $h_id)->update([
'h_name' => $data['organisationUnits']['organisationUnit']['name'],
'h_short_name' => $data['organisationUnits']['organisationUnit']['shortName'],
'h_code' => $data['organisationUnits']['organisationUnit']['code'],
'h_opening_date' => $data['organisationUnits']['organisationUnit']['openingDate'],
'h_closed_date' => $data['organisationUnits']['organisationUnit']['closedDate'],
'h_active' => $data['organisationUnits']['organisationUnit']['active'],
'h_comment' => $data['organisationUnits']['organisationUnit']['comment'],
'h_geo_code' => $data['organisationUnits']['organisationUnit']['geoCode'],
'h_last_updated' => $data['organisationUnits']['organisationUnit']['lastUpdated']
]);
You need to define that Attribute in Model that store that JSON Data as Array.
Example:
protected $casts = [
'column_name' => 'array'
];

Auto increment Invoice ID in Code-igniter

i am very new to code igniter /php .
Before i was using randomly generated invoice number like
$invoice_no = rand(9999,9999999999);
But now i wanted to increment invoice number and add current year as a prefix to it . But somewhere i am doing wrong as this code failed execute . Can some one point me in the right direction .
My model is ...
function insertInvoice($data)
{
$this->db->trans_begin();
$invoice = array();
if(!empty($data['client_id']))
{
$invoice['invoice_client_id'] = $data['client_id'];
}else{
$client_data = array(
'client_name' => $data['customername'],
'client_address1' => $data['address1']
);
$this->db->insert('client_details', $client_data);
$insert_id = $this->db->insert_id();
$invoice['invoice_client_id'] = $insert_id;
}
$query = $this->db->query("SELECT * FROM invoice ORDER BY invoice_id DESC LIMIT 1");
$result = $query->result_array(0);
$result ++;
$curYear = date('Y');
$invoice_no = $curYear . '-' .$result;
$invoice['invoice_no'] = $invoice_no;
$invoice['invoice_subtotal'] = $data['subTotal'];
$invoice['invoice_tax'] = $data['tax'];
$invoice['invoice_tax_amount'] = $data['taxAmount'];
$invoice['invoice_total'] = $data['totalAftertax'];
$invoice['invoice_total_extra'] = $data['totalextra'];
$invoice['invoice_rent'] = $data['rent'];
$invoice['invoice_paid'] = $data['amountPaid'];
$invoice['invoice_due'] = $data['amountDue'];
$invoice['invoice_desc'] = $data['notes'];
$invoice['invoice_items_count'] = $data['item_count'];
$invoice['invoice_extra_count'] = $data['extra_count'];
$invoice['invoice_miscellaneous'] = $data['miscellaneous'];
$this->db->insert('invoice', $invoice);
$i=1;
do {
$items = array(
'invoice_no' => $invoice_no,
'item_name' => $data['invoice']['product_name'][$i],
'item_price' => $data['invoice']['product_price'][$i],
'item_qty' => $data['invoice']['product_qty'][$i],
'item_total' => $data['invoice']['total'][$i],
'item_noof_crate_wait' => $data['invoice']['noof_crate_wait'][$i],
'item_crate_wait' => $data['invoice']['crate_wait'][$i],
'item_choot' => $data['invoice']['choot'][$i],
'item_net_quantity' => $data['invoice']['net_qty'][$i]
);
$this->db->insert('invoice_items',$items);
$i++;
} while($i<$data['item_count']);
$j=1;
do {
$extraitems = array(
'invoice_no' => $invoice_no,
'extra_item_name' => $data['extra']['name'][$j],
'extra_item_qunatity' => $data['extra']['qty'][$j],
'extra_item_price' => $data['extra']['price'][$j],
'extra_item_total' => $data['extra']['total'][$j]
);
$this->db->insert('extra_items',$extraitems);
$j++;
} while($j<$data['extra_count']);
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
return FALSE;
}
else
{
$this->db->trans_commit();
return TRUE;
}
}
invoice_id is primary key in DB .
You're attempting to increment the result array but what you really need is to acquire and increment a field value.
//you only need one field so ask only for that
$query = $this->db->query("SELECT invoice_id FROM invoice ORDER BY invoice_id DESC LIMIT 1");
//you really should check to make sure $query is set
// before trying to get a value from it.
//You can add that yourself
//Asked for only one row, so only retrieve one row -> and its contents
$result = $query->row()->invoice_id;
$result ++;
...
I'm guessing you're getting an "Object conversion to String error" on line $invoice_no = $curYear . '-' .$result;
Since $result contains an object and you're using it as a string. Print the $result variable to check how to use the data assigned to it.

Make Such Array For TreeView in PHP Where parent chid hierarchy directly did not exists

I have a function which gives me TreeList if I give him $treeData = array(id=1,Name=Abc, ParentId=null). Normally I have table structure like this so there is no problem to provide such array. Problem starts when I have no such structure in table but my client want TreeList for such structure where parent child hierarchy is not directly exists.
What Table Structure I have
Types
Subjects
Topics
Lessons
LessonTypes
In LessonTypes I have TypeId, SubjectId, TopicId, LessonId
I tried to make an array for my function but it is not quite good please see my code:
private function makeTreeDataArray(){
$treeDataArr = array();
$resourceTestTypesArr = array();
$topicArr = array();
$lessonArr = array();
$testTypeIdPrefix = 'TestType#';
$subjectIdPrefix = 'Subject#';
$topicIdPrefix = 'Topic#';
// $model = new ResourceTestType();
//Get All TestTypes into treeDataArr
$model = new Option();
$TestTypes = $model->where('Type','TestType')->get();
foreach ($TestTypes as $k => $TT) {
$testTypeId = $testTypeIdPrefix . $TT->Id;
$treeDataArr[] = array('Id' => $testTypeId, 'Name'=>$TT->Option, 'ParentId' => null);
$resourceTestTypesArr[] = $TT->resourceTestTypes()->get();
}
// return ($resourceTestTypes);
//****Get All Subjects Of TestType
foreach ($resourceTestTypesArr as $i =>$RTTs) {
foreach ($RTTs as $j => $RTT) {
$subjectId = $subjectIdPrefix . $RTT->SubjectId;
$resourceId =$RTT->ResourceId;
$subjectName = $RTT->subject()->first()->Name;
$testTypeIdAsParentId = $testTypeIdPrefix.$RTT->TestTypeId;
$treeDataArr[] = array('Id' => $subjectId, 'Name'=>$subjectName, 'ParentId' => $testTypeIdAsParentId);
//*** Create dataset for Topics
$topicId = $topicIdPrefix.$RTT->TopicId;
$topicIdWithoutPrefix = $RTT->TopicId;
$topicName = Option::getOptionById('Topics',$topicIdWithoutPrefix)->Display;
$topicArr[] = array('topicId' => $topicId, 'topicName'=>$topicName, 'SubjectId' => $subjectId, 'LessonId' => $resourceId);
}
}
// return ($topicArr);
//Get All Topics Of Subject
foreach ($topicArr as $i =>$T) {
$topicId = $T['topicId'];
$lessonId = $T['LessonId'];
$treeDataArr[] = array('Id' => $topicId, 'Name'=> $T['topicName'], 'ParentId' => $T['SubjectId']);
$lessonName = Lesson::find($lessonId)->Name;
$lessonArr[] = array('lessonId' => $lessonId, 'lessonName'=>$lessonName, 'topicId' => $topicId);
}
// return ($lessonArr);
//Get All Lessons Of Topics
foreach ($lessonArr as $i =>$L) {
$treeDataArr[] = array('Id' => $L['lessonId'], 'Name'=> $L['lessonName'], 'ParentId' => 'Topic#'.$L['topicId']);
}
$result = array_unique($treeDataArr,SORT_REGULAR);
// $result = array_unique($treeDataArr);
return $result;
}
And Result of the function is:
-> A-Type
-> A-Subject Of A-Type
-> A-Topic Of A-Subject
-> A-Lesson Of A-Topic
-> B-Topic Of A-Subject
-> A-Lesson Of B-Topic
-> B-Type
-> A-Subject Of A-Type
Notice: A-Subject Appear again here which is not correct it should be appear only inside the A-Type
It happens all others also. Please help me what's wrong with my code. Thanks in advance

Hook to Add a Value in a SugarCRM Custom Field

I am new to SugarCRM. I've created a custom field named 'account name' in the Meetings module so that if we select Contacts from related to field, the 'account name' of that Contact is automatically added to the field.
Here's my code:
$hook_array['after_retrieve'] = Array();
$hook_array['after_retrieve'][] = Array(1, 'Add custom account',
'custom/modules/Meetings/AddAccount.php','AddAccount', 'addAcc');
LogicHook:
class AddAccount
{
public function addAcc(&$bean, $event, $arguments)
{
global $current_user;
global $db;
echo "<pre>";
$meeting_id = $_REQUEST['record'];
$query = "SELECT * FROM `meetings_contacts` WHERE `meeting_id` LIKE '$meeting_id'";
$result = $bean->db->query($query, true, " Error filling in additional detail fields: ");
if ($bean->db->getRowCount($result) > 0) {
while ($row = $bean->db->fetchByAssoc($result)) {
$contact_id = $row['contact_id'];
}
if (isset($contact_id)) {
$query1 = "SELECT * FROM `accounts_contacts` WHERE `contact_id` LIKE '$contact_id'";
$result1 = $bean->db->query($query1, true, " Error filling in additional detail fields: ");
while ($row1 = $bean->db->fetchByAssoc($result1)) {
$account_id = $row1['account_id'];
}
$query2 = "SELECT * FROM `accounts` WHERE `id` LIKE '$account_id'";
$result2 = $bean->db->query($query2, true, " Error filling in additional detail fields: ");
while ($row2 = $bean->db->fetchByAssoc($result2)) {
$account_name = $row2['name'];
}
$update_custom_account = "UPDATE `meetings_cstm` SET `accountname_c` = '$account_name' WHERE `meetings_cstm`.`id_c` = '$meeting_id';";
$Change = $bean->db->query($update_custom_account);
}
}
}
}
The problem is that the field is getting added but the "i" in the ListView has stopped working. Is there a simpler way than this long query?
Thanks in advance.
This is a better way of doing the above.
custom/modules/Meetings/logic_hooks.php
// position, file, function
$hook_array['after_retrieve'] = Array();
$hook_array['after_retrieve'][] = Array(1, 'Add custom account', 'custom/modules/Meetings/AddAccount.php', 'AddAccount', 'getAccountName');
$hook_array['after_save'] = Array();
$hook_array['after_save'][] = Array(1, 'Add custom account', 'custom/modules/Meetings/AddAccount.php', 'AddAccount', 'getAccountName');
custom/modules/Meetings/AddAccount.php
class AddAccount {
public function getAccountName(&$bean, $event, $arguments) {
if ($bean->parent_type == 'Contacts') {
$contact = BeanFactory::getBean('Contacts', $bean->parent_id);
$contact->load_relationship('accounts_contacts');
$account = BeanFactory::getBean('Accounts', $contact->account_id);
$bean->account_name_c = $account->name;
}
}
}
This way, you are using the bean and not SQL.
EDIT:
To add the new field, you can create this fileā€¦
custom/Extension/modules/Meetings/Ext/Vardefs/account_name_c.php
<?php
$dictionary['Meeting']['fields']['account_name_c'] =
array (
'name' => 'account_name_c',
'vname' => 'LBL_ACCOUNT_NAME_C',
'type' => 'varchar',
'len' => '255',
'unified_search' => true,
'comment' => 'Account name for meeting',
'studio' => 'true',
);
Then after a Repair/Rebuild, go to Studio > Meetings > Layouts > ListView and drag/drop the new field from 'Hidden' to 'Default.' Select the 'Save & Deploy' button, and after saving the Meeting record, your account name will appear in the list view.

Categories