im trying assign values to my variables in ascript by calling a function and variables from another script, but currently im getting errors saying
Undefined property: stdClass::$Boys in
Undefined property: stdClass::$Girls in
im calling a function in a script called report.php from my script
report.php
public function projectReport($ID){
$get_con = $this->getConnection();
$result = mysql_query($query, $get_con);
$rep = new stdClass();
if(false !== $result){
$multis = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$count = new stdClass();
$count->Boys = (int)$row['males'];
$count->Girls = (int)$row['females'];
$multis[] = $count;
}
$rep->multiples = $multis;
}
return $rep;
}
function body of my script
$report = new Report();
$log = $report->projectReport($ID);
if($log != false){
$Boys = $log->Boys;
$Girls = $log->Girls;
print_r($Boys);
print_r($Girls);
}
return $log;
your $log can never be false so you don't need to check that. Alhtough multiples attribute might be missing.
Try this:
$report = new Report();
$log = $report->projectReport($ID);
if(property_exists($log, 'multiples')){ //check if multiples attribute exists
foreach ($log->multiples as $m) //walk through every multiples record
{
$Boys = $m->Boys; //get Boys and Girls attributes values and print them
$Girls = $m->Girls;
print_r($Boys);
print_r($Girls);
}
}
I'm pretty sure that's not what you wanna achieve, but that how it should work based on what you've got so far.
Related
I want to connect multiple databases with PHP.
I have table which has a connection parameters, i want to show you codes first.
class someClass {
protected $db, $arrayb;
public function __construct() {
include 'db.php';
$this->db = $db;
$this->arrayb = $arrayb;
}
public function prepareSites() {
$prepareSites = $this->db->prepare("SELECT id FROM sites WHERE site_type='somesites' ORDER BY id ASC");
$prepareSites->execute();
$getCountOpSites = $countOpSites->rowCount();
$prepareSites = $prepareSites->fetchAll(PDO::FETCH_ASSOC);
$arraycount = array();
foreach ($prepareSites as $a) {
$arraycount[] = $a;
}
$arrayb = array();
foreach ($arraycount as $b) {
$arrayb[] = $b["id"];
}
$arrayb;
}
Everything is fine in these codes. $arrayb variable gives me every id, i have no problem with arrays.
But,
public function connectSites() {
$dbarray = array();
$i = 0;
foreach ($this->arrayb as $a) {
$i++;
$conn.$i = $this->db->prepare("SELECT * FROM sites WHERE id='{$a}'");
$conn.$i->execute();
$conn.$i = $conn.$i->fetch(PDO::FETCH_ASSOC);
$asd.$i = $conn.$i["id"];
$host2 = $conn.$i["site_host"];
$name2 = $conn.$i["site_name"];
$user2 = $conn.$i["site_user"];
$pass2 = $conn.$i["site_pass"];
$this->dbop.$i = new PDO('mysql:host='.$host2.';dbname='.$name2.'', ''.$user2.'', ''.$pass2.'');
$this->dbop.$i->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->dbop.$i->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbarray[] = $this->dbop.$i;
}
return $dbarray;
}
Number of added connection won't be known. That's why i wanted to add $i variable to make different connections as many as i want. But $dbarray variable gives me nothing. And i don't know how to control it if it gives me anything.
Thank You.
I'm using Laravel to parse an XML file and store it into the DB. Now, it's probably some sort of a stupid mistake I can't put my finger on, but I would really appreciate if someone could check the code and the weird results I'm getting.
The XML has a deep and complex structure, here's a little piece from that's bugging me:
I'm dumping the $nizXMLsp in the end to see what's inside the array of objects:
public function upload(){
$dom = new DomDocument();
$nizBaza = DB::table('offers')->orderBy('id', 'DESC')->first();
$nizXML = array();
$objekat = new stdClass();
$dom->load("storage/X_Lista.xml");
$domXpath = new DomXPath($dom);
$upit = $domXpath->query('//offer');
foreach($upit as $of){
$objekat->Time = $of->getAttribute('Time');
$objekat->Date = $of->getAttribute('Date');
$objekat->betRound = $of->getAttribute('betRound');
$objekat->timestamp = $of->getAttribute('timestamp');
array_push($nizXML, $objekat);
}
if(is_null($nizBaza) or $nizBaza->id != $nizXML[0]->betRound) {
$kolo = new Offer();
$kolo->id = $objekat->betRound;
$kolo->ts = $objekat->Date . " " . $objekat->Time;
$kolo->posix = $objekat->timestamp;
$kolo->save();
//
$nizBaza = DB::table('sportovi')->get();
$nizXMLsp = array(); $objekat_sp = new stdClass();
foreach($dom->getElementsByTagName('sport') as $k=>$v){
$objekat_sp->id = $v->getAttribute('id');
$objekat_sp->name = $v->getAttribute('name');
$objekat_sp->betRound = $v->parentNode->getAttribute('betRound');
$nizXMLsp[$k] = $objekat_sp;
}
}
elseif($nizBaza->id == $nizXML[0]->betRound){
echo 'break1';
exit;
}
else {
echo 'break2';
exit;
}
return var_dump($nizXMLsp);
}
Now, what I see in the end is this:
instead of 4 objects with different sets of data, I get 4 objects with same set of data (all of the data comes from the last node). What could it be?
Possibly a very simple adjustment. Just reset $objekat_sp inside the loop:
foreach($dom->getElementsByTagName('sport') as $k=>$v){
$objekat_sp = "";
$objekat_sp->id = $v->getAttribute('id');
$objekat_sp->name = $v->getAttribute('name');
$objekat_sp->betRound = $v->parentNode->getAttribute('betRound');
$nizXMLsp[$k] = $objekat_sp;
}
Move
$objekat = new stdClass();
and
$objekat_sp = new stdClass();
inside their respective foreach loops.
Right now you're pushing the same object (after modifying its properties) into the array multiple times.
I'm working on a project in which I pull various statistics about the NHL and inserting them into an SQL table. Presently, I'm working on the scraping phase, and have found an XML parser that I've implemented, but I cannot for the life of me figure out how to pull information from it. The table can be found here -> http://www.tsn.ca/datafiles/XML/NHL/standings.xml.
The parser supposedly generates a multi-dimmensional array, and I'm simply trying to pull all the stats from the "info-teams" section, but I have no idea how to pull that information from the array. How would I go about pulling the number of wins Montreal has? (Solely as an example for the rest of the stats)
This is what the page currently looks like -> http://mattegener.me/school/standings.php
here's the code:
<?php
$strYourXML = "http://www.tsn.ca/datafiles/XML/NHL/standings.xml";
$fh = fopen($strYourXML, 'r');
$dummy = fgets($fh);
$contents = '';
while ($line = fgets($fh)) $contents.=$line;
fclose($fh);
$objXML = new xml2Array();
$arrOutput = $objXML->parse($contents);
print_r($arrOutput[0]); //This print outs the array.
class xml2Array {
var $arrOutput = array();
var $resParser;
var $strXmlData;
function parse($strInputXML) {
$this->resParser = xml_parser_create ();
xml_set_object($this->resParser,$this);
xml_set_element_handler($this->resParser, "tagOpen", "tagClosed");
xml_set_character_data_handler($this->resParser, "tagData");
$this->strXmlData = xml_parse($this->resParser,$strInputXML );
if(!$this->strXmlData) {
die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($this->resParser)),
xml_get_current_line_number($this->resParser)));
}
xml_parser_free($this->resParser);
return $this->arrOutput;
}
function tagOpen($parser, $name, $attrs) {
$tag=array("name"=>$name,"attrs"=>$attrs);
array_push($this->arrOutput,$tag);
}
function tagData($parser, $tagData) {
if(trim($tagData)) {
if(isset($this->arrOutput[count($this->arrOutput)-1]['tagData'])) {
$this->arrOutput[count($this->arrOutput)-1]['tagData'] .= $tagData;
}
else {
$this->arrOutput[count($this->arrOutput)-1]['tagData'] = $tagData;
}
}
}
function tagClosed($parser, $name) {
$this->arrOutput[count($this->arrOutput)-2]['children'][] = $this->arrOutput[count($this- >arrOutput)-1];
array_pop($this->arrOutput);
}
}
?>
add this search function to your class and play with this code
$objXML = new xml2Array();
$arrOutput = $objXML->parse($contents);
// first param is always 0
// second is 'children' unless you need info like last updated date
// third is which statistics category you want for example
// 6 => the array you want that has wins and losses
print_r($arrOutput[0]['children'][6]);
//using the search function if key NAME is Montreal in the whole array
//result will be montreals array
$search_result = $objXML->search($arrOutput, 'NAME', 'Montreal');
//first param is always 0
//second is key name
echo $search_result[0]['WINS'];
function search($array, $key, $value)
{
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && $array[$key] == $value)
$results[] = $array;
foreach ($array as $subarray)
$results = array_merge($results, $this->search($subarray, $key, $value));
}
return $results;
}
Beware
this search function is case sensitive it needs modifications like match to
a percentage the key or value changing capital M in montreal to lowercase will be empty
Here is the code I sent you working in action. Pulling the data from the same link you are using also
http://sjsharktank.com/standings.php
I have actually used the same exact XML file for my own school project. I used DOM Document. The foreach loop would get the value of each attribute of team-standing and store the values. The code will clear the contents of the table standings and then re-insert the data. I guess you could do an update statement, but this assumes you never did any data entry into the table.
try {
$db = new PDO('sqlite:../../SharksDB/SharksDB');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
echo "Error: Could not connect to database. Please try again later.";
exit;
}
$query = "DELETE FROM standings";
$result = $db->query($query);
$xmlDoc = new DOMDocument();
$xmlDoc->load('http://www.tsn.ca/datafiles/XML/NHL/standings.xml');
$searchNode = $xmlDoc->getElementsByTagName( "team-standing" );
foreach ($searchNode as $searchNode) {
$teamID = $searchNode->getAttribute('id');
$name = $searchNode->getAttribute('name');
$wins = $searchNode->getAttribute('wins');
$losses = $searchNode->getAttribute('losses');
$ot = $searchNode->getAttribute('overtime');
$points = $searchNode->getAttribute('points');
$goalsFor = $searchNode->getAttribute('goalsFor');
$goalsAgainst = $searchNode->getAttribute('goalsAgainst');
$confID = $searchNode->getAttribute('conf-id');
$divID = $searchNode->getAttribute('division-id');
$query = "INSERT INTO standings ('teamid','confid','divid','name','wins','losses','otl','pts','gf','ga')
VALUES ('$teamID','$confID','$divID','$name','$wins','$losses','$ot','$points','$goalsFor','$goalsAgainst')";
$result= $db->query($query);
}
Hey guys I have a little issue with a function that retrieves data from a MySQL Database and then I iterate over the results with a foreach loop, checking a value to see if it is null and if it is, replacing it with another value.
The problem with this function is this, that after returning the data I'm only able to view one record retrieved from the database. Probably something simple but it's beyond me.
I would like to do this before passing it to the controller or view. Maybe this isn't possible with the foreach loop? What am I missing?
Here is an example of my code.
public function get_basic_user_data(){
$sql = 'SELECT Account.First_Name, Account.Last_Name, Account.User_Name, Profile_Photos.Thumb_Url
FROM Account
LEFT JOIN Profile_Photos ON Account.idAccount = Profile_Photos.Account_Id
AND Profile_Photos.Active = 1
WHERE Account.idAccount != ?';
$account_id = $this->get_account_id();
$data = $this->db->query($sql, $account_id);
foreach($data->result() as $row){
if($row->Thumb_Url == NULL){
$image = base_url().'assets/images/no_photo_thumb.png';
}else{
$image = $row->Thumb_Url;
}
$new_data = new stdClass;
$new_data->First_Name = $row->First_Name;
$new_data->Last_Name = $row->Last_Name;
$new_data->User_Name = $row->User_Name;
$new_data->Thumb_Url = $image;
}
return $new_data;
}
Hopefully someone can help me with this? Thanks!
At the moment you are just returning the last data row. Change your code like this to return an array of all your rows from that function:
$rows = array()
foreach($data->result() as $row){
if($row->Thumb_Url == NULL){
$image = base_url().'assets/images/no_photo_thumb.png';
}else{
$image = $row->Thumb_Url;
}
$new_data = new stdClass;
$new_data->First_Name = $row->First_Name;
$new_data->Last_Name = $row->Last_Name;
$new_data->User_Name = $row->User_Name;
$new_data->Thumb_Url = $image;
$rows[] = $new_data;
}
return $rows;
This way every row returned from the database will be added to an array named $rows. At the end you have to return your new array.
You are overwriting $new_data each iteration. Try this
$new_data = new stdClass
...
$all_data[] = $new_data;
Instead of checking for null value in the code, you could just use a IFNULL statement in the SQL query, this does separate the logic a bit but it might just be worth it in this case.
The function returns only the last row in the result because the new_data variable is overwritten in every step of your loop. Declare new_data an array at the start of your function and add rows as array elements
...
$new_data[] = new stdClass;
...
Each iteration of the foreach overwrites $new_data so in the end when the function returns, only the last fetched row will be returned. To return more than one row you could store all the rows in an array and then return the array in the end. It would look something like this:
public function get_basic_user_data(){
$sql = 'SELECT Account.First_Name, Account.Last_Name, Account.User_Name, Profile_Photos.Thumb_Url
FROM Account
LEFT JOIN Profile_Photos ON Account.idAccount = Profile_Photos.Account_Id
AND Profile_Photos.Active = 1
WHERE Account.idAccount != ?';
$account_id = $this->get_account_id();
$data = $this->db->query($sql, $account_id);
$data = array();
foreach($data->result() as $row){
if($row->Thumb_Url == NULL){
$image = base_url().'assets/images/no_photo_thumb.png';
}else{
$image = $row->Thumb_Url;
}
$new_data = new stdClass;
$new_data->First_Name = $row->First_Name;
$new_data->Last_Name = $row->Last_Name;
$new_data->User_Name = $row->User_Name;
$new_data->Thumb_Url = $image;
$data[] = $new_data;
}
return $data;
}
To be able to use this function you have to change the code that uses it to loop through the array of objects.
I've got a, I think fairly easy question, but this is bugging me for a while now. So I figured, maybe I can get some help here.
Since recursive functions are always a bit tricky, and sometimes a bit unclear to me, I keep struggling to create a nice working solution to get my menudata.
In one of my classes I have this function, which gives me all menu-items recursively.
The thing I want is to determine at which recursion level a certain object was retrieved so I can create a nicely looking HTML output with indents for the levels of nesting.
public function GetObjectList($parentID = 0, $objectlist = null)
{
if(is_null($objectlist))
{
$objectlist = new ObjectList("Model_Navigation");
}
$query = MySQL::Query("SELECT * FROM `Navigation` WHERE `WebsiteID` = ".SITE_ID. " AND `LanguageID` = ".LANG_ID." AND `ParentID` = ".$parentID);
while($result = MySQL::FetchAssoc($query))
{
$object = new Model_Navigation();
$object->ID = $result["ID"];
$object->WebsiteID = $result["WebsiteID"];
$object->LanguageID = $result["LanguageID"];
$object->ParentID = $result["ParentID"];
$object->Name = $result["Name"];
$object->Page = Model_Page::GetObjectByID($result["PageID"]);
$object->ExternalURL = $result["ExternalURL"];
$object->Index = $result["Index"];
$object->Level = [here lies my problem];
$objectlist->Add($object);
self::GetObjectList($object->ID, $objectlist);
}
return $objectlist;
}
public function GetObjectList($parentID = 0, $objectlist = null, $level = 1)
{
if(is_null($objectlist))
{
$objectlist = new ObjectList("Model_Navigation");
}
$query = MySQL::Query("SELECT * FROM `Navigation` WHERE `WebsiteID` = ".SITE_ID. " AND `LanguageID` = ".LANG_ID." AND `ParentID` = ".$parentID);
while($result = MySQL::FetchAssoc($query))
{
$object = new Model_Navigation();
$object->ID = $result["ID"];
$object->WebsiteID = $result["WebsiteID"];
$object->LanguageID = $result["LanguageID"];
$object->ParentID = $result["ParentID"];
$object->Name = $result["Name"];
$object->Page = Model_Page::GetObjectByID($result["PageID"]);
$object->ExternalURL = $result["ExternalURL"];
$object->Index = $result["Index"];
$object->Level = $level;
$objectlist->Add($object);
self::GetObjectList($object->ID, $objectlist, $level+1);
}
return $objectlist;
}
Why don't you just add a parameter to the function call that stores the number of calls. At the first call just make that 0, increment the value inside the function and use it in the recursive call.