Can't solve 'Invalid arguments passed' - php

Why do I get this error?
Warning: implode(): Invalid arguments passed in /Applications/XAMPP/xamppfiles/htdocs/basis/php/php.php on line 17
index.php:
<?php
require_once 'php.php';
$piet = new Persoon();
$piet->voornaam = 'Piet';
$piet->achternaam = 'Jansen';
echo "De naam is: " . $piet->showNaam();
$piet->addHobby('zeilen');
$piet->addHobby('hardlopen');
echo "<br/> De hobbies van {$piet->showNaam()} zijn: {$piet->showHobbies()}";
?>
php.php
<?php
class Persoon {
public $voornaam = '';
public $achternaam = '';
protected $adres;
protected $hobbies;
public function showNaam() {
return $this->voornaam . ' ' . $this->achternaam;
}
public function addHobby($hobby) {
$hobbies[] = $hobby;
}
public function showHobbies() {
echo implode(', ', $this->hobbies);
}
}
?>

In addHobby() method, you must be used $this->hobbies instead of $hobbies. It's better to initialize hobbies with empty array to prevent error.
<?php
class Persoon {
public $voornaam = '';
public $achternaam = '';
protected $adres;
protected $hobbies = array();
public function showNaam() {
return $this->voornaam . ' ' . $this->achternaam;
}
public function addHobby($hobby) {
$this->hobbies[] = $hobby;
}
public function showHobbies() {
echo implode(', ', $this->hobbies);
}
}
?>

Variable access is wrong.
<?php
class Persoon {
public $voornaam = '';
public $achternaam = '';
protected $adres;
protected $hobbies;
public function showNaam() {
return $this->voornaam . ' ' . $this->achternaam;
}
public function addHobby($hobby) {
$this->hobbies[] = $hobby; <--- change this
}
public function showHobbies() {
//echo implode(', ', $this->hobbies);// remove this
echo count($this->hobbies) ? implode(', ', $this->hobbies) : "";// this will avoid errors in future if your array is empty.
}
}
?>

Your code is creating a new array everytime you call addHobby($hobby) function , what you need to do is to access it correctly . Change
public function addHobby($hobby) {
$hobbies[] = $hobby;
}
to
public function addHobby($hobby) {
$this->hobbies[] = $hobby;
}

Related

Need to identify an administrator with PHP and PDO

I do a project of an classified advertisements website, with PHP, Twig, SQL and PDO.
I want to put an elseif in the main.php (last part of code) during the users identification, and check if the user is an admin or not. My Admins value is a boolean in my table. I don't know how to do this checking.
First my user class :
<?php
class Utilisateur
{
private $ID_UTILISATEUR;
private $MDP_UTILISATEUR;
private $MAIL_UTILISATEUR;
private $NOM_UTILISATEUR;
private $PRENOM_UTILISATEUR;
private $ADMINS;
//CONSTRUCTEUR
public function __construct($id_user = -1, $user_pass = null, string $user_mail = null, string $nom = null, string $prenom = null, $admins = null)
{
$this->ID_UTILISATEUR = $id_user;
$this->MDP_UTILISATEUR = $user_pass;
$this->MAIL_UTILISATEUR = $user_mail;
$this->NOM_UTILISATEUR = $nom;
$this->PRENOM_UTILISATEUR = $prenom;
$this->ADMINS = $admins;
}
//GETTERS
public function getID_UTILISATEUR()
{
return $this->ID_UTILISATEUR;
}
public function getMDP_UTILISATEUR()
{
return $this->MDP_UTILISATEUR;
}
public function getMAIL_UTILISATEUR()
{
return $this->MAIL_UTILISATEUR;
}
public function getNOM_UTILISATEUR()
{
return $this->NOM_UTILISATEUR;
}
public function getPRENOM_UTILISATEUR()
{
return $this->PRENOM_UTILISATEUR;
}
public function getADMINS()
{
return $this->ADMINS;
}
//SETTERS
public function setID_UTILISATEUR($ID_UTILISATEUR)
{
$this->ID_UTILISATEUR = $ID_UTILISATEUR;
}
public function setMDP_UTILISATEUR($MDP_UTILISATEUR)
{
$this->MDP_UTILISATEUR = $MDP_UTILISATEUR;
}
public function setMAIL_UTILISATEUR($MAIL_UTILISATEUR)
{
$this->MAIL_UTILISATEUR = $MAIL_UTILISATEUR;
}
public function setNOM_UTILISATEUR($NOM_UTILISATEUR)
{
$this->NOM_UTILISATEUR = $NOM_UTILISATEUR;
}
public function setPRENOM_UTILISATEUR($PRENOM_UTILISATEUR)
{
$this->PRENOM_UTILISATEUR = $PRENOM_UTILISATEUR;
}
public function setADMINS($ADMINS)
{
$this->ADMINS = $ADMINS;
}
//FONCTION stringID
public function stringID()
{
return "[" . $this->ID_UTILISATEUR . "]";
}
//FONCTION __toString
public function __toString()
{
return $this->ID_UTILISATEUR . ", " . $this->NOM_UTILISATEUR . ", " . $this->MAIL_UTILISATEUR;
}
}
Then my DAO for getting the data of a user :
public function identifier(Utilisateur $u)
{
try
{
$n = $u->getMAIL_UTILISATEUR();
$p = $u->getMDP_UTILISATEUR();
$requete = $this->cnx->prepare("SELECT ID_UTILISATEUR, MDP_UTILISATEUR, MAIL_UTILISATEUR, ADMINS FROM utilisateur WHERE MAIL_UTILISATEUR=:mail and MDP_UTILISATEUR=SHA2(:pass,224)");
$requete->bindParam(':mail', $n);
$requete->bindParam(':pass', $p);
$requete->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'Utilisateur');
// exécution et récupération des résultats
$data2 = $requete->execute();
$data2 = $requete->fetchAll(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'Utilisateur');
return $data2;
}
catch (PDOException $e)
{
throw new BDDException ("Impossible d'identifier les données", 201);
}
}
and the main.php function identify users :
function identifierUtilisateur()
{
require_once dirname(__DIR__) . "/DAO/MySQLUtilisateurDAO.php";
require_once dirname(__DIR__) . "/views/VueLogin.php";
$login = new MySQLUtilisateurDAO();
$login1 = new Utilisateur("", $_POST['mdp'], $_POST['mail'], "", "", "");
$l = $login->identifier($login1);
if (empty($l)) {
echo 'utilisateur non identifié';
$url = $_SERVER["PHP_SELF"];
echo ('<a href=' . $url . '>return</a>');
}
else {
$_SESSION['identification'] = $l;
$mail = $_POST['mail'];
$mdp = $_POST['mdp'];
setcookie("MAIL_UTILISATEUR", $mail, time() + 864000, '/'); // expire après 10 jours
setcookie("MDP_UTILISATEUR", $mdp, time() + 864000, '/');
$url = $_SERVER["PHP_SELF"];
afficherAnnoncesUtilisateur();
}
}

my custom function not working

i create function called empty_fields but i can't figure out, to make it work..
<?php
function empty_fields($field_name)
{
if(!empty($order[$field_name]))
{
$output = "<li>Indigofera - " . $order[$field_name] . "Kg</li>";
} else { $output = null; }
return $output;
}
to display in html
<?php empty_fields('indigofera'); ?>
Change
if(!empty($order['$field_name'])){
to
if(!empty($order[$field_name])){
'$field_name' does not evaluate to anything and it will search for
key '$field_name' in the $orders array everytime, hence will not work.
Hope it works.
If you use $order as a global variable, use:
function empty_fields($field_name)
{
global $order;
$output = null;
if(!empty($order[$field_name]))
{
$output = "<li>Indigofera - " . $order[$field_name] . "Kg</li>";
}
return $output;
}
and use it:
<?php echo empty_fields('indigofera'); ?>
EDIT: the OOP way:
class Orders
{
private $order = null;
public function get_order()
{
$this->order = //....
}
public function empty_fields($field_name)
{
if(!isset($this->order) || empty($order[$field_name])) return;
return "<li>Indigofera - " . $order[$field_name] . "Kg</li>";
}
}
and use it:
<?php
$orders = new Orders();
$orders->get_order();
echo $orders->empty_fields("indigofera");

PHP illegal offset type error

Getting an illegal offset type error on this line in the second foreach loop.
$userlist[$user]->addPeriod($period);
Made some changes from past info given in past threads and this is the new version of the code. There is also a warning but I think that might be resolved if the error is resolved:
Call to a member function addPeriod() on a non-object
$periods_arr = array(1, 2, 3, 4, 5);
$subPeriods_arr = array(1, 2);
$questionslist = array("q_1_1", "q_1_2", "q_2_1", "q_2_2", "q_3_1", "q_4_1", "q_5_1");
class User {
public $userId;
public $periods = array();
public function __construct($number)
{
$this->userId = $number;
}
public function addPeriod($pno)
{
$this->periods[] = new Period($pno);
}
}
class Period {
public $periodNo;
public $subPeriods = array();
public function __construct($number)
{
$this->periodNo = $number;
}
public function addSubPeriod($spno)
{
$this->subPeriods[] = new SubPeriod($spno);
}
}
class SubPeriod {
public $SubPeriodNo;
public $answers = array();
public function __construct($number)
{
$this->SubPeriodNo = $number;
}
public function addAnswer($answer)
{
$this->answers[] = new Question($answer);
}
}
class Question {
public $answer;
public function __construct($ans)
{
$this->answer = $ans;
}
public function getAnswer()
{
echo $answer;
}
}
$userlist = array();
$sql = 'SELECT user_ref FROM _survey_1_as GROUP BY user_ref ORDER BY user_ref ASC';
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
$userlist[] = new User($row['user_ref']);
}
foreach ($userlist as &$user)
{
foreach ($periods_arr as &$period)
{
$userlist[$user]->addPeriod($period);
foreach ($subPeriods_arr as &$subPeriod)
{
$userlist[$user]->periods[$period]->addSubPeriod($subPeriod);
foreach($questionslist as &$aquestion)
{
$sql = 'SELECT ' . $aquestion . ' FROM _survey_1_as WHERE user_ref = ' .
$user . ' AND answer_sub_period = ' . $subPeriod . ' AND answer_period = ' . $period .'';
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
$userlist[$user]->periods[$period]->subPeriods[$subPeriod]->addAnswer($row[$questionNumber]);
}
}
}
}
}
$userlist[3]->periods[3]->subPeriods[1]->getAnswer();
You're using $user as a key into your $userlist array, but you're fetching it as a value. Try something like this:
foreach ($userlist as $user => $userVal)
{
...
$userlist[$user]->addPeriod($period);
}
This makes $user the key into your $userlist array.
It would be even clearer to do something like this:
foreach ($userlist as $user)
{
}
And then don't use $user as a key into your array, but just use $user as the value. For example:
$user->addPeriod($period);
...
$user->periods[$period]->addSubPeriod($subPeriod);

php array function in class

I cant get this script to work, $users should hold the array data we take out of the database but it doesnt seem to work. Can anyone tell us what we are doing wrong? i posted the script bellow.
added
$users has to stay static becaus it gets used again later on in the script (this is just a small part)
$user1 does get the right data it just doesnt get passed on to $users
added
this is the intire script hope that helps
<?php
class SingleSignOn_Server
{
public $links_path;
protected $started=false;
protected static $brokers = array(
'FGPostbus' => array('secret'=>"FGPostbus123"),
);
protected static $users = array();
public function query_personen(){
mysql_connect('host','user','pass') or die("Kan helaas geen verbinding maken" . mysql_error());
mysql_select_db('db') or die("Kan geen database selecteren");
$sql = mysql_query('select p_gebruikersnaam, p_wachtwoord, p_id, p_md5 FROM personen');
while ($row_user = mysql_fetch_assoc($sql)) {
self::$users[] = $row_user;
}
}
protected $broker = null;
public function __construct()
{
if (!function_exists('symlink')) $this->links_path = sys_get_temp_dir();
}
protected function sessionStart()
{
if ($this->started) return;
$this->started = true;
$matches = null;
if (isset($_REQUEST[session_name()]) && preg_match('/^SSO-(\w*+)-(\w*+)-([a-z0-9]*+)$/', $_REQUEST[session_name()], $matches)) {
$sid = $_REQUEST[session_name()];
if (isset($this->links_path) && file_exists("{$this->links_path}/$sid")) {
session_id(file_get_contents("{$this->links_path}/$sid"));
session_start();
setcookie(session_name(), "", 1);
} else {
session_start();
}
if (!isset($_SESSION['client_addr'])) {
session_destroy();
$this->fail("Not attached");
}
if ($this->generateSessionId($matches[1], $matches[2], $_SESSION['client_addr']) != $sid) {
session_destroy();
$this->fail("Invalid session id");
}
$this->broker = $matches[1];
return;
}
session_start();
if (isset($_SESSION['client_addr']) && $_SESSION['client_addr'] != $_SERVER['REMOTE_ADDR']) session_regenerate_id(true);
if (!isset($_SESSION['client_addr'])) $_SESSION['client_addr'] = $_SERVER['REMOTE_ADDR'];
}
protected function generateSessionId($broker, $token, $client_addr=null)
{
if (!isset(self::$brokers[$broker])) return null;
if (!isset($client_addr)) $client_addr = $_SERVER['REMOTE_ADDR'];
return "SSO-{$broker}-{$token}-" . md5('session' . $token . $client_addr . self::$brokers[$broker]['secret']);
}
protected function generateAttachChecksum($broker, $token)
{
if (!isset(self::$brokers[$broker])) return null;
return md5('attach' . $token . $_SERVER['REMOTE_ADDR'] . self::$brokers[$broker]['secret']);
}
public function login()
{
$this->sessionStart();
if (empty($_POST['p_gebruikersnaam'])) $this->failLogin("No user specified");
if (empty($_POST['p_wachtwoord'])) $this->failLogin("No password specified");
if (!isset(self::$users[$_POST['p_gebruikersnaam']]) || self::$users[$_POST['p_gebruikersnaam']]['p_wachtwoord'] != md5($_POST['p_wachtwoord'])) $this->failLogin("Incorrect credentials");
$_SESSION['user'] = $_POST['p_gebruikersnaam'];
$this->info();
}
public function logout()
{
$this->sessionStart();
unset($_SESSION['user']);
echo 1;
}
public function attach()
{
$this->sessionStart();
if (empty($_REQUEST['broker'])) $this->fail("No broker specified");
if (empty($_REQUEST['token'])) $this->fail("No token specified");
if (empty($_REQUEST['checksum']) || $this->generateAttachChecksum($_REQUEST['broker'], $_REQUEST['token']) != $_REQUEST['checksum']) $this->fail("Invalid checksum");
if (!isset($this->links_path)) {
$link = (session_save_path() ? session_save_path() : sys_get_temp_dir()) . "/sess_" . $this->generateSessionId($_REQUEST['broker'], $_REQUEST['token']);
if (!file_exists($link)) $attached = symlink('sess_' . session_id(), $link);
if (!$attached) trigger_error("Failed to attach; Symlink wasn't created.", E_USER_ERROR);
} else {
$link = "{$this->links_path}/" . $this->generateSessionId($_REQUEST['broker'], $_REQUEST['token']);
if (!file_exists($link)) $attached = file_put_contents($link, session_id());
if (!$attached) trigger_error("Failed to attach; Link file wasn't created.", E_USER_ERROR);
}
if (isset($_REQUEST['redirect'])) {
header("Location: " . $_REQUEST['redirect'], true, 307);
exit;
}
header("Content-Type: image/png");
readfile("empty.png");
}
public function info()
{
$this->sessionStart();
if (!isset($_SESSION['user'])) $this->failLogin("Not logged in");
header('Content-type: text/xml; charset=UTF-8');
echo '<?xml version="1.0" encoding="UTF-8" ?>', "\n";
echo '<user identity="' . htmlspecialchars($_SESSION['user'], ENT_COMPAT, 'UTF-8') . '">';
echo ' <p_id>' . htmlspecialchars(self::$users[$_SESSION['user']]['p_id'], ENT_COMPAT, 'UTF-8') . '</p_id>';
echo ' <p_md5>' . htmlspecialchars(self::$users[$_SESSION['user']]['p_md5'], ENT_COMPAT, 'UTF-8') . '</p_md5>';
echo '</user>';
}
protected function fail($message)
{
header("HTTP/1.1 406 Not Acceptable");
echo $message;
exit;
}
protected function failLogin($message)
{
header("HTTP/1.1 401 Unauthorized");
echo $message;
exit;
}
}
if (realpath($_SERVER["SCRIPT_FILENAME"]) == realpath(__FILE__) && isset($_GET['cmd'])) {
$ctl = new SingleSignOn_Server();
$ctl->$_GET['cmd']();
}
At the very least you probably want to:
self::$users[] = $users1[$row_user['p_gebruikersnaam']] = $row_user;
Since as is you where replacing the record every time and keeping only one.
You're building an array as a property of an object, but not using an instance of the object. You need to build a new instance ($usersObject = new ObjectName;), drop the static keywords, and instead of self::, use $this->. You also need square brackets after self::$users, like this: self::$users[].
Shouldn't this self::$users = $users1[$row_user['p_gebruikersnaam']] = $row_user; be:
array_push($this->users, $row_user)
You could put directly the result into the array:
while (false === ($row_user = mysql_fetch_array($sql, MYSQL_ASSOC)))
self::$users[$row_user['p_gebruikersnaam']] = $row_user;

Call to a member function on a non-object (first try of writing OOP) [duplicate]

This question already has answers here:
Call to a member function on a non-object [duplicate]
(8 answers)
Closed 10 years ago.
The class below is my first attempt at writing my own OOP application. I've used procedural for a while and the OO techniques are not coming as easily as I'd hoped.
The class is designed to put together input elements for HTML forms, optionally using SQL table records. I'm starting with the select box and will add more when I get this much working.
So the problem is that I'm getting
"Call to a member function get_table() on a non-object" on the 'public function get_table()' line of the Class code below.
I'm not sure why this is happening. Help/tips would be GREATLY appreciated.
and now the code:
Application:
$_input = new html_form_input();
$_input->set_input_type('select');
$_input->set_table('stores');
$_input->set_fieldname_id('store_id');
$_input->set_fieldname_desc('store_name');
$_input->set_sql_order(' ORDER BY store_name ASC ');
$_input->set_select();
$html_select_facility = $_input->get_select();
Class:
class html_form_input
{
public $input_type;
public $table;
public $fieldname_id;
public $fieldname_desc;
public $passed_id;
public $sql_where;
public $sql_order;
public $array_input_options;
public function __construct()
{
// constructor method
}
/*
setters
*/
public function set_input_type($input_type)
{
$this->input_type = $input_type;
}
public function set_array_input_options($array_input_options)
{
$this->array_input_options = $array_input_options;
}
public function set_table($table)
{
$this->table = $table;
}
public function set_fieldname_id($fieldname_id)
{
$this->fieldname_id = $fieldname_id;
}
public function set_fieldname_desc($fieldname_desc)
{
$this->fieldname_desc = $fieldname_desc;
}
public function set_passed_id($passed_id)
{
$this->passed_id = $passed_id;
}
public function set_sql_where($sql_where)
{
$this->sql_where = $sql_where;
}
public function set_sql_order($sql_order)
{
$this->sql_order = $sql_order;
}
/*
getters
*/
public function get_input_type()
{
return $this->$input_type;
}
public function get_array_input_options()
{
return $this->$array_input_options;
}
public function get_table()
{
return $this->$table;
}
public function get_fieldname_id()
{
return $this->$fieldname_id;
}
public function get_fieldname_desc()
{
return $this->$fieldname_desc;
}
public function get_passed_id()
{
return $this->$passed_id;
}
public function get_sql_where()
{
return $this->$sql_where;
}
public function get_sql_order()
{
return $this->$sql_order;
}
/*
set_query_form_data() queries the database for records to be used in the input element.
*/
public function set_query_form_data()
{
global $dbx;
$debug = true;
$_debug_desc = "<span style='color:blue;'>function</span> <b>set_query_form_data</b>()";
if ($debug) { echo "<p>BEGIN $_debug_desc <blockquote>"; }
$table->get_table();
$fieldname_id->get_fieldname_id();
$fieldname_desc->get_fieldname_desc();
$passed_id->get_passed_id();
$sql_where->get_sql_where();
$sql_order->get_sql_order();
if ($passed_id)
{
if (!is_array($passed_id))
{
$passed_id[] = $passed_id;
}
}
if ($sql_where!='')
{
$sql_where = " WHERE $sql_where ";
}
$q = "
SELECT
$fieldname_id,
$fieldname_desc
FROM
$table
$sql_where
$sql_order
";
$res = $mdb2_dbx->query($q);
if (PEAR::isError($res)) { gor_error_handler($res, $q, __LINE__,__FILE__,'die'); }
while ( $r = $res->fetchRow(MDB2_FETCHMODE_ASSOC) )
{
$id = $r[$fieldname_id];
$desc = $r[$fieldname_desc];
$array_values[$id] = $desc;
}
$this->sql_array_values = $array_values;
if ($debug) { echo "<p></blockquote>END $_debug_desc "; }
}
/*
getter for set_query_form_data (above)
*/
public function get_query_form_data()
{
return $this->$array_values;
}
/*
set_select() pieces together a select input element using database derived records, or a passed array of values.
*/
public function set_select($flag_query_db=1, $array_static_values=null)
{
if ($flag_query_db==1)
{
$array_values = $this->set_query_form_data();
} else if (is_array($array_static_values)) {
$array_values = $array_static_values;
}
$array_values = $array_data['row_data'];
$fieldname_id = $array_data['fieldname_id'];
$fieldname_desc = $array_data['fieldname_desc'];
$passed_id = $array_data['passed_id'];
if (!is_array($passed_id))
{
$passed_id[] = $passed_id;
}
foreach ($array_values as $id=>$desc)
{
// handle passed values (multiple or single)
$sel = null;
if (in_array($id,$passed_id))
{
$sel = ' selected ';
}
// construct html
$html_options .= " <option value='$id' $sel>$desc</option>\n";
}
$disabled = null;
$multiple = null;
$size = null;
$style = null;
$class = null;
$element_id = null;
$javascript = null;
if (is_array($array_input_options))
{
$s_disabled = $array_input_options['disabled'];
$s_multiple = $array_input_options['multiple'];
$s_size = $array_input_options['size'];
$s_style = $array_input_options['style'];
$s_id = $array_input_options['id'];
$s_class = $array_input_options['class'];
$s_javascript = $array_input_options['javascript'];
if ($s_disabled!='') {$disabled = ' disabled '; }
if ($s_multiple!='') {$multiple = ' multiple '; }
if ($s_size!='') {$size = ' size="' . $s_size . '"'; }
if ($s_style!='') {$style = ' style = "' . $s_style . '"'; }
if ($s_id!='') {$element_id = ' id = "' . $s_id . '"'; }
if ($s_class!='') {$class = ' class = "' . $s_class . '"'; }
if ($s_javascript!='') {$javascript = $s_javascript; }
}
$html = "
<select name='$fieldname_id' $element_id $disabled $multiple $size $style $class $javascript>
$html_options
</select>
";
$this->select_html = $html;
}
/*
getter for set_select (above)
*/
public function get_select()
{
return $this->$select_html;
}
}
With your getters, instead of using $this->$var it should be $this->var, for example $this->table and not $this->$table.
In the following code, $table hasn't been initialised.
public function set_query_form_data()
{
global $dbx;
$debug = true;
$_debug_desc = "<span style='color:blue;'>function</span> <b>set_query_form_data</b>()";
if ($debug) { echo "<p>BEGIN $_debug_desc <blockquote>"; }
$table->get_table();
You probably intend it to be $this, i.e. "the object currently being used":
public function set_query_form_data()
{
global $dbx;
$debug = true;
$_debug_desc = "<span style='color:blue;'>function</span> <b>set_query_form_data</b>()";
if ($debug) { echo "<p>BEGIN $_debug_desc <blockquote>"; }
$this->get_table();
The problem is in your set_query_form_data method:
public function set_query_form_data() {
// $table is no object
$table->get_table();
// you should use this instead
$this->table
}
Note:
// Are you sure with this calls? Shouldn't it be $this->array_input_options ?
return $this->$array_input_options;
You're making use of variable functions/dereferencing, unintentionally. Example:
$foo = 'name';
echo $object->$foo; // same as echo $object->name
Object properties and methods do not need to be prefixed with $.
With the pointers from the other answers and some more RTM, I got the basic script working. In particular, I removed the "$" from property names and accessed the properties of $this instead of calling get_* methods.
Application:
$array_input_options = array(
'include_blank_option' => 1,
'disabled' => 0,
'multiple' => 0,
'size' => '',
'style' => '',
'id' => '',
'class' => '',
'javascript' => '',
);
$_input = new html_form_input();
$_input->set_input_type('select');
$_input->set_table('gor_facility');
$_input->set_fieldname_id('facilityid');
$_input->set_fieldname_desc('facilityname');
$_input->set_sql_where(' status = 1');
$_input->set_sql_order(' ORDER BY facilityname ASC ');
$_input->set_array_input_options($array_input_options);
// $_input->set_passed_id('');
$html_select_facility = $_input->create_select();
Class:
class html_form_input
{
public $input_type;
public $table;
public $fieldname_id;
public $fieldname_desc;
public $passed_id;
public $sql_where;
public $sql_order;
public $array_input_options;
public function __construct()
{
// constructor method
}
/*
setters
*/
public function set_input_type($input_type)
{
$this->input_type = $input_type;
}
public function set_array_input_options($array_input_options)
{
$this->array_input_options = $array_input_options;
}
public function set_table($table)
{
$this->table = $table;
}
public function set_fieldname_id($fieldname_id)
{
$this->fieldname_id = $fieldname_id;
}
public function set_fieldname_desc($fieldname_desc)
{
$this->fieldname_desc = $fieldname_desc;
}
public function set_passed_id($passed_id)
{
$this->passed_id = $passed_id;
}
public function set_sql_where($sql_where)
{
$this->sql_where = $sql_where;
}
public function set_sql_order($sql_order)
{
$this->sql_order = $sql_order;
}
/*
getters
*/
public function get_input_type()
{
return $this->input_type;
}
public function get_array_input_options()
{
return $this->array_input_options;
}
public function get_table()
{
return $this->table;
}
public function get_fieldname_id()
{
return $this->fieldname_id;
}
public function get_fieldname_desc()
{
return $this->fieldname_desc;
}
public function get_passed_id()
{
return $this->passed_id;
}
public function get_sql_where()
{
return $this->sql_where;
}
public function get_sql_order()
{
return $this->sql_order;
}
/*
set_query_form_data() queries the database for records to be used in the input element.
*/
public function set_query_form_data()
{
global $mdb2_dbx;
$debug = false;
$_debug_desc = "<span style='color:blue;'>function</span> <b>set_query_form_data</b>()";
if ($debug) { echo "<p>BEGIN $_debug_desc <blockquote>"; }
$table = $this->table;
$fieldname_id = $this->fieldname_id;
$fieldname_desc = $this->fieldname_desc;
$passed_id = $this->passed_id;
$sql_where = $this->sql_where;
$sql_order = $this->sql_order;
if ($passed_id)
{
if (!is_array($passed_id))
{
$passed_id[] = $passed_id;
}
}
if ($sql_where!='')
{
$sql_where = " WHERE $sql_where ";
}
$q = "
SELECT
$fieldname_id,
$fieldname_desc
FROM
$table
$sql_where
$sql_order
";
if ($debug) {echo "<p>$q<br>";}
$res = $mdb2_dbx->query($q);
if (PEAR::isError($res)) { gor_error_handler($res, $q, __LINE__,__FILE__,'die'); }
while ( $r = $res->fetchRow(MDB2_FETCHMODE_ASSOC) )
{
$id = $r[$fieldname_id];
$desc = $r[$fieldname_desc];
$array_values[$id] = $desc;
}
$this->sql_array_values = $array_values;
if ($debug) { echo "<p></blockquote>END $_debug_desc "; }
}
/*
getter for set_query_form_data (above)
*/
public function get_query_form_data()
{
return $this->sql_array_values;
}
/*
set_select() pieces together a select input element using database derived records, or a passed array of values.
*/
public function construct_select($flag_query_db=1, $array_static_values=null)
{
if ($flag_query_db==1)
{
$this->set_query_form_data();
$row_data = $this->sql_array_values;
} else if (is_array($array_static_values)) {
$row_data = $array_static_values;
}
$fieldname_id = $this->fieldname_id;
$fieldname_desc = $this->fieldname_desc;
$passed_id = $this->passed_id;
$array_input_options = $this->array_input_options;
if (!is_array($passed_id))
{
$passed_id[] = $passed_id;
}
$disabled = null;
$multiple = null;
$size = null;
$style = null;
$class = null;
$element_id = null;
$javascript = null;
$html_option_blank = null;
if (is_array($array_input_options))
{
$s_disabled = $array_input_options['disabled'];
$s_multiple = $array_input_options['multiple'];
$s_size = $array_input_options['size'];
$s_style = $array_input_options['style'];
$s_id = $array_input_options['id'];
$s_class = $array_input_options['class'];
$s_javascript = $array_input_options['javascript'];
$s_blank = $array_input_options['include_blank_option'];
if ($s_disabled!='') {$disabled = ' disabled '; }
if ($s_multiple!='') {$multiple = ' multiple '; }
if ($s_size!='') {$size = ' size="' . $s_size . '"'; }
if ($s_style!='') {$style = ' style = "' . $s_style . '"'; }
if ($s_id!='') {$element_id = ' id = "' . $s_id . '"'; }
if ($s_class!='') {$class = ' class = "' . $s_class . '"'; }
if ($s_javascript!='') {$javascript = $s_javascript; }
if ($s_blank==1) { $row_data = array(''=>'Select an option below:') + $row_data; }
}
if (is_array($row_data))
{
foreach ($row_data as $id=>$desc)
{
// handle passed values (multiple or single)
$sel = null;
if (in_array($id,$passed_id))
{
$sel = ' selected ';
}
// construct html
$html_options .= " <option value='$id' $sel>$desc</option>\n";
}
}
$html = "
<select name='$fieldname_id' $element_id $disabled $multiple $size $style $class $javascript>
$html_option_blank
$html_options
</select>
";
$this->select_html = $html;
}
/*
getter for set_select (above)
*/
public function create_select()
{
$this->construct_select();
return $this->select_html;
}
}

Categories