Normal calling object inside Model VS fetchAll() - php

Im new to zendframework & zend db..any help will be great!!
(Normal Way)
Lets say i want to get data..so im using this
Inside Controller
$db = new Studentfinance_Model_DbTable_FeeItem();
$data =$this->db->getDate();
Inside Model
protected $_name = 'tbl_foo_foo';
protected $_primary = "foo_id";
public function getData() {
$db = Zend_Db_Table::getDefaultAdapter();
$selectData = $db->select()
->from(array('a'=>$this->_name))
->joinLeft(array('c'=>'tbl_bar'), 'c.idBar = a.id',array('DefinitionDesc','Status'))
->group('a.id')
$fc_cat = $db->fetchAll($selectData);
return($fc_cat);
}
For Above line of code...i understand the way its work..
But for below..i have a bit problem to understand..same concept..the purpose to get the data
inside controller/form
$feeCategoryDb = new Studentfinance_Model_DbTable_FeeCategory();
$listData = $feeCategoryDb->fetchAll();
i try to find function fetchAll()...but i dont find it inside Model FeeCategory...can someone explainn this

$feeCategoryDb->getData() already sets up the query and runs "fetchAll" and returns the results. So all you need to do is:
$feeCategoryDb = new Studentfinance_Model_DbTable_FeeCategory();
$listData = $feeCategoryDb->getData();

Related

How can use variable model several time in laravel 5.4

How can use variable model several time, something like this code:
$Db = Model::where(['user_id'=>1]);
$Db->first();
$Db->get();
$Db->delete();
I dont want using repeat $Db for get,first,delete or etc
for example I dont prefer using bad code something like this:
$Db = Model::where(['user_id'=>1])->first();
$Db = Model::where(['user_id'=>1])->get();
$Db = Model::where(['user_id'=>1])->delete();
or ...
I want separate class object for any first() or get() or ...
I haven't tested this but try using query builder https://laravel.com/docs/5.4/queries#introduction
$qb = DB::table('users')->where('votes', '>', 100);
$qb->get();
$qb->first();
$qb->delete();
Another option is to use a closure
$model = function() {
return Model::where(['user_id'=>1]);
};
$model()->get();
$model()->first();
$model()->delete();
Again, not tested :)
You can use:
$Db = Model::where(['user_id'=>1]);
with(clone($Db))->first();
with(clone($Db))->get();
with(clone($Db))->delete();
The best way you can do is to create a helper or class.
// create
public static function user_info($user_id) {
return Model::where(['user_id' => $user_id]);
}
// call
Helpers:user_info(1)->first();
Helpers:user_info(1)->get();
Helpers:user_info(1)->delete();

PHP how to send array variables to Class function

I'm writing a code in PHP OOP and I'm trying to send $_POST data
filtered by one Class function to another Class function that will add
the data to database. Specifically login and password in registration
form.
I have 3 Classes that will do that:
Is simple Class that handles connection to database (I think it is not necessary to put code here)
Is the Class that filters the coming $_POST-s:
class Filter extends Dbconnect {
protected $login;
protected $haslo;
public function regFilter() {
if (isset($_POST))
{
foreach($_POST as $key => $val)
{
$filterVal = strip_tags($val);
$filterVal = htmlspecialchars($filterVal);
$filterVal = stripslashes($filterVal);
$filterVal = str_replace("\\", "", $filterVal);
$filter = array(
$key => $filterVal
);
foreach($filter as $key => $val)
{
echo "[$$key]";
echo "$val";
$
{
$key
} = $val;
}
}
return $filter = array(
'login' => $login,
'haslo' => $haslo
);
}
else
{
echo "Proszę podać login i hasło!";
}
}
}
Class that will get login and password and send it to DB:
class Dbinsert extends regFilter{
//protected $login;
//protected $haslo;
protected $query;
protected $dbo;
public function insert(){
//$this->extract = extract($filter);
//$this->login = $login;
//$this->haslo = $haslo;
$this->connect();
$this->query = "INSERT INTO uzytkownik (id, nazwa, haslo) VALUES ('', :login, OLD_PASSWORD(:haslo))";
if(!$result = $this->connect()->prepare($this->query)){
echo 'Zapytanie nie powiodło się';
}
else{
$result->bindParam(':login', $login);
$result->bindParam(':haslo', $haslo);
$login = $_POST['login'];
$haslo = $_POST['haslo'];
$result->execute();
}
$dbo = null;
}
}
Now when I try to send data from form with objects:
$rejestruj = new Dbinsert();
$filtruj = $rejestruj->regFilter();
var_dump($filtruj);
$dodaj = $filtruj->insert();
I get the following result:
[$login]login
[$haslo]password123
array(2) { ["login"]= string(5) "login" ["haslo"]= string(11) "password123" }
Fatal error: Call to a member function insert() on array in `E:\Xampp\htdocs\php\bazy_danych\obiektowe\my\register.php` on line 78
Which doesn't surprises me since: login and haslo is returned from
"foreach" loop in class Filter (which is just for testing) "array(2)"
is returned from "var_dump($filtruj);"(to check if it is actually
working) and error is returned since I send an array to Class
Dbinsert - but in the function I put "extract" to get the variables.
How can I send just the variables from this filtered array to class
Dbinsert?
Edit: As #Twinfriends suggested I corrected function insert in class Dbinsert to actually use prepared statement, thats why (for now) login and haslo variables are reffering to $_POST. Now I need answer to my question.
(First time posting, thanks for edit suggestions, also any advice is appreciated since I'm quite the beginner
in PHP)
Sorry that it took so long to answer, I totally forgot your question. Well, lets take a look at your problem, hope to solve it.
I try to explain it as good as I can, so that you understand whats going on. First of all, lets look at your error message
Fatal error: Call to a member function insert() on array in
E:\Xampp\htdocs\php\bazy_danych\obiektowe\my\register.php on line 78
Okay. Call to a function on array... lets have a look at how you actually call the function:
$rejestruj = new Dbinsert();
$filtruj = $rejestruj->regFilter();
var_dump($filtruj);
$dodaj = $filtruj->insert();
And exactly here is your error. You have to understand that you call methods on objects and pass your data to this methods, not to call the methods on your data. What do I mean with that?
$rejestruj is your Dbinsert object. You create it in your first line of code here. Then, you call the regFilter function on it. Still anything is fine. As you see, var_dump gives you the expected results. So the error has to be on your last lane of code. And indeed, you try to call the method insert() on your array. And that won't work, since your array don't know any method called insert().
The right call to the method would be (Not the final one!!!):
$dodaj = $rejestruj->insert();
Now the method call should work. But in fact, it won't insert anything. Why? Because your insert() method try to bind the variables $login and $haslo - two variables the method don't know. So we need to pass the data in your method. To do that, you have to do the following changes:
Method call:
$rejestruj->insert($filtruj); // $filtruj contains your array
And your Dbinsert should look like:
class Dbinsert extends Dbconnect{
protected $query;
protected $dbo;
public function insert($data){
$this->connect();
$this->query = "INSERT INTO uzytkownik (id, nazwa, haslo) VALUES ('', :login, OLD_PASSWORD(:haslo))";
if(!$result = $this->connect()->prepare($this->query)){
echo 'Zapytanie nie powiodło się';
}
else {
$result->bindParam(':login', $data["login"]);
$result->bindParam(':haslo', $data["haslo"]);
$result->execute();
}
$dbo = null;
}
}
I hope your code works with this changes. So, while in my opinion the code should work now, I want to mention that there are many things you could improve. For example, you're not programming real "object-oriented" ... its more some pseudo OOP you're writing here. Some things are quite bad practice (could be done much easier). I don't want to dive to deep into details, since I don't know if you're interested in it. If you wish I can give you some more advises, but only if you wish.
Otherwise I really hope my answer help you. If the whole thing still doesn't work, please let me know so I can look at it again.
Have a nice day ;)
Edit:
Since it seems I haven't been clear enough, here the code how it should look like now:
$rejestruj = new Dbinsert();
$filtruj = $rejestruj->regFilter();
$dodaj = $rejestruj->insert($filtruj);

PHP Calling dynamic functions

Im trying to figure out how to call functions based on what a user clicks on a form. But im not sure if im doing it right.
I have a number of classes, lets say 3 for different ways to connect to a site, the user clicks on which one they would like.
FTP
SFTP
SSH
Which i have named 'service' in my code.
I don't want to run a whole bunch of IF statements, i would rather try and build the call dynamically.
What i have at the moment is as follows
$ftp_backup = new FTPBackup;
$sftp_backup = new SFTPBackup;
$ssh_backup = new SSHBackup;
$service = $request->input('service') . '_backup';
$service->testConn($request);
Im getting the following error
Call to a member function testConn() on string
Im not sure im doing this right.
Any help would be greatly appreciated.
Thanks
First of all $service is a string on which You cannot call method, because it is not an object (class instance).
I think it is a great example of where You can use Strategy Pattern which look like that:
class BackupStrategy {
private $strategy = null;
public function __construct($service_name)
{
switch ($service_name) {
case "ftp":
$this->strategy = new FTPBackup();
break;
case "sftp":
$this->strategy = new SFTPBackup();
break;
case "ssh":
$this->strategy = new SSHBackup();
break;
}
}
public function testConn()
{
return $this->strategy->testConn();
}
}
And then in place where You want to call it You call it by:
$service = new BackupStrategy($request->input('service'));
$service->testConn($request);
I suggest You to read about Design Patterns in OOP - it will help You a lot in the future.
How about this:
$ftp_backup = new FTPBackup;
$sftp_backup = new SFTPBackup;
$ssh_backup = new SSHBackup;
$service = $request->input('service') . '_backup';
${$service}->testConn($request);
This is called "Variables variable": http://php.net/manual/en/language.variables.variable.php
// Create class name
$className = $request->get('service') . '_backup';
// Create class instance
$service = new $className();
// Use it as you want
$service->testConn($request);

PHP Instantiate obj class with variable not working

I found a problem that I not sure if is a bug of the php or on my code (probably mine) so let me show you what is happening:
<?php namespace MyApp\Conciliation;
use SimpleExcel\SimpleExcel;
use ForceUTF8\Encoding;
use MyApp\Conciliation\Gol;
class Conciliation {
protected function equalizeFile($file, $providerName)
{
$type = false;
$nfile = 'public'.$file;
// TEST 1: the ideal aproach. not working (see error#1 bellow)
$provider = new $providerName();
// TEST 2: working, getting the correct response
$provider = new Gol();
// TEST 3: working, getting the correct response
$provider = new MyApp\Conciliation\Gol();
$provider->equalize($nfile);
}
Note, the $providerName = 'Gol';
error1
Class 'Gol' not found
http://inft.ly/N8Q6F4B
So, there is any way that I could keeping using variables to instantiate aliases similar as above?
Edit, Problem solved: working example
<?php namespace MyApp\Conciliation;
use SimpleExcel\SimpleExcel;
use ForceUTF8\Encoding;
class Conciliation {
protected function equalizeFile($file, $providerName)
{
$type = false;
$nfile = 'public'.$file;
$providerName = "MyApp\\Conciliation\\".$providerName;
$provider = new $providerName();
$provider->equalize($nfile);
}
http://php.net/manual/en/language.namespaces.dynamic.php
If you are calling the class dynamically, you have to use the full path to the class.
So, your call to equalizeFile should be something like:
equalizeFile("myFile", "MyApp\\Conciliation\\Gol");

Accessing array in class structure

I want to validate a form with php.
Therefor I created a class "benutzer" and a public function "benutzerEintragen" of this class to validate the form:
class benutzer
{
private $username = "";
private $mail = "";
private $mail_check = "";
private $passwort = "";
private $passwort_check = "";
public $error_blank = array();
public $error_notSelected = array();
public $error_notEqual = array();
public function benutzerEintragen () {
$textfields[0] = $this->username;
$textfields[1] = $this->mail;
$textfields[2] = $this->mail_check;
$textfields[3] = $this->passwort;
$textfields[4] = $this->passwort_check;
foreach ($textfields as $string) {
$result = checkFormular::emptyVariable($string);
$error_blank[] = $result;
}
In the function "benutzerEintragen" i filled the variables "username,mail" and so on with the appropriate $_POST entries (not shown in the code above). The call
checkFormular::emptyVariable($string)
just returns "TRUE" if the field is not set or empty otherwise FALSE.
Now when i try to create a new instance of this class, execute the function and get access to $error_blank[0] the array is empty!
if (($_SERVER['REQUEST_METHOD'] == 'POST')){
$BENUTZER = new benutzer();
$BENUTZER->benutzerEintragen();
echo $BENUTZER->error_blank[0];}
So the last line is leading to a "Notice: Undefined offset: 0". It seems to be related to the array structure, because if i do
echo $BENUTZER->mail;
I get any input I wrote in the form, which is correct. Also the foreach loop seems to do the right thing when i run the debugger in phpEd, but it seems like the array "error_blank" is erased after the function is executed.
Any help would be greatly appreciated. Thanks in advance.
There is a scope problem here. You do have a class attribute with the name. Unlike in Java where using a local variable with the same name as a class variable automatically selects the class attribute this is not the case in PHP.
Basically you are saving your output in a local variable which gets discarded once you leave the function. Change $error_blank[] = $result; to $this->error_blank[] = $result; and you should be fine.
First of all this seems overly complicated way to do a simple task, but that wasn't actually the question.
You are creating a new $error_blank variable that is only in function scope. If you wish to use the class variable you should use $this->error_blank[]

Categories