php script executes but no output - php

I have gone through all the similar questions and nothing fits the bill.
I am running a big script, which ran on chron on an old server but failed on the new so I am working on and testing in browser.
I have two functions, one pulls properties from the database, and then runs them through another which converts the price into 4 currencies, and if the value is different updates the row. The functions are as follows:
<?php
function convert_price($fore_currency, $aft_currency, $amount)
{
echo "going into convert<br/>";
$url = "http://www.currency.me.uk/remote/ER-ERC-AJAX.php?ConvertFrom=" . $fore_currency .
"&ConvertTo=" . $aft_currency . "&amount=" . $amount;
if (!is_int((int)file_get_contents($url))) {
//echo "Failed on convert<br/>";
return false;
} else {
//echo "Conversion done";
return (int)file_get_contents($url);
}
}
function run_conversion($refno = '', $output = false)
{
global $wpdb;
$currencies = array("GBP", "EUR", "TRY", "USD");
$q = "SELECT * FROM Properties ";
$q .= (!empty($refno)) ? " WHERE Refno='" . $refno . "'" : "";
$rows = $wpdb->get_results($wpdb->prepare($q), ARRAY_A);
$currencies = array("USD", "GBP", "TRY", "EUR");
//$wpdb->show_errors();
echo "in Run Conversion " . "<br/>";
foreach ($rows as $row) {
echo "In ROw <br/>";
foreach ($currencies as $currency) {
if ($currency != $row['Currency'] && $row['Price'] != 0) {
$currfield = $currency . "_Price";
$newprice = convert_price($row['Currency'], $currency, $row['Price']);
echo "Old Price Was " . $row['Price'] . " New Price Is " . $newprice . "<br/>";
if ($newprice) {
if ($row[$currfield] != $newprice) {
$newq = "UPDATE Properties SET DateUpdated = '" . date("Y-m-d h:i:s") . "', " .
$currfield . "=" . $newprice . " WHERE Refno='" . $row['Refno'] . "'";
$newr = $wpdb->query($newq);
if ($output) {
echo $newq . " executed <br/>";
} else {
echo "query failed " . $wpdb->print_error();
}
} else {
if ($output) {
echo "No need to update " . $row['Refno'] . " with " . $newprice . "<br/>";
}
}
} else {
echo "Currency conversion failed";
}
}
}
}
}
?>
I then run the process from a seperate file for the sake of chron like so:
require($_SERVER['DOCUMENT_ROOT'] . "/functions.php"); // page containing functions
run_conversion('',true);
If I limit the mysql query to 100 properties it runs fine and I get all the output in a nice stream. But when I try to run it in full the script completes (I can see from rows updated in db) but no output. I have tried upping the memory allowance but no joy. Any ideas gratefully received. Also, I get a 500 error when changing from Apache Module to CGI. Any ideas on that also well received as ideally I would like to turn site onto fastCGI.

You're running out of memory most likely. Probably in your DB layer. Your best bet is to unset your iterative values at the end of each loop:
foreach ( $rows as $row ) {
...
foreach ( $currencies as $currency ) {
...
unset( $currency, $newr, $currfield, $newprice );
}
unset( $row );
}
This will definitely help.

As another answer suggests you may be running out of memory, but if you make an HTTP call everytime the loop is running, and you have 100+ currencies, this may also cause the problem. Try limit it to 5 currencies for example.
If this is indeed the problem I would split the process, so a chunk of currencies have their respective value updated per cron job, instead of everything.

Related

Authorize.Net API limit 1000 results. How to overcome it?

On my website we keep transactions as pending and capture them when we ship (often we need to change amounts/cancel and it makes it easier accounting wise to work like that).
When we are ready to ship, we match all specified orders (with specified order status) with the invoice#/order id in authorize.
the issue is that the authorize.net API only allows for 1000 transaction limit so when using their GetUnsettledTransactionListRequest function it is missing transactions that are unsettled passed that amount.
I am able to set the paging limit to 1000 and I can also set the offset to 1000 (or 999 not sure which yet) so I think what I need to do is something like check if the array storing the results size is 1000 and if so get the next 1000 results to store in the array. But about about the next loop do I have to manually say 3000, 4000, 5000 (we don't have that many transactions but still).
here is my current code:
function getUnsettledTransactionList()
{
//get orders that are in the exp status
$orders_pending_query = tep_db_query("select orders_id as invoice_number from " . TABLE_ORDERS . " where orders_status = '15' order by invoice_number");
$orders_pending = array();
while ($row = mysqli_fetch_array($orders_pending_query, MYSQLI_ASSOC)) {
$orders_pending[] = $row;
}
/* Create a merchantAuthenticationType object with authentication details
retrieved from the constants file */
$merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
$merchantAuthentication->setName(\SampleCodeConstants::MERCHANT_LOGIN_ID);
$merchantAuthentication->setTransactionKey(\SampleCodeConstants::MERCHANT_TRANSACTION_KEY);
// Set the transaction's refId
$refId = 'ref' . time();
$request = new AnetAPI\GetUnsettledTransactionListRequest();
$request->setMerchantAuthentication($merchantAuthentication);
$controller = new AnetController\GetUnsettledTransactionListController($request);
$response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::PRODUCTION);
$transactionArray = array();
$resulttrans = array();
if (($response != null) && ($response->getMessages()->getResultCode() == "Ok")) {
if (null != $response->getTransactions()) {
foreach ($response->getTransactions() as $tx) {
$transactionArray[] = array(
'transaction_id' => $tx->getTransId(),
'invoice_number' => $tx->getInvoiceNumber()
);
// echo "TransactionID: " . $tx->getTransId() . "order ID:" . $tx->getInvoiceNumber() . "Amount:" . $tx->getSettleAmount() . "<br/>";
}
//match the array column by invoice mumber to find all the transaction ids for cards to capture
$invoiceNumbers = array_column($orders_pending, "invoice_number");
$result = array_filter($transactionArray, function ($x) use ($invoiceNumbers) {
return in_array($x["invoice_number"], $invoiceNumbers);
});
$resulttrans = array_column($result, "transaction_id");
print_r($resulttrans);
} else {
echo "No unsettled transactions for the merchant." . "\n";
}
} else {
echo "ERROR : Invalid response\n";
$errorMessages = $response->getMessages()->getMessage();
echo "Response : " . $errorMessages[0]->getCode() . " " . $errorMessages[0]->getText() . "\n";
}
return $resulttrans;
}
GetUnsettledTransactionListRequest offers the ability to page the results. So you after you process the first 1,000 results you can request the next 1,000 results.
I don't use the Authnet SDK but it looks like you can use AnetAPI\PagingType() to handle the paging for you:
$pagenum = 1;
$transactionArray = array();
do {
// ...code truncated...
$request = new AnetAPI\GetUnsettledTransactionListRequest();
$request->setMerchantAuthentication($merchantAuthentication);
// Paging code
$paging = new AnetAPI\PagingType();
$paging->setLimit("1000");
$paging->setOffset($pagenum);
$request->setPaging($paging);
$controller = new AnetController\GetUnsettledTransactionListController($request);
// ...code truncated...
$numResults = (int) $response->getTotalNumInResultSet();
// ...code truncated...
$pagenum++;
} while ($numResults === 1000);
The JSON would resemble this:
{
"getUnsettledTransactionListRequest": {
"merchantAuthentication": {
"name": "",
"transactionKey": ""
},
"paging": {
"limit": "1000",
"offset": "1"
}
}
}

Method's optional parameter, when passed as string, becomes an array

Tl;dr: at the bottom
Setup:
I have a cron job that calls a PHP script to handle some Backend tasks. For simplicity, the cron job redirects all output to a log file. Because this matters to my actual question found below, here's the sanitized format of the cron job:
15 4 * * * php /usr/local/bin/myScript.php >> /home/$USER/scriptLogs/myScript.log 2>&1
I'm new-ish to OOP and I'm being tasked with learning it as I go, and for myScript.php, I'm doing some data imports that require querying the DB to validate the data prior to its import and I'm supposed to log every transaction. We recently moved from 5.6 to 7.2 and part of task at hand is to use 7.2's new features as we refactor.
The refactor itself is to take all of the duplicated code and move it to classes to obey the DRY principle.
Previously, it looked something like this:
<?php namespace CronJobs
use PDO;
use Exception;
class JobAt415 {
private function getDBconnection()
{
// connects to a DB through environment variable set in a config file
return $db;
}
public function query1($parameter1, $parameter2, $inclusionParameter)
{
$sql = "SELECT " . $parameter1 . ", ". $parameter2 . " FROM `foo`.`bar` WHERE " . $inclusionParmeter " IS NOT NULL;";
try
{
$db = $this->getDBconnection();
echo '[' . strftime("%c") . '] Running query 1' . PHP_EOL;
$resultDictionary = $db->query($sql)->fetchall(PDO::FETCH_KEY_PAIR)
return $resultDictionary;
}
catch (Exception $e)
{
echo '[' . strftime("%c") . '] ERRORS ' . PHP_EOL;
echo $e->getMessage();
return null;
}
}
public function query2($parameter1, $parameter3)
{
$sql = "SELECT " . $parameter1 . " FROM `foo`.`bar` WHERE " . $parameter3 " > 0;";
try
{
$db = $this->getDBconnection();
echo '[' . strftime("%c") . '] Running query 1' . PHP_EOL;
$resultDictionary = $db->query($sql)->fetchall()
return $resultArray;
}
catch (Exception $e)
{
echo '[' . strftime("%c") . '] ERRORS ' . PHP_EOL;
echo $e->getMessage();
return null;
}
}
}
Post-Refactor:
<?php namespace CronJobs
use PDO;
use Exception;
Class DbConnectionFactory {
protected $dbConnection;
public function __construct()
{
$this->dbConnection = $this->createConnection();
}
public function runQuery($sql, ...$queryDescriptor)
{
try
{
$descriptor = $queryDescriptor ? (string) $queryDescriptor : $sql;
echo '[' . strftime("%c") . '] Running query ' . "$descriptor" . PHP_EOL;
$resultPending = $this->dbConnection->query($sql);
echo '[' . strftime("%c") . '] Query successful.' . PHP_EOL;
return $resultPending;
}
catch (Exception $e)
{
echo '[' . strftime("%c") . '] ERRORS ' . PHP_EOL;
echo $e->getMessage();
return null;
}
}
public function runQueryFetchDictionary($sql, ...$queryDescriptor)
{
$description = (string) $queryDescriptor;
$fetchAll = $this->runQuery($sql, $description)->fetchall(PDO::FETCH_KEY_PAIR);
return $fetchAll;
}
// In the JobAt415 class
private function runQuery1()
{
$sql = 'SELECT `parameter1`, `parameter2` FROM `foo`.`bar` WHERE `baz` IS NOT NULL;';
$description = 'p1, p2 :: baz != NULL';
$p1Dictionary = $this->db->runQueryFetchDictionary($sql, $descripton); // $this->db is an instantiation of the DbConnectionFactory class
So, now I just pass the SQL query as a parameter and a description of what is being queried to be echoed to the log, and I don't have 19 try/catch blocks in the code or a bunch of duplicated code that I've removed from this example.
Unfortunately, as I'm stepping through the code with XDebug, the optional parameter $queryDescriptor is being converted from a string to an array. I've tried multiple ways of passing it, casting it, and/or defining it and get the same result: $queryDescriptor is an array. At one point, casting it to a string returned the value of "Array".
When I checked the PHP website, I found this:
Note:
The behaviour of an automatic conversion to array is currently undefined.
Emphasis mine.
I don't want any conversion. So, how do I prevent this? Does anyone see what I'm missing? Why doesn't the $sql string get converted to an array but the $queryDescriptor always get converted?
Tl;dr:
Why is my string now an array?
Because by adding a parameter like ...$queryDescriptor you tell PHP that there can be endless parameters. This is because of the ... in front of the variable name. That's why PHP changes the type to an array.
Otherwise how could you handle the number of possibly thousand of parameters?
https://secure.php.net/manual/en/functions.arguments.php#functions.variable-arg-list
//You tell PHP that there can be a variable number of parameters by adding '...' in front of the variable name
function foo(...$bar) {
//You get an array holding all the passed parameters
foreach($bar as $arg) {
//By stepping through it you get all the parameters
echo $arg;
}
}
Or of course you can get the parameters by their indexes.
$bar[0]; //returns the first passed parameter

CSV Data not Writing to Database, SuiteCRM, Custom Import Script

I'm writing a custom import script for SuiteCRM and I'm getting the error:
Warning: array_combine() expects parameter 2 to be array, boolean
given in /var/www/html/afscmedbv5test/custom/wimporter/newimporter.php
on line 162
My Script is as follows:
<?php
if (!defined('sugarEntry') || !sugarEntry) die ('Not a Valid Entry Point!');
$date = new DateTime();
echo '<H2>Wilderness Import Started</h2>';
echo $date->format('r').'<br>';
echo '-----------------------------------------------------------------------
--------------------------------------------------------------<br>';
require_once("include/utils/sugar_file_utils.php");
WildernessImportJob();
die();
function var_dump_ret($mixed = null) {
ob_start();
var_dump($mixed);
$content = ob_get_contents();
ob_end_clean();
return $content;
}
function time_elapsed()
{
static $first = null;
static $previous = null;
$now = microtime(true);
if ($first == null) $first = $now;
if ($previous != null)
echo '--- Partial ' . round(($now - $previous), 2) . ', Total ' . round(($now
- $first), 2) . ' ---'; // 109s
$ret = round(($now - $previous), 2);
$previous = $now;
return $ret;
}
function myLog ($str2log)
{
file_put_contents('./zlog_'.date("j.n.Y").'.txt', date("H:i:s", time())."
".$str2log.PHP_EOL, FILE_APPEND);
}
function calcDelta($a1, $a2)
{
//combine into a nice associative array:
$delta=Array();
foreach ($a1 as $key=>$value)
{
if ($a1[$key] != $a2->$key)
$delta[] = array($key => ("Was ". $a1[$key]. ", became " . $a2->$key));
}
$num = count($data);
if (empty($a1)) $delta[] = array("a1" => ("Was empty"));
if (empty($a2)) $delta[] = array("a2" => ("Was empty"));
return $delta;
}
require_once("include/utils/sugar_file_utils.php");
function fillPerson($record, &$person)
{
// $record is what is being imported from CSV
// $person is the bean about to be filled and going into the SuitCRM DB. It
may be new or not, depending on whether it exists in the DB previously.
// name: only updates if not existant yet, because it's the key we use for
search, and because names are more complex with parts
if ($person->full_name_c == "") {
$recordname = $record["FULL NAME"]; // != "") ? $record["FULL NAME"] : "
[To-be-filled]");
//echo $prefix;
$recordname = str_replace(" ", " ", $recordname);
echo $recordname;
$parts = explode(" ", $recordname);
$person->last_name = array_pop($parts);
$person->first_name = $parts[0];
$person->name = $person->first_name . " " . $person->last_name;
$person->full_name_c = $record["FULL NAME"]; // custom field created in
Studio
}
//$datanasc = DateTime::createFromFormat('!m/d/Y', $record["PPE"]);
// $datasnasc->setTime(0, 0);
// $person->ppe_date_c = ($datanasc == false) ? "" : $datanasc->format('m-d-
Y');
//$person->ppe_date_c = $record["PPE"];
//print_r($person);
var_dump($person);
}
// finish by making a complete analysis of what changed:
return calcDelta($person->fetched_row, $person);
function GetOrCreateMember ($the_name)
{
//Check if the fullname is null
if ($the_name != "")
{
$person = BeanFactory::getBean("locte_Members");
$person = $person->retrieve_by_string_fields(array('full_name_c' =>
$the_name));
if (is_null($person))
{
//get members bean
$person = BeanFactory::newBean("locte_Members");
//set full_name_c to the_name variable
$person->full_name_c = $the_name;
// $person->lcl_employee_id = $personEmployeeID;
$person_name = str_replace(" ", " ", $the_name);
$parts = explode(" ", $person_name);
$person->last_name = array_pop($parts);
$person->first_name = $parts[0];
//combine first and last name to populate the fullname field
$person->name = $person->first_name . " " . $person->last_name;
$person_id = $person->save();
// add new duespayment to member record
// $rosterDuesPayments = BeanFactory::getBean('Dues Payments')-
>retrieve_by_string_fields(array('name'=> $duesEmployeeID));
// $person->load_relationship('locte_Members_adues_dues'); //confirm
relationship name in cache
// $person->dues_payments->add($rosterDuesPayments->id);
}
return $person;
}
return null;
}
function WildernessImportJob()
{
try
{
time_elapsed();
$GLOBALS['log']->info('Wilderness Import');
$config = new Configurator();
$config->loadConfig();
$xmlDataDir = 'custom/wimporter/ToImport'; //$config->config['WildernessImporter_DataFilePath'];
$GLOBALS['log']->info("Wilderness Import: Scanning XML Data dir $xmlDataDir...");
echo("<h3>Wilderness Import: Scanning XML Data dir $xmlDataDir...<br /></h3>");
$directoryContent = scandir($xmlDataDir);
$GLOBALS['log']->info("Wilderness Import: Scanning XML Data dir $xmlDataDir... [Found " . count($directoryContent) . " files]");
echo("<h3>Wilderness Import: Scanning XML Data dir $xmlDataDir... [Found " . count($directoryContent) . " files]</h3><br />");
foreach ($directoryContent as $itemFile)
{
if (is_dir($xmlDataDir . DIRECTORY_SEPARATOR . $itemFile)) continue;
if (strcasecmp(substr($itemFile, -4), ".csv") != 0) continue;
$GLOBALS['log']->info("Wilderness Import: Processing $itemFile file...");
myLog("---------------------------------------------------");
myLog("Wilderness Import: Processing $itemFile file...");
myLog("----------------------------------------------------");
echo("<h4>---------------------------------------------------------------</h4>");
echo("<h4>Wilderness Import: Processing $itemFile file...</h4>");
echo("<h4>---------------------------------------------------------------</h4>");
$oFile = fopen($xmlDataDir . DIRECTORY_SEPARATOR . $itemFile, 'r');
if ($oFile !== FALSE)
{
// read entire file at once:
// expected separator is ",", expected encoding is UTF-8 without BOM (BOM is 3 weird characters in beginning of file)
while (($data[] = fgetcsv($oFile, 0, ',')) !== FALSE) { }
echo('File opened..... <br /> <br />');
fclose($oFile);
//combine into a nice associative array:
$arow=Array();
echo('Building CSV File Row Array <br /><br />');
$fields = array_shift($data);
echo('Building CSV Header Fields Array as shown below:<strong> <br /><br />');
echo implode(", ", $fields) . "</strong><br /><br />\n";
foreach ($data as $i=>$arow)
{
$GLOBALS['log']->info("Wilderness Import: array_combine " . $i);
$data[$i] = array_combine($fields, $arow);
}
unset($arow); // **********************************************! ! ! !! ! ! ! ! ! !! !
$num = count($data);
echo('Build Full Array of Roster to be Imported Complete. Entries to be imported are shown below <br /><br />');
for ($row=0; $row < $num - 1 ; $row++)
{ // normal bounds: from 0 to $num
//$num is the number of lines including header in csv file
echo "<strong>Filename: $itemFile | Roster Import, Row" . ($row + 1) . ":</strong><br />\n";
$GLOBALS['log']->info("Wilderness Import: Importing " . $data[$row]["FULL NAME"]);
// echo("<strong>Importing Roster Row #: ". ($row + 1) . "<br />" . "Local Number " . $data[$row]["AFFILIATE"] . "<br />" . "Employee: " . $data[$row]["FULL NAME"] . "</strong><br /><br />");
echo "<strong><table>\n";
foreach ($fields as $field) {
//echo "<tr><td>" . $field . "</td><td>" . $data[$row][$field] . "</td><td>" . $data[$row+1][$field] . "</td><td>" . $data[$row+2][$field] . "</td></tr>\n";
}
echo "</table>\n";
echo "File Row Data: ";
echo implode(", ", $data[$row]) . "</strong><br /><br />\n";
$Member = BeanFactory::getBean("locte_Members");
$FullName=$Member->full_name_c;
//$myfield_defs = $Member->getFieldDefinitions(); // just to help while developing
//foreach($myfield_defs as $def) echo $def["name"] . "<br />\n";
$Member=$Member->retrieve_by_string_fields(array('full_name_c' => $data[$row]["FULL NAME"]));
if (is_null($Member)) {
$Member = BeanFactory::newBean("locte_Members");
$delta = fillPerson($data[$row], $Member, ""); //->full_name_c, "FULL NAME");
}
if (count($delta)) {
$Member_id = $Member->save();
}
}
// Records have been saved: from this point on, only work on relationships:
$GLOBALS['log']->info('End: Wilderness Import');
myLog('End: Wilderness Import');
time_elapsed();
return true;
}
}
} catch (Exception $e)
{
$GLOBALS['log']->fatal("Wilderness Import: Exception " . $e->getMessage());
myLog("Wilderness Import: Exception " . $e->getMessage());
echo '\n\nCaught exception: ', $e->getMessage(), "\n";
return false;
}
}
It does return info from both the database and the csv file.
Image of error below.
Error - Capture from browser
Help always appreciated :)
This script is throwing error because the parameter $arow given to array_combine is not an array. So a check should be there to check whether $arow is an array or not.
Try code following:
foreach ($data as $i => $arow) {
$GLOBALS['log']->info("Wilderness Import: array_combine " . $i);
if (is_array($arow)) {
$data[$i] = array_combine($fields, $arow);
}
}
Read more about array_combine
Update
Code you are using to read csv need to be changed. Second parameter in fgetcsv must be greater than the longest line (in characters) to be found in the CSV file. So replace code
while (($data[] = fgetcsv($oFile, 0, ', ')) !== FALSE) {
}
with
while (($data[] = fgetcsv($oFile, 10, ', ')) !== FALSE) {
}
Read more about fgetcsv
This block is doing the saving of records using the beanfactory.... I think :|
$Member = BeanFactory::getBean("locte_Members");
$FullName=$Member->full_name_c;
//$myfield_defs = $Member->getFieldDefinitions(); // just to help while developing
//foreach($myfield_defs as $def) echo $def["name"] . "<br />\n";
$Member=$Member->retrieve_by_string_fields(array('full_name_c' => $data[$row]["FULL NAME"]));
if (is_null($Member)) {
$Member = BeanFactory::newBean("locte_Members");
$delta = fillPerson($data[$row], $Member->full_name_c, "FULL NAME");
var_dump($arow);
}
if (count($delta)) {
$Member_id = $Member->save();
}
}
// Records have been saved: from this point on, only work on relationships:
Here's the output of the script in the browser with field definition dump
Wilderness Import Started
Tue, 19 Jun 2018 02:05:56 -0400
Wilderness Import: Scanning XML Data dir custom/wimporter/ToImport...
Wilderness Import: Scanning XML Data dir custom/wimporter/ToImport... [Found 3 files]
Wilderness Import: Processing L1554v4.csv file...
File opened.....
Building CSV File Row Array
Building CSV Header Fields Array as shown below:
LAST NAME, FIRST NAME, FULL NAME
Build Full Array of Roster to be Imported Complete. Entries to be imported are shown below
Filename: L1554v4.csv | Roster Import, Row1:
LAST NAME BUTLER
FIRST NAME BRIANA
FULL NAME BUTLER BRIANA
File Row Data: BUTLER, BRIANA, BUTLER BRIANA
-id
-name
-date_entered
-date_modified
-modified_user_id
-modified_by_name
-created_by
-created_by_name
-description
-deleted
-securitygroup
-securitygroup_display
-created_by_link
-modified_user_link
-assigned_user_id
-assigned_user_name
-assigned_user_link
-additionalusers
-additionalusers_listview
-salutation
-first_name
-last_name
-full_name
-title
-photo
-department
-do_not_call
-phone_home
-email
-phone_mobile
-phone_work
-phone_other
-phone_fax
-email1
-email2
-invalid_email
-email_opt_out
-primary_address_street
-primary_address_street_2
-primary_address_street_3
-primary_address_city
-primary_address_state
-primary_address_postalcode
-primary_address_country
-alt_address_street
-alt_address_street_2
-alt_address_street_3
-alt_address_city
-alt_address_state
-alt_address_postalcode
-alt_address_country
-assistant
-assistant_phone
-email_addresses_primary
-email_addresses
-email_addresses_non_primary
-lcl_birthdate
-lcl_affiliate_number
-member_signature
-ssn
-staff_rep
-mem_join_date
-class_title
-steward
-olo_code
-enterprise_id
-member_card
-address_map
-member_status
-primary_language
-english_speaking
-annual_salary
-currency_id
-state_hire_date
-dues_frequency
-card_sent_date
-gender
-disabilities
-marital_status
-executive_board
-affiliate_type
-middle_name
-name_suffix
-mailableflag
-no_mailflag
-apt_number
-zip4
-infosrc
-lcl_phone_collected
-lcl_hasmobile
-lcl_hasemail
-lcl_member_status
-backofficeassistants
-backoffice_assistant_phonoe
-backoffice_assistant_email
-lcl_employercontact
-lcl_work_dept
-lcl_work_location
-lcl_jobclasstitle
-lcl_employee_id
-lcl_join_date
-lcl_sig_auth
-lcl_dues_status
-lcl_on_probation
-lcl_prob_end_date
-lcl_prob_term
-afs_signed_by
-afs_region_number
-afemp_employers_id_c
-afs_employer
-primary_address_county
-locte_members_adues_dues
-full_name_c
-locte_members_afcbu_cbu
-locte_members_afcbu_cbu_name
-locte_members_afcbu_cbuafcbu_cbu_idb
-ppe_date_c
--- Partial 0.01, Total 0.01 ---

How to get attribute values of an object stored in $_SESSION?

I have this code that store a "student" object in $_SESSION:
if(isset($_POST["name"]) && isset($_POST["note"]) && isset($_POST["year"]))
{
$nom = $_POST["name"];
$note = $_POST["note"];
$session = $_POST["year"];
$vec = array("name" => $name, "note" => $note, "year" => $year);
$_SESSION["students"][] = $vec;
echo "The student has been added.<br><br>";
}
Then I have this code in another page:
function calculateAverage()
{
$av = 0;
$count = 0;
foreach($_SESSION['students'] as $student)
{
$av = $av + $student["note"];
$count = $count + 1;
}
return $av / $count;
}
function bestNote()
{
//$best = array_search(max())
return $best;
}
function worstNote()
{
$worst = min(array_search(["note"], $_SESSION['students']));
return $worst;
}
if(isset($_SESSION['students']))
{
echo "The average note of the group is = " . calculateAverage() . "\n";
echo "The one with the best note is " . bestNote()["name"] . " is " . hauteNote()["note"] . " points.\n";
echo "The one with the worst note is " . worstNote()["name"] . " with " . basseNote()["note"] . " points.\n";
}
As you can see, it is not finished. What I want to do is to be able to get the note of a student that is stored in $_SESSION["students"]. How can I do this?
Thanks for answers.
you can access the stored values within a nested array like so:
$studentNote = $_SESSION["students"][YourActiveStudent]["note"];
However, you are currently not adding but overwriting data. Use array_push() to add data to an array (your students).
And when adding a student to the array, make sure to give it a name to make it associative so you can simply "call a student":
$_SESSION["students"][$nom] = $vec;
this way, if the $nom was "Max", you could say
$_SESSION["students"]["Max"]["note"]
to get Max's note (BTW, I assume you are talking about grades or marks, rather than notes?)

Access to Access Transfer

I have asked a couple of questions on here in a rush, and I am getting nowhere fast, I keep changing things and just ending up with a different problem, and no closer to having a clue what is causing it. I am a PHP MYSQL man, and I am having to work with Access via the COM class.
Basically the client has multiple servers, each with an access database, and each with a CMS, the tables should contain the same data and have slipped out of Sync. It is my job to come up with a way of resyncing them.
I have came to bringing the data out into an Array, serializing it and saving it to a file on the main server (the one all should sync to) and then on the other servers, downloading the file, unserializing it and item by item, checking if it is in the DB, and if not inserting it. The insert is failing. I have tried building an sql query for each item and doing $this->conn->Execute(); and that is failing row by row on silly things, so I am now trying this:
function syncCMS()
{
$this->output['msg'] .= "<p><b>The following properties were added to the database on ." . $this->hsite . "</b></p>";
$this->get_field_names();
$this->make_connection(); //assigns connection to $this->conn
$rs = new COM('ADODB.Recordset');
$rs->CursorType = 2;
$rs->CursorLocation = 1;
$rs->LockType = 4;
$rs->Open($this->table_name,$this->conn);
foreach ($this->awayPropertyDetails as $key => $property)
{
$this->check_for_property($property['pname']);
if (!$this->property_exists || $this->mode == "fullSync")
{
unset($values);
$bfields = array("pshow","rent","best", "oda1", "oda2", "oda3", "oda4", "oda5", "oda6", "odap", "topool","tomountain","tofitness","tosauna"); //stores the yes/no values
$q = "INSERT INTO " . $this->table_name . " (" . $this->dbfields . ") VALUES (";
foreach ($property as $k => $value)
{
if ($k == "Kimlik") {
$value = null;
}
if ($k == "tarih")
{
$value = date("d/m/Y");
$value = "'" . $value . "'";
}
if (in_array($k,$bfields))
{
if ($value == "")
{
$value = 'FALSE';
}
else
{
$value = 'TRUE';
}
}
$rs->fields->$k = $value;
$this->output['msg'] .= $property['pname'] . " added";
}
$rs->BatchUpdate();
$rs->Close();
$this->conn->Close();
//$this->download_images($property['OBJECT_NR'],$k);
//$this->output['msg'] .= "<p>Images added</p>";
}
}
$message .= "</ul>";
$this->output['msg'] .= $message;
$this->sendOutput();
//print_r($property);*/
}
And getting this:
Fatal error: Uncaught exception 'com_exception' with message 'Unable to lookup `Kimlik': Unknown name. ' in D:\inetpub...
Kimlik is the name of the first field, the Auto Number field, I took it out and the problem shifted to the second field.
I got there with:
$sql = "SELECT * FROM " . $this->table_name;
if (!$this->property_exists || $this->mode == "fullSync")
{
$this->make_connection();
$rs->Open($sql,$this->conn);
$rs->addnew();
foreach($rs->Fields as $field)
{
if ($field->name != "Kimlik")
{
$rs->Fields[$field->name] = $property[$field->name];
}
}
$rs->Update();
$rs->Close();
$this->conn->Close();
$msg = $this->download_images($property['OBJECT_NR'],$k);
$this->output['msg'] .= $property['pname'] . " added<br/>" . $msg . "<br/><br/>";
}

Categories