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);.
Related
Thank you StackOverflow experts for looking at my question.
First, It is possible this question has been asked before but my situation is a bit unique. So, please hear me out.
When our users want to edit an existing record, they would also like to have the ability to delete an existing pdf file if one exists before adding a new one.
To display an existing file, I use this code.
<td class="td_input_form">
<?php
// if the BidIDFile is empty,
if(empty($result["BidIDFile"]))
{
//then show file upload field for Bid File
echo '<input type="file" name="BidIDFile[]" size="50">';
}
else
{
// Bid file already upload, show checkbox to delete it.
echo '<input type="checkbox" name="delete[]" value="'.$result["BidIDFile"].'"> (delete)
'.$result["BidIDFile"].'';
}
</td>
Then to delete this file, I use the following code:
// Connect to SQL Server database
include("connections/Connect.php");
// Connect to SQL Server database
include("connections/Connect.php");
$strsID = isset($_GET["Id"]) ? $_GET["Id"] : null;
if(isset($_POST['delete']))
{
// whilelisted table columns
$fileColumnsInTable = array( 'BidIDFile', 'TabSheet', 'SignInSheet', 'XConnect',
'Addend1', 'Addend2','Addend3','Addend4','Addend5', 'Addend6');
$fileColumns = array();
foreach ($_POST['delete'] as $fileColumn)
{
if(in_array($fileColumn, $fileColumnsInTable))
$fileColumns[] = $fileColumn;
}
// get the file paths for each file to be deleted
$stmts = "SELECT " . implode(', ', $fileColumns) . " FROM bids WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
$files = sqlsrv_fetch_array($querys,SQLSRV_FETCH_ROW);
// loop over the files returned by the query
foreach ($files as $file )
{
//delete file
unlink($file);
}
// now remove the values from the table
$stmts = "UPDATE bids SET " . impload(' = '', ', $fields) . " WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
This works fine. However, the edit file points to an existing file with an INSERT and UPDATE operation in this one file (great thanks to rasclatt) and I am having problem integrating the two together.
Can someone please help with integrating the two files into one?
Thanks in advance for your assistance.
Here is the INSERT and UPDATE file:
<?php
error_reporting(E_ALL);
class ProcessBid
{
public $data;
public $statement;
public $where_vals;
protected $keyname;
protected $conn;
public function __construct($conn = false)
{
$this->conn = $conn;
}
public function SaveData($request = array(),$skip = false,$keyname = 'post')
{
$this->keyname = $keyname;
$this->data[$this->keyname] = $this->FilterRequest($request,$skip);
return $this;
}
public function FilterRequest($request = array(), $skip = false)
{
// See how many post variables are being sent
if(count($request) > 0) {
// Loop through post
foreach($request as $key => $value) {
// Use the skip
if($skip == false || (is_array($skip) && !in_array($key,$skip))) {
// Create insert values
$vals['vals'][] = "'".ms_escape_string($value)."'";
// Create insert columns
$vals['cols'][] = "".str_replace("txt","",$key)."";
// For good measure, create an update string
$vals['update'][] = "".str_replace("txt","",$key)."".' = '."'".ms_escape_string($value)."'";
// For modern day binding, you can use this array
$vals['bind']['cols'][] = "".$key."";
$vals['bind']['cols_bind'][] = ":".$key;
$vals['bind']['vals'][":".$key] = $value;
$vals['bind']['update'][] = "".$key.' = :'.$key;
}
}
}
return (isset($vals))? $vals:false;
}
public function AddFiles($name = 'item')
{
// If the files array has been set
if(isset($_FILES[$name]['name']) && !empty($_FILES[$name]['name'])) {
// Remove empties
$_FILES[$name]['name'] = array_filter($_FILES[$name]['name']);
$_FILES[$name]['type'] = array_filter($_FILES[$name]['type']);
$_FILES[$name]['size'] = array_filter($_FILES[$name]['size']);
$_FILES[$name]['tmp_name'] = array_filter($_FILES[$name]['tmp_name']);
// we need to differentiate our type array names
$use_name = ($name == 'item')? 'Addend':$name;
// To start at Addendum1, create an $a value of 1
$a = 1;
if(!empty($_FILES[$name]['tmp_name'])) {
foreach($_FILES[$name]['name'] as $i => $value ) {
$file_name = ms_escape_string($_FILES[$name]['name'][$i]);
$file_size = $_FILES[$name]['size'][$i];
$file_tmp = $_FILES[$name]['tmp_name'][$i];
$file_type = $_FILES[$name]['type'][$i];
if(move_uploaded_file($_FILES[$name]['tmp_name'][$i], $this->target.$file_name)) {
// Format the key values for addendum
if($name == 'item')
$arr[$use_name.$a] = $file_name;
// Format the key values for others
else
$arr[$use_name] = $file_name;
$sql = $this->FilterRequest($arr);
// Auto increment the $a value
$a++;
}
}
}
}
if(isset($sql) && (isset($i) && $i == (count($_FILES[$name]['tmp_name'])-1)))
$this->data[$name] = $sql;
return $this;
}
public function SaveFolder($target = '../uploads/')
{
$this->target = $target;
// Makes the folder if not already made.
if(!is_dir($this->target))
mkdir($this->target,0755,true);
return $this;
}
public function where($array = array())
{
$this->where_vals = NULL;
if(is_array($array) && !empty($array)) {
foreach($array as $key => $value) {
$this->where_vals[] = $key." = '".ms_escape_string($value)."'";
}
}
return $this;
}
public function UpdateQuery()
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$update[] = implode(",",$arr['update']);
}
}
$vars = (isset($update) && is_array($update))? implode(",",$update):"";
// Check that both columns and values are set
$this->statement = (isset($update) && !empty($update))? "update bids set ".implode(",",$update):false;
if(isset($this->where_vals) && !empty($this->where_vals)) {
$this->statement .= " where ".implode(" and ",$this->where_vals);
}
return $this;
}
public function SelectQuery($select = "*",$table = 'bids')
{
$stmt = (is_array($select) && !empty($select))? implode(",",$select):$select;
$this->statement = "select ".$stmt." from ".$table;
return $this;
}
public function InsertQuery($table = 'bids')
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
$this->statement = "insert into ".$table;
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$insert['cols'][] = implode(",",$arr['cols']);
$insert['vals'][] = implode(",",$arr['vals']);
}
}
$this->statement .= '(';
$this->statement .= (isset($insert['cols']) && is_array($insert['cols']))? implode(",",$insert['cols']):"";
$this->statement .= ") VALUES (";
$this->statement .= (isset($insert['vals']) && is_array($insert['vals']))? implode(",",$insert['vals']):"";
$this->statement .= ")";
return $this;
}
}
include("../Connections/Connect.php");
function render_error($settings = array("title"=>"Failed","body"=>"Sorry, your submission failed. Please go back and fill out all required information."))
{ ?>
<h2><?php echo (isset($settings['title']))? $settings['title']:"Error"; ?></h2>
<p><?php echo (isset($settings['body']))? $settings['body']:"An unknown error occurred."; ?></p>
<?php
}
// this function is used to sanitize code against sql injection attack.
function ms_escape_string($data)
{
if(!isset($data) || empty($data))
return "";
if(is_numeric($data))
return $data;
$non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15
$non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31
$non_displayables[] = '/[\x00-\x08]/'; // 00-08
$non_displayables[] = '/\x0b/'; // 11
$non_displayables[] = '/\x0c/'; // 12
$non_displayables[] = '/[\x0e-\x1f]/'; // 14-31
foreach($non_displayables as $regex)
$data = preg_replace($regex,'',$data);
$data = str_replace("'","''",$data);
return $data;
}
// New bid save engine is required for both sql statement generations
$BidSet = new ProcessBid($conn);
$strId = null;
if(isset($_POST["Id"]))
{
$strId = $_POST["Id"];
//echo $strId;
}
If ($strId == "") {
//echo "This is an insert statement";
// This will generate an insert query
$insert = $BidSet->SaveData($_POST)
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->InsertQuery()
->statement;
// Check that statement is not empty
if($insert != false) {
sqlsrv_query($conn,$insert);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to Solicitation screen'));
$err = false;
}
//echo '<pre>';
//print_r($insert);
// echo '</pre>';
}
else
{
//echo "This is an update statement";
// This will generate an update query
$update = $BidSet->SaveData($_POST,array("Id"))
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->where(array("Id"=>$_POST["Id"]))
->UpdateQuery()
->statement;
//echo '<pre>';
//print_r($update);
//echo '</pre>';
// Check that statement is not empty
if($update != false) {
sqlsrv_query($conn,$update);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to admin screen'));
$err = false;
}
}
// This will post an error if the query fails
if((isset($err) && $err == true) || !isset($err))
render_error(); ?>
I'm sending information from an html form into a php page where I am checking the information against a mysql database.
Right now there are 5 checkboxes plus other variables in the form*(searchbar, radiobuttons, etc)*.
Is there a way to write the conditions without having to have a specific if statement for each path? Otherwise I have to write each specific path, and thats a lot of typing :/
Right now it would look something like:
if($orderBy == "price")
{
if($searchBy == "begin")
{
if($_POST["gameType"] == "RTS")
{
$sql = "select * from gametbl where gme_title like '$title%' and where gme_type = 'RTS' ORDER BY gme_price DESC";
}
}
and for all the conditions, thats going to take way to long. Is there a better way of doing this?
This is essentially what I mean by doing a method chain. You can specify within each method what to do if a specific variable is fed into it. It would dynamically write a statement based on single values. This a series of guesses based on your only bit of code:
<?php
class SQLBuilder
{
protected $order;
protected $sql;
public $statement;
public function Select($columns = false)
{
$this->sql[] = "select";
if(is_array($columns))
$this->sql[] = implode(",",$columns);
else
$this->sql[] = ($columns != false)? $columns:"*";
return $this;
}
public function Where($array = false,$like = false)
{
if($array == false)
return $this;
if(in_array("where", $this->sql))
$this->sql[] = "and";
$this->sql[] = "where";
if(is_array($array)) {
foreach($array as $key => $value)
$where[] = ($like != false)? "`$key` like '%".$value."$'":"`$key` = '".$value."'";
if(isset($where))
$this->sql[] = implode("and",$where);
}
else
$this->sql[] = $array;
return $this;
}
public function From($table = 'gametbl')
{
$this->sql[] = "from";
$this->sql[] = "`$table`";
return $this;
}
public function OrderBy($value = false,$order = false)
{
if($value != false) {
// I am guessing this is order
$heiarchy = ($order == 'begin')? " DESC":" ASC";
if($value == 'price')
$order = "`gme_price`".$heiarchy;
}
if(isset($order))
$this->sql[] = "order by ".$order;
return $this;
}
public function Fetch($return_obj = false)
{
$this->statement = implode(" ",$this->sql);
return ($return_obj != false)? $this:$this->statement;
}
}
// I don't know what your form fields are called, these are just for instances
$_POST['gameType'] = 'RTS';
$_POST['gameTitle'] = 'whatever game';
$_POST['orderBy'] = 'price';
$_POST['list'] = 'begin';
// Create instance of builder
$SQLBuilder = new SQLBuilder();
// This will just accumulate the statement based on fed-in variables.
$sql = $SQLBuilder->Select()
->From()
->Where(array("gme_title"=>$_POST['gameTitle']),true)
->Where(array("gme_type"=>$_POST['gameType']))
->OrderBy($_POST['orderBy'],$_POST['list'])
->Fetch();
echo $sql;
?>
GIVES YOU:
select * from `gametbl` where `gme_title` like '%whatever game$' and where `gme_type` = 'RTS' order by `gme_price` DESC
Here is my class :
class ProfileLink {
function profileLink(PDO $pdo, $string, $i=0)
{
if ($i!=0) {
$link = $string . '-' . $i;
} else {
$link = $string;
}
$req = $pdo->prepare('SELECT link FROM users WHERE link = ?');
$req->execute(array($link));
$nb = $req->rowCount();
$req->closeCursor();
if ($nb > 0) {
$i++;
return profileLink($pdo, $string, $i);
} else {
return $link;
}
}
}
When I call the profileLink function from the class, it doesn't work, but if I call it outside the class, everything is ok. It might be a problem with the PDO, what do you think ?
require_once ('lib/profileLink.class.php');
$profileLink = new ProfileLink();
$link = $profileLink->profileLink($pdo, $string);
I would store the instance of PDO as a class property so that it can be easily accessed within the class. Note that my example uses slightly different syntax (modern PHP).
class ProfileLink {
protected $pdo;
public function __construct(PDO $pdo) {
$this->pdo = $pdo;
}
public function profileLink($string, $i=0)
{
if ($i!=0) {
$link = $string . '-' . $i;
} else {
$link = $string;
}
$req = $this->pdo->prepare('SELECT link FROM users WHERE link = ?');
$req->execute(array($link));
$nb = $req->rowCount();
$req->closeCursor();
if ($nb > 0) {
$i++;
return profileLink($string, $i);
} else {
return $link;
}
}
}
$profileLink = new ProfileLink($pdo);
2 Things:
here
return profileLink($pdo, $string, $i);
you are missing a $this, because it's no regular function but a class method:
return $this->profileLink($pdo, $string, $i);
And second, your method has the same name as the class (except of the first capital letter), and thus seems to be interpreted as constructor. I have just tested this:
class Test {
function test() {
echo "test";
}
}
$t = new Test();
And it outputs "test".
So you should rename your method to getLink or something similar.
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;
}
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;
}
}