Class not found in php script - php

I have a path in my Laravel project (app/data/report) with 2 files: refresh_numbers.php''' and '''numbers_temp.php
I'm trying to run refresh numbers as a way to run one function within numbers_temp like so:
refresh_numbers.php
<?php
require 'Numbers_temp.php';
echo "Beginning \n\n";
Numbers_temp::refresh();
echo "\n Finished \n";
?>
Numbers_temp.php
<?php
namespace app/data/report;
class Numbers_temp
{
function refresh()
{
$sql = "select C,S,P,Q FROM data";
$result_set = DB::runQuery_simple($sql);
$log = "";
foreach ($result_set as $row) {
$log .= "EXECUTING: $sql -- ";
$res = $this->add_quota($row['S'], $row['P'], $row['Q'], $row['C']);
$log .= "$res \n";
}
return $log;
}
}
But when I run refresh_numbers.php I get an error on line 6 that Class Numbers_temp can't be found?

It just doesn't know about the namespace. Add a use statement:
use app\data\report\Numbers_temp;

Related

Call a PHP file from another one multiple times (+ file reading)

What I am trying to do is read a value from blankVoteOB.txt, delete the value and repeat this process multiple times.
blankVote.php
global $cur_random;
for ($i=0; $i<2; $i++){
include 'readWriteRandomBV.php';
$random[$i]=$cur_random;
echo $random[$i];
echo ',';
}
readWriteRandomBV.php (reads current line from file blankVoteOB.txt and then deletes the line)
<?php
$dir = "blankVoteOB.txt";
$file = fopen($dir, "r") or exit("Unable to open file!");
global $lines;
global $line_no;
global $all_lines;
global $writelines;
global $cur_random;
$lines = "";
$line_no=0;
while(!feof($file)) {
$line_no++;
$line = fgets($file);
$all_lines .= $line."<br>";
if($line_no > 1)
$writelines .= $line;
else{
$curran = trim($line);
$cur_random = $curran;
}
}
fclose($file);
$fh = fopen($dir, 'w') or die("ERROR! Cannot open $file file!");
fwrite($fh, $writelines);
fclose($fh);
?>
Before running the PHPs, blankVoteOB.txt looks like this:
313328804459
159078851698
226414688415
380287830671
301815692106
2991355110
After being ran, it becomes:
159078851698
226414688415
380287830671
301815692106
2991355110
226414688415
380287830671
301815692106
2991355110
What I want is:
226414688415
380287830671
301815692106
2991355110
What am I doing wrong here?
I suggest you use an array to store the ballots, and then use array_shift to get the first item from the array.
I prefer using classes so I made a lottery class which allows you to "draw" the first item in the array.
If you run the code below and match the text output to the code you can see what it does.
See it live here: https://ideone.com/T8stdB
<?php
namespace Lottery;
class Lotto {
protected $lots;
public function __construct($lots = [])
{
$this->lots = $lots;
}
public function draw() {
return array_shift($this->lots);
}
}
namespace BallotGuy;
use Lottery\Lotto;
$lotto = new Lotto([313328804459,
159078851698,
226414688415,
380287830671,
301815692106,
2991355110,
]);
echo "Lotto status at this point\n";
echo "===========================================================\n";
var_dump($lotto);
echo "===========================================================\n";
echo "Drawn: " . $lotto->draw()."\n";
echo "\nLotto status at this point\n";
echo "===========================================================\n";
var_dump($lotto);
echo "===========================================================\n";
$saved = serialize($lotto);
//file_put_contents('ballots.txt',$saved);
/**
* setting to null to emulate script ending
*/
$lotto = null;
echo "Lotto set to null 'script' ends sort to speak here\n";
echo "\nLotto status at this point\n";
echo "===========================================================\n";
var_dump($lotto);
echo "===========================================================\n";
echo "Loading lotto from file\n";
//$saved = file_get_contents('ballots.txt');
$lotto = unserialize($saved);
echo "\nLotto status at this point\n";
echo "===========================================================\n";
var_dump($lotto);
echo "===========================================================\n";
echo "Drawn: ". $lotto->draw()."\n";
echo "\nLotto status at this point\n";
echo "===========================================================\n";
var_dump($lotto);
echo "===========================================================\n";
A version without the superfluos var_dumping
See it live https://ideone.com/YNKIM4
<?php
namespace Lottery;
class Lotto {
protected $lots;
public function __construct($lots = [])
{
$this->lots = $lots;
}
public function draw() {
return array_shift($this->lots);
}
}
namespace BallotGuy;
use Lottery\Lotto;
/**
* initialize lotto object
*/
$lotto = new Lotto([313328804459,
159078851698,
226414688415,
380287830671,
301815692106,
2991355110,
]);
echo "Drawn: " . $lotto->draw()."\n";
echo "Writing lotto to file. Ending script(j/k)\n";
$saved = serialize($lotto);
file_put_contents('ballots.txt',$saved);
/**
* setting to null to emulate script ending
*/
$lotto = null;
$saved = null;
echo "Loading lotto from file\n";
$saved = file_get_contents('ballots.txt');
$lotto = unserialize($saved);
echo "Drawn: ". $lotto->draw()."\n";
var_dump($lotto);

php mysql returns only 1 row if using class

I have this code:
class SampleClass extends MainClass {
private $totalOrder;
//construct goes here
function get_total_number_of_order($buyerIndex) {
$totalSum = //sql to get sum of orders
return $totalSum;
}
function fetch_buyer() {
$qryBuyerInfo = //sql to get buyer info;
while($rs = $qryBuyerInfo->fetch()) {
$this->totalOrder = $this->get_total_number_of_order($rs['buyer_index']);
echo $buyerInfo .'<br>';
echo $this->totalOrder .'<br>';
}
}
I'm wondering why I only get 1 record wherein fact my table has at least 20 records. But if I comment out $this->totalOrder = $this->get_total_number_of_order($rs['buyer_index']);I will be able to generate all 20 records. Another thing I tried is to put get_total_number_of_order to other class an every loop, I initiate new class to use get_total_number_of_order function.
Anybody can have any better idea?
I think I found the issue in your code.
while($rs = $qryBuyerInfo->fetch()) {
$this->totalOrder = $this->get_total_number_of_order($rs['buyer_index']);
echo $buyerInfo .'<br>';
echo $this->totalOrder .'<br>';
}
with above code, you are only getting 1 record as you are re-writing the data into same object. You need to add this loop data into an array. Something like below:
$i=0;
while($rs = $qryBuyerInfo->fetch()) {
$this->totalOrder[$i] = $this->get_total_number_of_order($rs['buyer_index']);
echo $buyerInfo .'<br>';
echo $this->totalOrder[$i] .'<br>';
$i++;
}

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;

display multiple items with different statuses

I don’t know how to search the net for the answer and I’m not sure how to explain the problem, so I’m sorry if it’s not clear or if it’s been asked before.
Here’s the deal: I need to show some items which have different statuses (there’s “unanswered”, “in discussion” and “answered”). What’s happening now is that the unanswered questions are being shown, the correct text is being shown for the questions that are in discussion, but the text for the question that are answered is the same as the “in discussion”. When one of the questions is moved from “unanswered” to “in discussion”, the correct text is being show for the “answered” questions. When there are no “unanswered” questions, the text is correct for that item. But the other items are getting the same text as the “unanswered” and the questions that should be shown in “in discussion” aren’t visible.
Does someone know what I can do to fix this? I'll put some code below. Thanks!!!
overzicht.php
<?php
session_start();
if(!isset($_SESSION['views']))
{
header('Location: index.php');
}
else
{
$feedback = "";
try
{
include_once('classes/question.class.php');
$oQuestion = new Question();
$oQuestionsUnanswered = $oQuestion->getQuestionsUnanswered();
$oQuestionsInDiscussion = $oQuestion->getQuestionsInDiscussion();
$oQuestionsAnswered = $oQuestion->getQuestionsAnswered();
}
catch(Exception $e)
{
$feedback = $e->getMessage();
}
}
?>
To show the different items (this is repeated twice for the other 2 statuses, with other variables e.g $oQuestionsAnswered):
<h3>Vragen onbeantwoord:</h3>
<div id="questionUnanswered">
<?php
if(isset($oQuestionsUnanswered))
{
$unanswered_details = "";
while($arr_unanswered = mysqli_fetch_array($oQuestionsUnanswered))
{
$unanswered_details .= "<div class='head'>";
$unanswered_details .= "<div class='titel'>";
$unanswered_details .= "<a href='full_topic.php?id=".$arr_unanswered['bericht_id']."'>".$arr_unanswered['bericht_titel']."</a></div>";
$unanswered_details .= "<div class='datum'>" . $arr_unanswered['bericht_datum'] . "</div></div>";
}
echo $unanswered_details;
}
else
{
echo $feedback;
}
?>
</div>
question.class.php (this is also repeated for the other 2)
public function getQuestionsUnanswered()
{
include('connection.class.php');
$sql = "SELECT *
FROM tblbericht
WHERE fk_status_id = 3;";
$result = $conn->query($sql);
if($result->num_rows!=0)
{
return $result;
}
else
{
throw new Exception("Er zijn momenteel nog geen onbeantwoorde vragen");
}
mysqli_close($conn);
}
IMO you make a big mistake, you split the query moment from the fetch moment, so you can create an array of question objects, than you use it inside the page.
Here's a draft of your code adapted:
public function getQuestionsUnanswered()
{
include('connection.class.php');
$sql = "SELECT *
FROM tblbericht
WHERE fk_status_id = 3;";
$result = $conn->query($sql);
$_rv =array()
if($result->num_rows!=0)
{
while($arr = mysqli_fetch_array($result))
{
$_rv[] = new QuestionBean($arr);
}
}
else
{
throw new Exception("Er zijn momenteel nog geen onbeantwoorde vragen");
}
mysqli_close($conn);
return $_rv
}
Then
<h3>Vragen onbeantwoord:</h3>
<div id="questionUnanswered">
<?php
if(count($oQuestionsUnanswered))
{
$unanswered_details = "";
foreach( $oQuestionsUnanswered as $bean)
{
$unanswered_details .= "<div class='head'>";
$unanswered_details .= "<div class='titel'>";
$unanswered_details .= "<a href='full_topic.php?id=".$bean->bericht_id."'>".$bean->bericht_titel."</a></div>";
$unanswered_details .= "<div class='datum'>" . $bean->bericht_datum . "</div></div>";
}
echo $unanswered_details;
}
else
{
echo $feedback;
}
?>
</div>
Of course you can optimize it using 1 class for all kind of question and 1 function using the paramiter to select wich kind of question you need.
The type of question will be a parameter of QuestionBean.
QuestionBean is a Bean :)
As bean I mean a "simple" data object where each attributes has a getter and setter OR is public.
I use the __constructor as initializer with a function called populate:
class simpleBean{
public $id;
public function __construct($params){
// some logic as need
}
// simple populate
public function populate($params){
$valid = get_class_vars ( self );
foreach($params as $k => $v){
if(!isset($valid[$k]){
// if this key has no attrib matchig I skip it
continue;
}
$this->$k = $v;
}
}
}
class QuestionBean extend simpleBean{
public $attr1;
public function __construct($params){
// may be I've some common logic in parent
parent::__construc($params);
//
$this->populate($params);
}
}
Now after the
while($arr = mysqli_fetch_array($result))
{
$_rv[] = new QuestionBean($arr);
}
you will have an array ($rv) of beans, each bean is a single result row of your query, but it's an object, that's much better than a stupid array.

Accessing a variable in the function declared in model from the controller in Zend framework

I am quite new to OOPS and Zend. I am converting a part of web app code to Zend framework, I can't post all the code in here coz its quite lengthy. I created a model as in the code below(I can post only two functions) and I want to access the variables inside the functions from the controller and then print them out in HTML tables(I guess I will have to use "views" for that", below is my model:
public function getVenueTypes()
{
$poiTypes = array();
if($this->_cache)
{
$key = $this->getCacheKey()."poiTypes_stats:{$this->language}";
}
if(!$poiTypes)
{
$sql = "SELECT poi_type_id, poi_type_name_".$this->language."
AS
poi_type_name
FROM
poi_types
ORDER BY
poi_type_name_".$this->language." ASC";
$result = mysql_query($sql);
if(!$result)
{
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= "Whole query: \n\n$sql\n";
die($message);
}
while($row = mysql_fetch_array($result))
{
$poiTypes[] = array('id' => $row['poi_type_id'] ,'name' => $row['poi_type_name']);
}
print_r($poiTypes);
if ($this->_cache)
{
$this->_cache->save($key, $poiTypes);
}
}
foreach($poiTypes as $poiType)
{
$count_type = null;
if($this->_cache)
{
$key = $this->getCacheKey()."poiTypeCount:{$poiType['id']}:{$this->metro_id}";
$count_type = $this->_cache->load($key);
}
if(!$count_type)
{
$sql = "SELECT COUNT(*) FROM
poi
WHERE
find_in_set('{$poiType['id']}', poi_type_id_array)
AND poi_status = 1 AND poi_address_prefecture_id = '$this->metro_id'";
$result = mysql_query($sql) or die(mysql_error());
}
if(!$result)
{
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= "Whole query: \n\n$sql\n";
die($message);
}
while($count = mysql_fetch_array($result))
{
$count_type[$poiType['id']][$this->metro_id] = $count['COUNT(*)'];
}
if($this->_cache)
{
$this->_cache->save($key, $count_type);
}
}
}
Any help is Highly appreciated, I hope I am being clear enough and thanks in advance.
I'm noy sure if this will help you, but you have several options to access those values.
Option 1: return an array with the variables you need
return array($myVar1, $myVar2, ..., $myVarN);
Option 2 (less modular): create the html string inside that function and then echo or return the string.
Im assuming that you have a basic knowledge of Zend
The basic idea of Zend framework is the link between controller ,models and view
Your model file,BlaBla.php
Class Namespace_models_BlaBla extends Zend_Db_Table_Abstract{
public function foo(){
return 'hello world';
}
}
Your controller say BarController and an action say test
class BarController extends extends Zend_Controller_Action{
public function testAction(){
$class = new Namespace_models_BlaBla();
$this->view->string = $class->foo();
}
}
Your html side // test.phtml
<?php echo $this->string; ?> /**this will output hello world **/

Categories