Pass variables through include (another php file) in php - php

I'm working on a php web application for a website, and I would like to pass some variables from one php file to another. I have tried the old fashion way with the include file but was not successful. I also tried to set the variables in global scope but still not working. The code in first.php file is:
function rc_getAvailableVehicles($pickup_timestamp, $return_timestamp, $vehicle_classes=array()) {
global
$wpdb;
$rc_currency = RC_Registry::get('rc_currency');
$where_classes = "";
if ($vehicle_classes) {
foreach($vehicle_classes as $vehicle_class) {
$where_classes[] = " v.class = '". $wpdb->escape($vehicle_class) ."'";
}
$where_classes = "AND (".implode(' OR ', $where_classes).") ";
}
$sql = "SELECT *
FROM ".$wpdb->rc_vehicles." v
WHERE v.quantity > (SELECT COUNT(*) FROM ".$wpdb->rc_bookings." b WHERE b.vehicle_id = v.vehicle_id AND ((UNIX_TIMESTAMP(b.pickup_date) >= '". (int)$pickup_timestamp ."' AND UNIX_TIMESTAMP(b.pickup_date) < '". (int)$return_timestamp ."') || (UNIX_TIMESTAMP(b.pickup_date) < '". (int)$pickup_timestamp ."' AND UNIX_TIMESTAMP(b.return_date) >= '". (int)$pickup_timestamp ."')) AND (b.status != 'new' AND b.status != 'canceled') AND b.trash = '0') ".$where_classes."AND v.status = '1' AND v.archive = '0'
ORDER BY v.rent ASC";
$results = $wpdb->get_results($sql,ARRAY_A);
$vehicles = array();
$rental_days = ceil(($return_timestamp-$pickup_timestamp)/91800);
$xfee = get_field('another_location_fee');
$xfee2 = get_field('return_to_another_location_fee_2');
if ($results) {
foreach ($results as $result) {
if ($result['image'] && file_exists(RC_UPLOADS_DIR . "vehicle_" . $result['image'])) {
$image = RC_UPLOADS_URL . 'vehicle_' . $result['image'];
$image_thumb = RC_UPLOADS_URL . 'cache/' . rc_image_resize(RC_UPLOADS_DIR . "vehicle_" . $result['image'], 220, 160);
} else {
$image = '';
$image_thumb = '';
}
$result['description'] = do_shortcode($result['description']);
$description = html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8');
global $GeneralPrice, $discount_price, $rent1, $rent5;
include_once ('file2.php');
//$GeneralPrice = $result['rent'];
$rent1 = $vehicle_meta['rent1'];
$rent2 = $vehicle_meta['rent2'];
$rent3 = $vehicle_meta['rent3'];
$rent4 = $vehicle_meta['rent4'];
$rent5 = $vehicle_meta['rent5'];
$rent6 = $vehicle_meta['rent6'];
$rent7 = $vehicle_meta['rent7'];
$rent8 = $vehicle_meta['rent8'];
$rent9 = $vehicle_meta['rent9'];
$rent10 = $vehicle_meta['rent10'];
$rent11 = $vehicle_meta['rent11'];
$rent12 = $vehicle_meta['rent12'];
$rent13 = $vehicle_meta['rent13'];
$rent14 = $vehicle_meta['rent14'];
$rent15 = $vehicle_meta['rent15'];
$rent16 = $vehicle_meta['rent16'];
$rent17 = $vehicle_meta['rent17'];
$rent18 = $vehicle_meta['rent18'];
$rent19 = $vehicle_meta['rent19'];
$rent20 = $vehicle_meta['rent20'];
$rent21 = $vehicle_meta['rent21'];
$rent22 = $vehicle_meta['rent22'];
$rent23 = $vehicle_meta['rent23'];
$rent24 = $vehicle_meta['rent24'];
$rent25 = $vehicle_meta['rent25'];
$rent26 = $vehicle_meta['rent26'];
$rent27 = $vehicle_meta['rent27'];
$rent28 = $vehicle_meta['rent28'];
$rent29 = $vehicle_meta['rent29'];
$rent30 = $vehicle_meta['rent30'];
$rent31 = $vehicle_meta['rent31'];
$rent32 = $vehicle_meta['rent32'];
$rent33 = $vehicle_meta['rent33'];
$rent34 = $vehicle_meta['rent34'];
$rent35 = $vehicle_meta['rent35'];
$rent36 = $vehicle_meta['rent36'];
$vehicle_meta = rc_getVehicleMeta($result['vehicle_id']);
$vehicles[$result['vehicle_id']] = array(
'vehicle_id' => $result['vehicle_id'],
'title' => $result['manufacturer']." ".$result['series'],
'manufacturer' => $result['manufacturer'],
'series' => $result['series'],
'year' => $result['year'],
'class' => $result['class'],
'image' => $image,
'image_thumb' => $image_thumb,
'description' => $description,
'seats' => $vehicle_meta['seats'],
'doors' => $vehicle_meta['doors'],
'baggages' => $vehicle_meta['baggages'],
'conditioning' => $vehicle_meta['conditioning'],
'transmission' => $vehicle_meta['transmission'],
'rent1' => $vehicle_meta['rent1'],
'rent2' => $vehicle_meta['rent2'],
'rent3' => $vehicle_meta['rent3'],
'rent4' => $vehicle_meta['rent4'],
'rent5' => $vehicle_meta['rent5'],
'rent6' => $vehicle_meta['rent6'],
'rent7' => $vehicle_meta['rent7'],
'rent8' => $vehicle_meta['rent8'],
'rent9' => $vehicle_meta['rent9'],
'rent10' => $vehicle_meta['rent10'],
'rent11' => $vehicle_meta['rent11'],
'rent12' => $vehicle_meta['rent12'],
'rent13' => $vehicle_meta['rent13'],
'rent14' => $vehicle_meta['rent14'],
'rent15' => $vehicle_meta['rent15'],
'rent16' => $vehicle_meta['rent16'],
'rent17' => $vehicle_meta['rent17'],
'rent18' => $vehicle_meta['rent18'],
'rent19' => $vehicle_meta['rent19'],
'rent20' => $vehicle_meta['rent20'],
'rent21' => $vehicle_meta['rent21'],
'rent22' => $vehicle_meta['rent22'],
'rent23' => $vehicle_meta['rent23'],
'rent24' => $vehicle_meta['rent24'],
'rent25' => $vehicle_meta['rent25'],
'rent26' => $vehicle_meta['rent26'],
'rent27' => $vehicle_meta['rent27'],
'rent28' => $vehicle_meta['rent28'],
'rent29' => $vehicle_meta['rent29'],
'rent30' => $vehicle_meta['rent30'],
'rent31' => $vehicle_meta['rent31'],
'rent32' => $vehicle_meta['rent32'],
'rent33' => $vehicle_meta['rent33'],
'rent34' => $vehicle_meta['rent34'],
'rent35' => $vehicle_meta['rent35'],
'rent36' => $vehicle_meta['rent36'],
'total_price' => $rc_currency->format((($rental_days*$GeneralPrice)-(($rental_days*$GeneralPrice) * ($discount_price)/100)+ $utime)),
'total_price_return_fee' => $rc_currency->format((($rental_days*$result['rent']) - ($rental_days*$result['rent']) * ($discount_price)/100)+ $xfee),
'total_price_return_fee2' => $rc_currency->format((($rental_days*$result['rent']) - ($rental_days*$result['rent'])*($discount_price)/100)+ $xfee2),
'daily_price' => $rc_currency->format((($GeneralPrice)-($GeneralPrice)*($discount_price)/100)+ ($utime / $rental_days)),
'daily_price_return_fee' => $rc_currency->format(($result['rent']-($result['rent'])* ($discount_price)/100)+ ($xfee / $rental_days)),
'daily_price_return_fee2' => $rc_currency->format(($result['rent']-($result['rent'])*($discount_price)/100) + ($xfee2 / $rental_days))
);
}
}
return $vehicles;
}
and I want to echo all the $rent variables in file2.php
I have tried the
echo $rent; without success!

You have problems with the order of the code
$vehicle_meta = rc_getVehicleMeta($result['vehicle_id']);
Should be BEFORE you populate rent variables, and
include_once ('file2.php');
Should be AFTER you populated rent variables.

You need to call a function in file1.php that exists in file2.php
ex. in file1.php you could call the function return_rent
return_rent($rent);
in file2 then you make the function
function return_rent($var){
echo $rent;
}

$pass = "anything";
include_once ('file2.php');
From file2.php you can access $pass variable.

Related

Hello! I'm trying to insert rows in my mysql db using contact form 7

I'm trying to insert rows in my MySQL DB using contact form 7.
But it doesn't insert those elements, just five I see inserted.
Is there any limit for the array?
Tks a lot.
I'm using this code:
function contactform7_before_send_mail( $form_to_DB ) {
//set your db details
$mydb = new wpdb('test','test,','test','test');
$form_to_DB = WPCF7_Submission::get_instance();
if ( $form_to_DB )
$formData = $form_to_DB->get_posted_data();
$localorigem = $formData['local-origem'];
$dataatendimento = $formData['data-atendimento'];
$numeroprontuario = $formData['numero-prontuario'];
$numerocartaosus = $formData['numero-cartao-sus'];
$nomeusuario = $formData['nome-usuario'];
$sexo = $formData['sexo'];
$gestante = $formData=['gestante'];
$idgestacional = $formData=['id-gestacional'];
$datanascimento = $formData=['data-nascimento'];
$estadocivil = $formData=['estado-civil'];
$racacor = $formData=['raca-cor'];
$escolaridadeanos = $formData=['escolaridade-anos'];
$ocupacaotexto = $formData=['ocupacao-texto'];
$mydb->insert(
'test', array(
'local-origem' =>$localorigem,
'data-atendimento' =>$dataatendimento,
'numero-prontuario' =>$numeroprontuario,
'numero-cartao-sus' => $numerocartaosus,
'nome-usuario' => $nomeusuario,
'data-nascimento' => $datanascimento,
'id-gestacional' => $idgestacional,
'data-nascimento' = $datanascimento,
'estado-civil' = $estadocivil,
'raca-cor' = $racacor,
'escolaridade-anos' = $escolaridadeanos,
'ocupacao-texto' = $ocupacaotexto
) );
}
remove_all_filters ('wpcf7_before_send_mail');
add_action( 'wpcf7_before_send_mail', 'contactform7_before_send_mail' );
Please change this. UPDATED Answer
$gestante = $formData=['gestante'];
$idgestacional = $formData=['id-gestacional'];
$datanascimento = $formData=['data-nascimento'];
$estadocivil = $formData=['estado-civil'];
$racacor = $formData=['raca-cor'];
$escolaridadeanos = $formData=['escolaridade-anos'];
$ocupacaotexto = $formData=['ocupacao-texto'];
$mydb->insert(
'test', array(
'local-origem' =>$localorigem,
'data-atendimento' =>$dataatendimento,
'numero-prontuario' =>$numeroprontuario,
'numero-cartao-sus' => $numerocartaosus,
'nome-usuario' => $nomeusuario,
'data-nascimento' => $datanascimento,
'id-gestacional' => $idgestacional,
'data-nascimento' = $datanascimento,
'estado-civil' = $estadocivil,
'raca-cor' = $racacor,
'escolaridade-anos' = $escolaridadeanos,
'ocupacao-texto' = $ocupacaotexto
) );
To
$gestante = $formData['gestante'];
$idgestacional = $formData['id-gestacional'];
$datanascimento = $formData['data-nascimento'];
$estadocivil = $formData['estado-civil'];
$racacor = $formData['raca-cor'];
$escolaridadeanos = $formData['escolaridade-anos'];
$ocupacaotexto = $formData['ocupacao-texto'];
$mydb->insert(
'test', array(
'local-origem' =>$localorigem,
'data-atendimento' =>$dataatendimento,
'numero-prontuario' =>$numeroprontuario,
'numero-cartao-sus' => $numerocartaosus,
'nome-usuario' => $nomeusuario,
'data-nascimento' => $datanascimento,
'id-gestacional' => $idgestacional,
'data-nascimento' => $datanascimento,
'estado-civil' => $estadocivil,
'raca-cor' => $racacor,
'escolaridade-anos' => $escolaridadeanos,
'ocupacao-texto' => $ocupacaotexto
) );

How to parse and write .ini file in codeigniter PHP?

I am uploading a INI file in Codeigniter.
I file upload a file with some parameters but its values are blank, and i store the file and file-path in database.
Now, I want to let user write some values to that file.
So i open the file and let user add some values to it.
But when i save the file its doesn't get stored the way i want.
Current Result
SipUserName = ""
SipAuthName = ""
DisplayName = ""
Password = ""
Domain = ""
Proxy = ""
Port = ""
ServerMode = ""
UCServer = 123456
UCPassword = 123456
DP_Exception = 123456
DP_Rule1 = 123456
DP_Rule2 = 123456
OperationMode = 123456
MutePkey = 123456
Codec = 123456
PTime = 123456
AudioMode = 123456
SoftwareAEC = 123456
EchoTailLength = 123456
PlaybackBuffer = 123456
CaptureBuffer = 123456
JBPrefetchDelay = 123456
JBMaxDelay = 123456
SipToS = ""
RTPToS = 123456
LogLevel = 123456
Expected Result:
[INIDetails]
SipUserName =
SipAuthName =
DisplayName =
Password =
Domain =
Proxy =
Port =
ServerMode =
UCServer = 123456
UCPassword = 123456
[DialPlan]
DP_Exception = 123456
DP_Rule1 = 123456
DP_Rule2 = 123456
[Advanced]
OperationMode = 123456
MutePkey = 123456
Codec = 123456
PTime = 123456
AudioMode = 123456
SoftwareAEC = 123456
EchoTailLength = 123456
PlaybackBuffer = 123456
CaptureBuffer = 123456
JBPrefetchDelay = 123456
JBMaxDelay = 123456
SipToS =
RTPToS = 123456
LogLevel = 123456
Below is my code:
public function edit_ini($id)
{
/*The ID wen get from View's URI*/
$path = "./uploads/";
$site = $this->session->userdata('site');
/*Set the path to open the file*/
$this->db->select('*');
$this->db->where('site_key',$site);
$this->db->where('id',$id);
/*Here the id it the ID we got in URI from View*/
$this->db->from('base_ini');
$query = $this->db->get();
$result = $query->row();
$filename= $result->base_ini_filename;
$path= $result->file_path;
echo $this->db->last_query();
/*Setting the Path and the filename from database.*/
file_get_contents($path.$filename);
/*Get All The Contents from that file*/
$this->data['params'] = $this->parameter_m->get();
/*Getting the parameters to display on view*/
$this->data['parameters'] = parse_ini_file($path.$filename,true);
$insert = array(
'SipUserName' => $this->input->post('SipUserName'),
'SipAuthName' => $this->input->post('SipAuthName'),
'DisplayName' => $this->input->post('DisplayName'),
'Password' => $this->input->post('Password'),
'Domain' => $this->input->post('Domain'),
'Proxy' => $this->input->post('Proxy'),
'Port' => $this->input->post('Port'),
'ServerMode' => $this->input->post('ServerMode'),
'UCServer' => $this->input->post('UCServer'),
'UCPassword' => $this->input->post('UCPassword'),
'DP_Exception' => $this->input->post('DP_Exception'),
'DP_Rule1' => $this->input->post('DP_Rule1'),
'DP_Rule2' => $this->input->post('DP_Rule2'),
'OperationMode' => $this->input->post('OperationMode'),
'MutePkey' => $this->input->post('MutePkey'),
'Codec' => $this->input->post('Codec'),
'PTime' => $this->input->post('PTime'),
'AudioMode' => $this->input->post('AudioMode'),
'SoftwareAEC' => $this->input->post('SoftwareAEC'),
'EchoTailLength' => $this->input->post('EchoTailLength'),
'PlaybackBuffer' => $this->input->post('PlaybackBuffer'),
'CaptureBuffer' => $this->input->post('CaptureBuffer'),
'JBPrefetchDelay' => $this->input->post('JBPrefetchDelay'),
'JBMaxDelay' => $this->input->post('JBMaxDelay'),
'SipToS' => $this->input->post('SipToS'),
'RTPToS' => $this->input->post('RTPToS'),
'LogLevel' => $this->input->post('LogLevel')
);
$this->load->helper('file');
$file = $path.$filename;
function write_php_ini($array, $file)
{
$res = array();
foreach($array as $key => $val)
{
if(is_array($val))
{
$res[] = "[$key]";
foreach($val as $skey => $sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"');
}
else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
}
safefilerewrite($file, implode("\r\n", $res));
}
function safefilerewrite($fileName, $dataToSave)
{ if ($fp = fopen($fileName, 'w'))
{
$startTime = microtime(TRUE);
do
{ $canWrite = flock($fp, LOCK_EX);
// If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
if(!$canWrite) usleep(round(rand(0, 100)*1000));
} while ((!$canWrite)and((microtime(TRUE)-$startTime) < 5));
//file was locked so now we can store information
if ($canWrite)
{ fwrite($fp, $dataToSave);
flock($fp, LOCK_UN);
}
fclose($fp);
}
}
/*Inserting The Data into .ini File*/
write_php_ini($insert,$file);
/*Back to you index page id data is submmited*/
if(isset($_POST['submit'] ))
{
redirect('customer/upload_ini/index');
}
$this->data['subview'] = 'customer/upload/edit_ini';
$this->load->view('customer/_layout_main', $this->data);
}
I want to print the sections into file.
This is not a complete solution, but some corrections to do to your code
First thing : please avoid the ternary operator, your code must always be as clear as possible, also you haven't planned the case where your value is null/empty
please try as follow
foreach($val as $skey => $sval) {
$configPrefix = $skey . ' = ';
if (!is_null($sval) && !empty($sval)) {
if (is_numeric($sval)) {
$res[] = $configPrefix . $sval;
}
else if (is_string($sval)) {
$res[] = $configPrefix . "'" .
$sval . "'" ;
}
else {
// TODO Log/throw exception for your unhandled case ...
}
}
}
Also you didn't decomposed your $insert array by sections, so use this and adapt your code to write sections in your ini file
$insert = array(
'INIDetails' => array(
'SipUserName' => $this->input->post('SipUserName'),
'SipAuthName' => $this->input->post('SipAuthName'),
'DisplayName' => $this->input->post('DisplayName'),
'Password' => $this->input->post('Password'),
'Domain' => $this->input->post('Domain'),
'Proxy' => $this->input->post('Proxy'),
'Port' => $this->input->post('Port'),
'ServerMode' => $this->input->post('ServerMode'),
'UCServer' => $this->input->post('UCServer'),
'UCPassword' => $this->input->post('UCPassword')
),
'DialPlan' => array(
'DP_Exception' => $this->input->post('DP_Exception'),
'DP_Rule1' => $this->input->post('DP_Rule1'),
'DP_Rule2' => $this->input->post('DP_Rule2')
),
'Advanced' => array(
'OperationMode' => $this->input->post('OperationMode'),
'MutePkey' => $this->input->post('MutePkey'),
'Codec' => $this->input->post('Codec'),
'PTime' => $this->input->post('PTime'),
'AudioMode' => $this->input->post('AudioMode'),
'SoftwareAEC' => $this->input->post('SoftwareAEC'),
'EchoTailLength' => $this->input->post('EchoTailLength'),
'PlaybackBuffer' => $this->input->post('PlaybackBuffer'),
'CaptureBuffer' => $this->input->post('CaptureBuffer'),
'JBPrefetchDelay' => $this->input->post('JBPrefetchDelay'),
'JBMaxDelay' => $this->input->post('JBMaxDelay'),
'SipToS' => $this->input->post('SipToS'),
'RTPToS' => $this->input->post('RTPToS'),
'LogLevel' => $this->input->post('LogLevel')
)
);
parse_ini_file(), and work on the associative array.
sample:
$ini_array = parse_ini_file("sample.ini", true);
print_r($ini_array);
you have to pass true as second argument to get correct format.

Looping through character data and items from MySQL DB in PHP

I have the following code:
include "config.php";
error_reporting(0);
$idSuccess = 0;
if(isset($_POST['userName']))
{
$usr = $_POST['userName'];
$pwd = $_POST['userPwd'];
$sqlQ = "SELECT * FROM dr_users where dr_user_name='$usr' AND dr_user_pwd='$pwd' LIMIT 1";
$q = mysql_query($sqlQ);
if(mysql_num_rows($q) > 0)
{
$userO = mysql_fetch_assoc($q);
$userData = array('userID' => $userO['dr_user_id'], 'userName' => $userO['dr_user_name'], 'userPwd' => $userO['dr_user_pwd'], 'userEml' => $userO['dr_user_email'], 'privLvl' => $userO['dr_user_priv_level']);
$idSuccess = 1;
$uID = $userO['dr_user_id'];
$charQ = mysql_query("SELECT * FROM dr_chars WHERE dr_user_id='$uID'");
while($char = mysql_fetch_array($charQ))
{
$chars[] = $char;
$charID = $char['dr_char_id'];
$itemQ = mysql_query("SELECT * FROM dr_items WHERE dr_char_id='$charID'");
while($item = mysql_fetch_array($itemQ))
{
$itemData[] = array('itemID' => $item['dr_item_id'], 'itemName' => $item['dr_item_name'], 'itemDesc' => $item['dr_item_desc'], 'itemType' => $item['dr_item_type'], 'itemCost' => $item['dr_item_cost'], 'itemCurType' => $item['dr_item_cur_type'], 'itemAtk' => $item['dr_item_stat_atk'], 'itemDef' => $item['dr_item_stat_def'], 'itemEnd' => $item['dr_item_stat_end'], 'itemLuck' => $item['dr_item_stat_luck'], 'itemFileURL' => $item['dr_item_file_url'], 'itemStaff' => $item['dr_item_staff'], 'itemEquipped' => $item['dr_char_eqp'], 'spX' => $item['dr_static_pos_x'], 'spY' => $item['dr_static_pos_y']);
}
$charData[] = array('charID' => $char['dr_char_id'], 'charName' => $char['dr_char_name'], 'charRace' => $char['dr_char_race'], 'charLvl' => $char['dr_char_lvl'], 'charItems' => $itemData);
}
$resData = array('idSuccess' => $idSuccess, 'user' => $userData, 'chars' => $charData);
} else {
$resData = array('idSuccess' => $idSuccess);
}
echo json_encode($resData);
}
?>
I have successfully loaded character data from the table 'dr_chars' in my database. I'm trying to load the corresponding item data from the retrieved character ID and push it into the $charData array. So I can then easily encode & output it in a JSON format.
If my question isn't clear just ask and I'll try to explain the situation better. The JSON data is being outputted into flash for dynamic use.
I managed to fix this final code as follows:
<?php
include "config.php";
error_reporting(0);
$idSuccess = 0;
if(isset($_POST['userName']))
{
$usr = $_POST['userName'];
$pwd = $_POST['userPwd'];
$sqlQ = "SELECT * FROM dr_users where dr_user_name='$usr' AND dr_user_pwd='$pwd' LIMIT 1";
$q = mysql_query($sqlQ);
if(mysql_num_rows($q) > 0)
{
$userO = mysql_fetch_assoc($q);
$userData = array('userID' => $userO['dr_user_id'], 'userName' => $userO['dr_user_name'], 'userPwd' => $userO['dr_user_pwd'], 'userEml' => $userO['dr_user_email'], 'privLvl' => $userO['dr_user_priv_level']);
$idSuccess = 1;
$uID = $userO['dr_user_id'];
$charQ = mysql_query("SELECT * FROM dr_chars WHERE dr_user_id='$uID'");
$chars = array();
while($char = mysql_fetch_array($charQ))
{
$charID = $char['dr_char_id'];
$itemQ = mysql_query("SELECT * FROM dr_items WHERE dr_char_id='$charID'");
$items = array();
while($item = mysql_fetch_array($itemQ))
{
$items[] = array('itemID' => $item['dr_item_id'], 'itemName' => $item['dr_item_name'], 'itemDesc' => $item['dr_item_desc'], 'itemType' => $item['dr_item_type'], 'itemCost' => $item['dr_item_cost'], 'itemCurType' => $item['dr_item_cur_type'], 'itemAtk' => $item['dr_item_stat_atk'], 'itemDef' => $item['dr_item_stat_def'], 'itemEnd' => $item['dr_item_stat_end'], 'itemLuck' => $item['dr_item_stat_luck'], 'itemFileURL' => $item['dr_item_file_url'], 'itemStaff' => $item['dr_item_staff'], 'itemEquipped' => $item['dr_char_eqp'], 'spX' => $item['dr_static_pos_x'], 'spY' => $item['dr_static_pos_y']);
}
$chars[] = array('charID' => $char['dr_char_id'], 'charName' => $char['dr_char_name'], 'charRace' => $char['dr_char_race'], 'charLvl' => $char['dr_char_lvl'], 'charItems' => $items);
}
$resData = array('idSuccess' => $idSuccess, 'user' => $userData, 'chars' => $chars);
} else {
$resData = array('idSuccess' => $idSuccess);
}
echo json_encode($resData);
}
?>

How to dynamicly get a multi dimensional array?

My code just populates the last array in the array $workshops
my loop function populates array $workshops, like so
while (ECSE_purchase::have_products()) {
ECSE_purchase::the_product();
$prodid = ECSE_purchase_product::get_the_ID();
$workshop_data = ETICKETDATA::get_workshop_details_helper($prodid);
$workshops = array();
if($prodid == 565) {
............
} else {
$workshopsTmp = array();
$workshopsTmp['workshop_barcode'] = $data['workshop_barcode'];
$workshopsTmp['workshop_id'] = ECSE_purchase_product::get_the_ID();
$workshopsTmp['workshop_title'] = ECSE_purchase_product::get_the_name();
$workshopsTmp['workshop_time'] = $workshop_data['time'];
$workshopsTmp['workshop_room'] = $workshop_data['room'];
$workshopsTmp['workshop_num_of_tickets'] = ECSE_purchase_product::get_the_QTY();
$workshops[] = $workshopsTmp;
}
But here i just get the last array and not like this:
$workshops = array(array('workshop_barcode' => '0101010101',
'workshop_id' => '589',
'workshop_title' => 'Swimming',
'workshop_time' => '12:00',
'workshop_room' => 'Room 1',
'workshop_num_of_tickets' => '2'),
array('workshop_barcode' => '03030303003',
'workshop_id' => '568',
'workshop_title' => 'Running',
'workshop_time' => '15:00',
'workshop_room' => 'Room 3',
'workshop_num_of_tickets' => '3'),
array('workshop_barcode' => '0505050505',
'workshop_id' => '570',
'workshop_title' => 'Biking',
'workshop_time' => '16:00',
'workshop_room' => 'Room 2',
'workshop_num_of_tickets' => '2'));
Any pointers appreciated.
regards,
just edit the loop
You keep redefining your initial array. Try putting $workshops array before while loop
$workshops = array();
while (ECSE_purchase::have_products()) {
ECSE_purchase::the_product();
$prodid = ECSE_purchase_product::get_the_ID();
$workshop_data = ETICKETDATA::get_workshop_details_helper($prodid);
if($prodid == 565) {
............
} else {
$workshopsTmp = array();
$workshopsTmp['workshop_barcode'] = $data['workshop_barcode'];
$workshopsTmp['workshop_id'] = ECSE_purchase_product::get_the_ID();
$workshopsTmp['workshop_title'] = ECSE_purchase_product::get_the_name();
$workshopsTmp['workshop_time'] = $workshop_data['time'];
$workshopsTmp['workshop_room'] = $workshop_data['room'];
$workshopsTmp['workshop_num_of_tickets'] = ECSE_purchase_product::get_the_QTY();
$workshops[] = $workshopsTmp;
}

Cakephp set function not passing variables from controller to the view

I'm trying to pass variable to the view and this one is very weird as the naming and directory structure is correct. Below is the function in my controller:
public function validate_apply_link(){
App::uses('CakeEmail', 'Network/Email');
$this->layout = 'blank';
$listings = $this->CareersAndJob->query("
SELECT l.sid, l.title, lp.value, u.CompanyName, u.WebSite
FROM listings l
LEFT JOIN listings_properties lp
ON lp.object_sid = l.sid
LEFT JOIN users u
ON u.sid = l.user_sid
WHERE l.active = 1
AND lp.add_parameter = 2
AND l.JobGateSenderReference IS NULL
AND u.CompanyName != 'AECOM'
ORDER BY u.CompanyName ASC
LIMIT 5
");
$doc = new DOMDocument();
ob_start();
$listing_count = count($listings);
echo nl2br("Checking $listing_count active jobs...\n\n");
$i=0;
foreach($listings as $listing){
$sid = $listing['l']['sid'];
$url = $listing['lp']['value'];
$company_name = $listing['u']['CompanyName'];
$title = htmlspecialchars($listing['l']['title']);
$length = strpos($title, "-");
if($length != 0){
$title = substr($title, 0, $length-1);
}
$title = substr($title, 0, $length-1);
$title = substr($title, 0, 10);
$data = $this->curl($url);
$check_pdf = strpos($data['info']['content_type'], "pdf");
if($check_pdf != false){
$outputs['data'][$i]['url'] = $url;
$outputs['data'][$i]['sid'] = $sid;
$outputs['data'][$i]['title'] = $title;
$outputs['data'][$i]['company_name'] = $company_name;
$outputs['data'][$i]['our_link'] = "http://careersandjobs.com.au/display-job/{$sid}";
$outputs['data'][$i]['content_type'] = $data['info']['content_type'];
$outputs['data'][$i]['data_type'] = 'pdf';
$i++;
continue;
}
#$doc->loadHTML($data['results']);
$html = $doc->saveHTML();
$xpath = new DOMXpath($doc);
$body = $doc->getElementsByTagName('body')->item(0);
$parsed_url = parse_url($url);
switch($parsed_url['host']){
case "www.michaelpage.com.au":
parse_str($url);
$exist = $xpath->query("//*[contains(#value,'{$ref}')]");
break;
case "https://vacancies.mackay.qld.gov.au":
parse_str($url);
$exist = $xpath->query("//*[contains(#value,'{$title}')]");
break;
default:
$exist = $xpath->query("//*[contains(text(),'{$title}')]");
break;
}
if($exist->length == 0){
if(strpos($url, '#') == false){
$outputs['data'][$i]['url'] = $url;
$outputs['data'][$i]['sid'] = $sid;
$outputs['data'][$i]['title'] = $title;
$outputs['data'][$i]['company_name'] = $company_name;
$outputs['data'][$i]['our_link'] = "http://careersandjobs.com.au/display-job/{$sid}";
$outputs['data'][$i]['content_type'] = $data['info']['content_type'];
$response_code = $this->http_response_codes($data['info']['http_code']);
$outputs['data'][$i]['response_code'] = $response_code;
$outputs['data'][$i]['data_type'] = 'title_not_found';
}else{
$outputs['data'][$i]['data_type'] = 'no_iframe';
}
$i++;
}
flush();
ob_flush();
}
$this->set(compact('outputs'));
}
I can do pr on the outputs variable in the view but this outputs to NULL but when I delete the entire bunch of code inside the controller function and just pass a test variable through it works.
Is there something wrong with the function that I am not aware of?
No errors were found in the above function by the way
app/Controller/CareersAndJobsController.php (line 1048)
array(
'data' => array(
(int) 0 => array(
'url' => 'http://bawbawshire.currentjobs.com.au/cvbuilder/apply+for+this+job/no/1225055',
'sid' => '3649',
'title' => 'Graduate P',
'company_name' => 'Baw Baw Shire Council',
'our_link' => 'http://careersandjobs.com.au/display-job/3649',
'content_type' => 'text/html; charset=utf-8',
'response_code' => 'OK',
'data_type' => 'title_not_found'
),
(int) 1 => array(
'url' => 'http://bawbawshire.currentjobs.com.au/cvbuilder/apply+for+this+job/no/1225724',
'sid' => '3726',
'title' => 'Program &a',
'company_name' => 'Baw Baw Shire Council',
'our_link' => 'http://careersandjobs.com.au/display-job/3726',
'content_type' => 'text/html; charset=utf-8',
'response_code' => 'OK',
'data_type' => 'title_not_found'
),
(int) 2 => array(
'url' => 'http://bawbawshire.currentjobs.com.au/cvbuilder/apply+for+this+job/no/1225826',
'sid' => '3727',
'title' => 'Road Netwo',
'company_name' => 'Baw Baw Shire Council',
'our_link' => 'http://careersandjobs.com.au/display-job/3727',
'content_type' => 'text/html; charset=utf-8',
'response_code' => 'OK',
'data_type' => 'title_not_found'
)
)
)
This is what I am getting from outputs variable just before it gets set by the set function in controller
Any reason you chose to use CakePHP? Because you seem to not make use of its functionality!
You're using literal SQL queries, therefore basically skipping the Models functionality.
You're outputting your content from your Controller? Be careful when using output buffering, this may conflict with CakePHP's inner workings, which also relies on output buffering in many cases. Because you're already outputting the content here (ob_flush()), you'll be outputting your content before your View is reached..
Normally I would point to specific points in the manual, however, because there's so much wrong here, I would suggest to start reading at the beginning

Categories