Strict Standards: Public Static Function :Errors - php

I'm having a bit of an issue. I just updated my dedicated server to PHP 5.4.17 and seem to be running into some strict standard issues. I can't hide the errors due to the unique way that our server and scripts handle errors, and just changing "public function" to "public static function" doesn't seem to be doing anything at all. Below is the snippet of code that is causing the error. Any help is appreciated.
ERROR MESSAGE
Strict Standards: Non-static method KRecord::new_record() should not be called statically, assuming $this from incompatible context in ../actions_controller.php on line 11
Strict Standards: Non-static method KRecord::sanitize_field_list() should not be called statically, assuming $this from incompatible context in ../krecord.php on line 70
Strict Standards: Non-static method KRecord::set_str() should not be called statically, assuming $this from incompatible context in ../krecord.php on line 72
Strict Standards: Non-static method KRecord::sanitize_field_list() should not be called statically in ../krecord.php on line 94
Strict Standards: Non-static method KRecord::set_str() should not be called statically in ../krecord.php on line 95
Thanks,
Thomas
actions_controller.php
require_once('../action.php');
class ActionsController {
public function ActionsController() {
Action::init();
}
public static function create($fields) {
$action = Action::new_record($fields);
return $action;
}
public function show($id) {
$action = Action::find_by($id);
return $action;
}
public function show_all($condition) {
$action = Action::find_all_by($condition);
return $action;
}
public function update($fields, $condition) {
$action = Action::update($fields, $condition);
return $action;
}
public function create_or_update($fields, $condition) {
// $condition will be: WHERE `day_id` = 123 AND `type` = "lunch"
$action = Action::find_by($condition);
if ( $action ) {
Action::update($fields, $condition);
} else {
// Remember to include all the necessary fields
Action::new_record($fields);
}
return $action;
}
public function destroy($condition) {
$action = Action::destroy($condition);
}
}
actions.php
<?php
require_once('../krecord.php');
class Action extends KRecord {
public static function init() {
KRecord::$tablename = 'mod_ets_actions';
KRecord::$fieldlist = array('id', 'employee_id', 'action', 'parameters', 'action_time');
}
}
krecord.php
<?php
class KRecord {
public static $tablename; // Name of the table
public static $fieldlist = array(); // The list of fields in the table (array)
public function KRecord() {
}
/* Cleans the fields passed into various functions.
If the field is not in list given in the model,
this method strips it out, leaving only the correct fields.
*/
private function sanitize_field_list($fields) {
$field_list = self::$fieldlist;
//print_r($field_list);
foreach ( $fields as $field => $field_value ) {
if ( !in_array($field, $field_list) ) {
//echo "<br/>$field is gone...<br/>";
unset($fields[$field]);
}
}
//print_r($fields);
return $fields;
}
// Setter for $tablename
public static function set_tablename($tname) {
self::$tablename = $tname;
}
// Turns the key-value pairs into a comma-separated string to use in the queries
private function set_str($clean_fields) {
$set_string = NULL;
foreach ( $clean_fields as $field => $field_val ) {
$set_string .= "`$field` = '$field_val', ";
}
$set_string = rtrim($set_string, ', ');
return $set_string;
}
// Assembles the condition string
private function query_str($type, $clean_fields) {
$fieldlist = self::$fieldlist;
$update_str = NULL;
$delim = NULL;
foreach ($clean_fields as $field => $field_val) {
if ( $type == 'where' ) {
if ( isset($fieldlist[$field]['pkey']) ) {
$delim = ' AND ';
$update_str .= "$field = '$field_val'$delim ";
}
} elseif ( $type == 'update' ) {
$delim = ', ';
$update_str .= "$field = '$field_val'$delim ";
}
}
$update_str = rtrim($update_str, $delim);
return $update_str;
}
// Inserts new record into the database
public function new_record($fields) {
$clean_fields = self::sanitize_field_list($fields);
//echo "<br/>".self::set_str($clean_fields)."<br/>";
$q = 'INSERT INTO ' . '`' . self::$tablename . '` SET ' . self::set_str($clean_fields) . ';';
//echo "<br/>$q<br/>";
$r = mysql_query($q) or die(mysql_error());
return;
}
// An experimental method. Do not use without testing heavily
public static function insert_unless_exists($fields, $condition) {
$clean_fields = self::sanitize_field_list($fields);
$q = 'INSERT INTO ' . '`' . self::$tablename . '` SET ' . self::set_str($clean_fields);
$q .= ' ON DUPLICATE KEY UPDATE ' . self::set_str($clean_fields);
$q .= ' WHERE ' . $condition . ';';
/* Don't use replace.. it deletes rows. do some sort of insert/update deal. */
//$q = 'REPLACE INTO ' . '`' . self::$tablename . '` SET ' . self::set_str($clean_fields);
//echo "<br/>$q<br/>";
$r = mysql_query($q) or die(mysql_error());
return;
}
// Updates a record in the data table
public static function update($fields, $condition) {
$clean_fields = self::sanitize_field_list($fields);
$q = 'UPDATE `' . self::$tablename . '` SET ' . self::set_str($clean_fields) . ' WHERE ' . $condition .';';
//echo "<br/>$q<br/>";
$r = mysql_query($q) or die(mysql_error());
return;
}
//Removes a record from the data table
public static function destroy($condition) {
$q = 'DELETE FROM ' . self::$tablename . ' WHERE ' . $condition .';';
$r = mysql_query($q);
return;
}
// Finds one record using the given condition
public static function find_by($condition) {
$q ='SELECT * FROM ' . '`' . self::$tablename . '`' . ' WHERE ' . $condition .';';
//echo "<br/>$q<br/>";
$r = mysql_query($q) or die(mysql_error());
$obj = mysql_fetch_object($r);
return $obj;
}
// Finds 1+ records in the table using the given conditions
public static function find_all_by($condition) {
if ( empty($condition) ) {
$where_str = null;
} else {
$where_str = ' WHERE ' . $condition;
}
$objs = array();
$q ='SELECT * FROM ' . '`' .self::$tablename . '`' . $where_str . ';';
//echo "<br/>$q<br/>";
$r = mysql_query($q) or die(mysql_error());
while ( $o = mysql_fetch_object($r) ) {
if ( $o->id != '' )
$objs[$o->id] = $o;
else
array_push($objs, $o);
}
return $objs;
}
}
?>

It's a notice, not really an error. You've got an interesting server setup if you're not able to disable strict notices....
Following this part of the notice: Non-static method KRecord::new_record() tells us that
in your class KRecord, the method new_record needs to be defined statically, such as:
public function new_record($fields) {
Simply need to be defined statically:
public static function new_record($fields) {
You indicate you've changed them to static, but your code in the question does not indicate that change.

Related

Fatal Error: Call to a member function addSnippet() on a non-object

I'm making a little PHP function that will show the avatar of all the administrators in my database. For some reason, I get the following error when I try to call the function $backend->addSnippet('login: show-admins');. Here is the PHP Class.
<?php
class zBackend {
private $adminCount;
final public function fetchAdminInfo() {
global $zip, $db, $tpl;
$query = $db->prepare('SELECT first_name, last_name FROM zip__admins');
$query->execute();
$result = $query->fetchAll();
$id = 1;
foreach($result as $row) {
$tpl->define('admin: first_name-' . $id, $row['first_name']);
$tpl->define('admin: last_name-' . $id, $row['last_name']);
$id++;
}
$this->adminCount = $id;
}
final public function addSnippet($z) {
global $tpl;
if(isset($z) && !empty($z)) {
$this->fetchAdminInfo();
switch($z) {
case 'login: show-admins':
$tpl->write('<ul id="users">');
$id = 0;
while($this->adminCount > $id) {
$tpl->write('<li data-name="{admin: first_name-' . $id + 1 . '} {admin: last_name-' . $id + 1 . '}">');
$tpl->write('<div class="av-overlay"></div><img src="{site: backend}/img/avatars/nick.jpg" class="av">');
$tpl->write('<span class="av-tooltip">{admin: first_name-' . $id + 1 . '} {admin: last_name-' . $id + 1 . '}</span>');
$tpl->write('</li>');
}
break;
}
} else {
return false;
}
}
}
?>
Here is where I set the function:
final public function __construct() {
global $zip, $core, $backend;
$this->Define('site: title', $zip['Site']['Title']);
$this->Define('site: location', $zip['Site']['Location']);
$this->Define('site: style', $zip['Site']['Location'] . '/_zip/_templates/_frontend/' . $zip['Template']['Frontend']);
$this->Define('site: backend', $zip['Site']['Location'] . '/_zip/_templates/_backend/' . $zip['Template']['Backend']);
$this->Define('social: email', $zip['Social']['Email']);
$this->Define('social: twitter', $zip['Social']['Twitter']);
$this->Define('social: youtube', $zip['Social']['Youtube']);
$this->Define('social: facebook', $zip['Social']['Facebook']);
$this->Define('snippet: show-admins', $backend->addSnippet('login: show-admins'));
}
And here is where I call the function:
<ul id="users">
{snippet: show-admins}
<br class="clear">
</ul>
Here is where I declare $backend
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');
define('D', DIRECTORY_SEPARATOR);
define('Z', '_zip' . D);
define('L', '_lib' . D);
define('C', '_class'. D);
require Z . 'config.php';
require Z . L . 'common.php';
try {
$db = new PDO($zip['Database']['Data']['Source']['Name'], $zip['Database']['Username'], $zip['Database']['Password']);
} catch(PDOException $e) {
die(zipError('ZipDB: Connection Failed', $e->getMessage()));
}
require Z . C . 'class.ztpl.php';
require Z . C . 'class.zcore.php';
require Z . C . 'class.zbackend.php';
require Z . C . 'class.zmail.php';
$tpl = new zTpl();
$backend = new zBackend();
$core = new zCore();
?>
It works just fine if I put the code into the file, but that limits what I can do. I want to be able to do it in a class and use functions to call it. Any ideas?
$backend isn't defined when your constructor fires. It's unclear from the code you've posted what class your __construct is constructing, but I'm guessing it's within zTpl. Consider moving your snippet definition call to a separate method, which you can call once all dependent objects have been constructed.
In class zTpl:
final public function __construct() {
global $zip; //note that we don't need $core or
//$backend, since they aren't yet defined
//Personally, I would pass the $zip array
//as a parameter to this constructor.
$this->Define('site: title', $zip['Site']['Title']);
//...
}
public function defineShowAdminsSnippet($backend) {
$this->Define('snippet: show-admins', $backend->addSnippet('login: show-admins'));
}
Where you define your objects:
$tpl = new zTpl();
$backend = new zBackend();
$core = new zCore();
//new:
$tpl->defineShowAdminsSnippet();
In my opinion, it is easier to avoid dependency problems like this if you eliminate use of the global keyword.

How to create a select list using PHP OOP

I've started recoding a PHP project into OOP. One thing I can't work out among many is how to make a dynamic select list. I have many lookup select lists to make. What's the best way to go about it?
I made a DatabaseObject class which has all my generic database queries in it. Do I add them here or make a special class for them, and how do I go about coding it?
require_once("database.php");
class DatabaseObject {
protected static $table_name;
// find all from a specific table
public static function find_all(){
global $database;
return static::find_by_sql("SELECT * FROM ".static::$table_name);
}
// select all from a specific table
public static function find_all_from($table){
global $database;
return static::find_by_sql("SELECT * FROM " .$table);
}
// find all from a specific table
public static function find_by_id($id){
global $database;
$result_array = static::find_by_sql("
SELECT * FROM ".static::$table_name. " WHERE id = '{$id}' LIMIT 1");
// return the data only for the one user
return !empty($result_array) ? array_shift($result_array) : false;
}
// find using sql
public static function find_by_sql($sql=""){
global $database;
// return all data from sql
$result_set = $database->query($sql);
$object_array = array();
while($row = $database->fetch_array($result_set)){
$object_array[] = static::instantiate($row);
}
return $object_array;
}
protected static function instantiate($record){
$class_name = get_called_class();
$object = new $class_name;
foreach($record as $attribute=>$value){
if($object->has_attribute($attribute)){
$object->$attribute = $value;
}
}
return $object;
}
protected function has_attribute($attribute){
$object_vars = $this->attributes();
// here we only want to know if the key exist
// so we will return true or false
return array_key_exists($attribute, $object_vars);
}
protected function attributes() {
$attributes = array();
foreach(static::$db_fields as $field) {
if(property_exists($this,$field)) {
$attributes[$field]= $this->$field;
}
}
return $attributes;
}
protected function sanitised_attributes() {
global $database;
$clean_attributes = array();
foreach($this->attributes() as $key => $value){
$clean_attributes[$key] = $database->escape_value($value);
}
return $clean_attributes;
}
public function save() {
// A new object won't have an id yet
return isset($this->id) ? $this->update() : $this->create();
}
// create new
protected function create() {
global $database;
$attributes =$this->sanitised_attributes();
$sql = "INSERT INTO ".static::$table_name." (";
$sql .= join(", " ,array_keys($attributes));
$sql .= ") VALUES ( '";
$sql .= join("', '" ,array_values($attributes));
$sql .= "')";
if($database->query($sql)) {
$this->id = $database->insert_id();
return true;
} else {
return false;
}
}
// update details
protected function update() {
global $database;
$attributes =$this->sanitised_attributes();
$attribute_pairs = array();
foreach($attributes as $key => $value) {
$attribute_pairs[] = "{$key}='{$value}'";
}
$sql = "UPDATE " .static::$table_name. " SET ";
$sql .= join(", ",$attribute_pairs);
$sql .= " WHERE id=". $database->escape_value($this->id);
$database->query($sql);
return ($database->affected_rows() ==1) ? true : false ;
}
public function delete() {
global $database;
$sql = "DELETE FROM ".static::$table_name;
$sql .= " WHERE id =". $database->escape_value($this->id);
$sql .= " LIMIT 1";
$database->query($sql);
return ($database->affected_rows() ==1) ? true : false ;
}
}
I would definitely model the select list as an object, since it has a well defined responsibility that can be encapsulated. I would go for keeping it as decoupled as possible from the DatabaseObject so that changes in any of those classes don't affect the other. As an example consider:
class SelectList
{
protected $options;
protected $name;
public function __construct($name, $options)
{
$this->options = $options;
$this->name = $name;
}
public function render()
{
$html = "<select name='" . $this->name . "'>\n";
foreach ($this->options as $option)
{
$html .= $option->render();
}
$html .= "</select>\n";
return $html;
}
}
class SelectListOption
{
protected $label;
protected $value;
protected $isSelected;
public function __construct($label, $value, $isSelected = false)
{
//Assign the properties
}
public function render()
{
$html .= '<option value="' . $this->value . '"';
if ($this->isSelected)
{
$html .= ' selected="selected" ';
}
$html .= '>' . $this->label . "</option>\n";
}
}
The one thing I like about modeling things this way is that adding new features (e.g. CSS styles for selected/unselected items, or the disabled attribute) is quite easy, since you know in which object that new feature belongs. Also, having this kind of "small" objects make it quite easy to write unit tests.
HTH
Just create a method which returns an HTML select/options view, by iterating over an associative array passed to the method...? Something like this maybe:
public static function viewSelect($name = "select", $arr_options = array()) {
$html = "<select name='$name'>\n";
foreach ($arr_options as $key => $val) {
$html .= "<option value='$key'>$val</option>\n";
}
$html .= "</select>\n";
return $html;
}
Then just pass the result from one of your database queries to this method. You could put this method into any appropriate class you want to.
You can also add selected option functionality
public static function viewSelect($name = "select", $arr_options =
array(), $selected) {
$selectedhtml = "";
$html = "<select name='$name'>\n";
foreach ($arr_options as $key => $val) {
if($key == $selected) $selectedhtml = "selected";
$html .= "<option value='$key' $selectedhtml>$val</option>\n";
}
$html .= "</select>\n";
return $html; }
public function get_posts()
{
$query="select * from tbl_posts";
$result= mysql_query($query);
$i=0;
while($data= mysql_fetch_assoc($result))
{
foreach($data as $key=>$value)
{
$info[$i][$key]=$value;
}
$i++;
}
return $info;
}

PHP Error when using variable variable to insert data into static variable

I'm not very good at this, so I'm sure this is a stupid question.
I have a class:
class debug {
private static $messages = array();
private static $errors = array();
private static $all = array(); // includes both of above
private static $types = array('messages','errors');
public static function add($type, $message) {
if(!in_array($type,self::$types) ) {
self::add('errors','Bad type "' . $type . '" specified when sending this message: ' . $message);
return false;
}
self::$$type[] = $message; // ERROR IS HERE (see below)
self::$all[] = $message; // no error
}
}
I'm calling this from another class in order to debug (Surprise).
debug::add('error', 'Error in ' . __FILE__ . ' on line ' . __LINE__);
PHP error message from error.log:
PHP Fatal error: Cannot use [] for reading in /var/www/lib/lib.php on line 1248
It refers to the above-specified line in the debug class.
EDIT:
What I am trying to do is use a variable variable (hence the posting title) to determine which static array to add data to.
I.e. if $type == 'messages', then $$type == $messages.
So I want self::$$type[] == self::$messages[]
Or if $type == 'errors', then $$type == $errors and self::$$type[] == self::$errors[]
Change the following line to. This ensures that $type is evaluated into 'message' or 'error' first.
self::${$type}[] = $message;
To expand on this, this is the code that I have. There seems to be additional syntax errors in your code that is causing the other failures, but this is why $$type[] is giving you that error.
class debug {
public static $messages = array();
public static $errors = array();
public static $all = array(); // includes both of above
private static $types = array('messages','errors');
public static function add($type, $message) {
self::${$type}[] = $message;
self::$all[] = $text;
}
}
debug::add('messages', "Regular Message");
debug::add('errors', "Error Message");
print_r(debug::$messages);
print_r(debug::$errors);
And this is the output that I get
Array
(
[0] => Regular Message
)
Array
(
[0] => Error Message
)
2 Errors
A. if(!in_array($type,self::$types) ) { not properly closed .. you used ) insted of } at the end
B. self::$all[] = $text; $text not defined anywhere in the script
Try
class Debug {
private static $errors = array ();
private static $types = array (
'messages',
'errors'
);
public static function add($type, $message) {
if (! in_array ( $type, self::$types )) {
return false;
}
self::$errors [$type][] = $message; // results in error (see below)
}
public static function get($type = null) {
if (! in_array ( $type, self::$types ) && $type !== null) {
return false;
}
return ($type === null) ? self::$errors : self::$errors [$type] ;
}
}
debug::add ( 'errors', 'Error in ' . __FILE__ . ' on line ' . __LINE__ );
debug::add ( 'messages', 'Error in ' . __FILE__ . ' on line ' . __LINE__ );
var_dump(debug::get());
var_dump(debug::get("messages"));

PHP - Calling function inside another class -> function

I'm trying to do this:
class database {
function editProvider($post)
{
$sql = "UPDATE tbl SET ";
foreach($post as $key => $val):
if($key != "providerId")
{
$val = formValidate($val);
$sqlE[] = "`$key`='$val'";
}
endforeach;
$sqlE = implode(",", $sqlE);
$where = ' WHERE `id` = \''.$post['id'].'\'';
$sql = $sql . $sqlE . $where;
$query = mysql_query($sql);
if($query){
return true;
}
}
//
}//end class
And then use this function * INSIDE of another class *:
function formValidate($string){
$string = trim($string);
$string = mysql_real_escape_string($string);
return $string;
}
//
.. on $val. Why doesn't this work? if I write in a field of the form, it's not escaping anything at all. How can that be?
* UPDATE *
handler.php:
if(isset($_GET['do'])){
if($_GET['do'] == "addLogin")
{
$addLogin = $db->addLogin($_POST);
}
if($_GET['do'] == "addProvider")
{
$addProvider = $db->addProvider($_POST);
}
if($_GET['do'] == "editProfile")
{
$editProfile = $db->editProfile($_POST);
}
if($_GET['do'] == "editProvider")
{
$editProvider = $db->editProvider($_POST);
}
}
//end if isset get do
** The editProvider function works fine except for this :-) **
You need to instantiate that validate class and than once instantiated you will need to call that function in that class with your value parameters.
Inside your editProvider you can have:
$validator = new validate();
$val = $validator->formValidate($val);
If the above doesn't work, try the following:
$val = mysql_real_escape_string(trim($val));
and see if it works, if it does it has to do with the correct function not being called.
Not sure why you are so bent on using $this vs a static implementation. IMO, a static call makes this code much easier. If you really want access to $this->formValidatString() from your database class, you will have to do class database extends MyOtherClass.
Here is how easy it would be to do a static call:
class database {
public function editProvider($post)
{
$sql = "UPDATE tbl SET ";
foreach($post as $key => $val):
if($key != "providerId")
{
$val = MyOtherClass::formValidate($val);
$sqlE[] = "`$key`='$val'";
}
endforeach;
$sqlE = implode(",", $sqlE);
$where = ' WHERE `id` = \''.$post['id'].'\'';
$sql = $sql . $sqlE . $where;
$query = mysql_query($sql);
if($query){
return true;
}
}
}//end class
class MyOtherClass
{
public static function formValidate($string) {
if (strlen($string) < 1) {
throw new Exception('Invalid $string ' . $string . ');
}
$string = trim($string);
$string = mysql_real_escape_string($string);
return $string;
}
}
You don't need to have an instance for this purpose. Just do validate::formValidate($val);.

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