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

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?)

Related

Why is do while loop creating/overwriting 2 separate arrays

I have the following code that is overwriting my array on the second pass through of the while loop.
Here is my code:
<?php
require '../vendor/autoload.php';
require_once 'constants/constants.php';
use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;
require('includes/application_top.php');
define("AUTHORIZENET_LOG_FILE", "phplog");
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 = '14' 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();
$pagenum = 1;
do {
$request = new AnetAPI\GetUnsettledTransactionListRequest();
$request->setMerchantAuthentication($merchantAuthentication);
$paging = new AnetAPI\PagingType;
$paging->setLimit("1000");
$paging->setOffset($pagenum);
$request->setPaging($paging);
$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/>";
}
$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");
} 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";
}
$numResults = (int) $response->getTotalNumInResultSet();
$pagenum++;
print_r($resulttrans);
} while ($numResults === 1000);
return $resulttrans;
}
getUnsettledTransactionList();
?>
the print_r($resulttrans); is actually printing 2 separate arrays, instead of my desired 1 array.
If I move the print_r($resulttrans) to after the while loop, I am only seeing the second array, meaning the first array was overwritten. I am not seeing where this is happening though as to me it seems like all results should be added onto the array.
Your code is supposed to work as you described because you are reassigning the array variable in your loop like this
$resulttrans = array_column($result, "transaction_id");
If you need to get all the resulting values in the same array you need to append it to the array. you can do that by merging the new result into your array variable like this
$resulttrans = array_merge($resulttrans, array_column($result, "transaction_id"));

Getting full list of contacts from Hubspot API

Hubspot's API allows you retrieve a list of contacts, however it only allows a max of 100 per call.
I do that with this call:
$contacts_batch1 = $contacts->get_all_contacts(array( 'count' => '100'));
And then if I want to get the next 100 I do this:
$offset1 = $contacts_batch1->{'vid-offset'};
$contacts_batch2 = $contacts->get_all_contacts(array('count' => '100', 'vidOffset'=>$offset1));
I am trying to get all the contacts without having to create a new variable each time I want the next 100. My first question would be how would I go about getting the vid-offset of the last set, and then how would I put that as a parameter into the next variable automatically.
Here's an example of getting all contacts into one array using HubSpot's API.
<?php
require "haPiHP/class.contacts.php";
require "haPiHP/class.exception.php";
define("HUBSPOT_API_KEY", "<YOUR API KEY HERE>");
$contacts = new HubSpot_Contacts(HUBSPOT_API_KEY);
$all_contacts = array();
do
{
$params = array("count" => 100);
if (isset($vidOffset))
{
$params["vidOffset"] = $vidOffset;
}
echo "count=" . $params["count"] . (isset($params["vidOffset"]) ? ", vidOffset=" . $params["vidOffset"] : "") . "\n";
$some_contacts = $contacts->get_all_contacts($params);
if ($some_contacts !== NULL)
{
$all_contacts = array_merge($all_contacts, $some_contacts->contacts);
}
else
{
break;
}
$vidOffset = $some_contacts->{'vid-offset'};
} while ($some_contacts->{'has-more'});
echo "Received " . count($all_contacts) . " contacts.\n";
?>

printing an variable of an object that's inside an array that's inside an object

Well, ive been trying to get my crm to print multiple contacts for each company but i cant get it to work
Company is a class,companycontactis a class
//class called company
function __construct($idklanten,$naam,$adres,$postcode,$stad,$contacten){
$this->idklanten=$idklanten;
$this->naam=$naam;
$this->adres=$adres;
$this->postcode=$postcode;
$this->stad=$stad;
$this->contacten=$contacten;
}
//class called contact
function __construct($idcontactklanten,$voornaam,$tussenvoegsel,$achternaam,$tel,$email,$klantID){
$this->idcontactklanten=$idcontactklanten;
$this->voornaam=$voornaam;
$this->tussenvoegsel=$tussenvoegsel;
$this->achternaam=$achternaam;
$this->tel=$tel;
$this->email=$email;
$this->klantID=$klantID;
}
//getname for a contact
function getNaam() {
if(strlen($this->gettussenvoegsel()) == 0) {
return $this->getvoornaam()." ".$this->getachternaam()."";
}
else {
return $this->getvoornaam() . " " . $this->gettussenvoegsel() . " " . $this->getachternaam();
}
}
//function for getting the names from my object company,array with objects of contacts
function getcontacten(){
$ct=$this->contacten[$teller];
$txt="";
for($teller=0;$teller<10;$teller++){
$txt+=$ct->getNaam()."<br>";
}
return $txt;
}
then on my index page when i call getcontacten() it does not work comparing to my other get function which do work. it just outputs a 0
Any help is appreciated
Your biggest error would be the following:
$txt+=$ct->getNaam()."<br>";
Should be
$txt.=$ct->getNaam()."<br>";
Because to append to a string you use ".=", not "+=".
Also I don't know if the other part of you code works, I would write something like the following:
$txt = "";
foreach ($this->contacten as $ct){
$txt .= $ct->getNaam() . "<br />";
}
return $txt;
or
$txt = "";
for ($i = 0; $i < count($this->contacten); $i++){
$txt .= $this->contacten[$i]->getNaam() . "<br />";
}
return $txt;

php array not saved in object

I do not understand fully why this PHP code is not saving the data in the arrays. when I echo out the array during the while loop, the values are set but after I exit the loop, the values in the array are missing. The other variables did contain their values after leaving the array.
<?php
class VIEWARRAY {
public $year;
public $month;
public $day = array();
public $views = array();
}
$viewdatabase = array();
$connection = MySQL_Connection($host, Session_Get("username"), Session_Get("password"), $database);
$dayviewindex = 0; $monthyearindex = 0; $previousmonth = "";
$information = MySQL_Script($connection, "SELECT * FROM viewdatabase");
while ($index = mysqli_fetch_array($information)) {
if ($index["month"] != $previousmonth) {
$viewdatabase[$monthyearindex] = new VIEWARRAY;
$viewdatabase[$monthyearindex]->year = $index["year"];
$viewdatabase[$monthyearindex]->month = $index["month"];
$dayviewindex = 0;
$monthyearindex++;
$previousmonth = $index["month"];
}
$viewdatabase[$monthyearindex]->day[$dayviewindex] = $index["day"];
$viewdatabase[$monthyearindex]->views[$dayviewindex] = $index["views"];
$dayviewindex++;
}
MySQL_Disconnect($connection);
//testing area
echo "->" . $viewdatabase[0]->year . " + " . $viewdatabase[0]->month . "<br />"; //prints out ->2013 + 8
echo "------>" . $viewdatabase[0]->day[2] . " + " . $viewdatabase[0]->views[2] . "<br />"; //prints out ------> +
echo count($viewdatabase[0]->views) . "<br />"; //prints out 0
echo count($viewdatabase[1]->views) . "<br />"; //prints out 0
?>
I made sure that I was able to connect to my database just fine and that my database did return information. This is how my database is setup
year month day views
2013 8 25 1
2013 8 26 1
2013 8 27 1
2013 9 3 1
At first run, after if ($index["month"] != $previousmonth), $monthyearindex will be 1.
That means you'll next try to access $viewdatabase[1] but it's NULL.
On the next iteration you won't enter the if, $monthyearindex will be 1, and $viewdatabase[1] will still be NULL.
So you never actually get to set anything in day and views.
Use
if ($index["month"] !== $previousmonth) {
instead of
if ($index["month"] != $previousmonth) {
, because
0 == ''
, but
0 !== ''
. Because,
$index['month'] != ''
is
false
, your if statement fails.

php script executes but no output

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.

Categories