I do have a search form on a page which search records from a table in my database. I want to show how many results each query gives us. All this is written in codeigniter.
All my code on that page:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index() {
$data['title'] = "Welcome | randomsite";
$data['html'] = "";
if($this->input->post()) {
$uq = $this->security->xss_clean($this->input->post('query'));
if(trim($uq) != "") {
$searchBy = $this->security->xss_clean($this->input->post('searchBy'));
$searchByJSON = json_encode(array(1 => "Email", 2 => "Username", 3 => "IP", 4 => "FullName", 5 => "Phone"), JSON_FORCE_OBJECT);
if(isset(json_decode($searchByJSON)->$searchBy)) {
$start = microtime(true);
$this->db->from('Databases');
$rs = $this->db->get()->result();
$end = microtime(true);
$data['html'] .= "Search completed in: " . ($end - $start) . " seconds.<p></p>";
foreach($rs as $row) {
$this->db->distinct();
$this->db->select('Username, Password, Email, FullName, IP, Phone, salt');
$this->db->from('Accounts');
$this->db->where(json_decode($searchByJSON)->$searchBy, $uq);
$this->db->where('DatabaseID', $row->ID);
$query = $this->db->get();
if($query->num_rows() > 0) {
if($searchBy == 5 && $query->row()->Phone == 0) {
break;
}
$resultsHTML = "";
foreach($query->result() as $qr) {
$resultsHTML .= "<div class='card-block-results' style='table-layout:fixed; word-wrap:break-word;'><table class='table table-hover' style='font-size:13px;'>";
foreach($qr as $key => $value) {
if(!empty($value)) {
if($key == "FullName") {
$key = "Full Name";
}
$resultsHTML .= "<tr><td>" . $key . ": " . $value . "</td></tr>";
}
}
$resultsHTML .= "</table></div>";
}
$data['html'] .= $row->Website . " has: <b style='color:lime;'>" . $query->num_rows() . "</b> result(s) found. This data was hacked on approximately " . $row->Date . ". <button class='btn btn-success btn-sm' style='margin-bottom:5px;' id='button" . $row->ID . "'>view results</button><div id='results" . $row->ID . "' style='display:none;'><div class='card card-outline-primary' style='margin-bottom:10px;text-align:left;margin-top:5px;'><div class='card-header card-primary'>Results</div>" . $resultsHTML . "</div></div><script type='text/javascript'>$('#button" . $row->ID . "').click(function() { $(this).hide(); $('#results" . $row->ID . "').show(); });</script><br>";
}
}
if($data['html'] == "Search completed in: " . ($end - $start) . " seconds.<p></p>") {
$data['html'] .= "No results found!<p></p>Are you searching in the right fields? Searching for an email in the phone number field will not work.<br>Make sure first and last names are correct. Example: Mike Tyson";
}
$data['html'] .= "<br><br><br>";
$this->db->from('Lookups');
$query = $this->db->get();
$new_lookup = $query->row()->Number + 1;
$qdata = array(
"Number" => $new_lookup
);
$this->db->update('Lookups', $qdata);
}
} else {
$data['html'] = '<div class="alert alert-danger">×Please enter something in your query before searching!</div>';
}
}
$this->load->view('welcome', $data);
}
}
So how can I add that into every time someone is searching? Like 'Query had x results.'
Like this:
I searched on many different sites about this but I couldn't find anything for my specific question.
you have already used it in your code,
$query->num_rows()
will give you the number of rows u get from the query.
i think this is abusing a framework like CI - i give you some insights in to this framework - if you are willing to learn, study this piece of code because
you nearly don't use any of his built in functionality
in my opinion you've to restructure your code to such an extent that you don't even recognize your previous attempt ;)
i'll try to give you a hunch - but in order to understand - you've to work with this code
put in your models folder the following models
Database Model
class Database_model extends CI_Model
{
private $objCollection;
public function __construct()
{
$this->objCollection = new Database_Collection();
}
public function getCollection()
{
$this->benchmark->mark('code_start');
$this->db->from('Databases');
$this->objCollection->append($this->db->get()->result());
$this->benchmark->mark('code_end');
$this->objCollection->queryTime = $this->benchmark->elapsed_time('code_start', 'code_end');
return $this->objCollection;
}
}
class Database_Collection extends ArrayObject
{
public $queryTime = 0;
}
Accounts Model
class Accounts_model extends CI_Model
{
private $objCollection;
public function __construct()
{
$this->objCollection = new Accounts_Collection();
}
public function getCollection()
{
$this->benchmark->mark('code_start');
$this->db
->distinct()
->select('Username, Password, Email, FullName, IP, Phone, salt')
->from('Accounts');
$this->objCollection->append($this->db->get()->result());
$this->benchmark->mark('code_end');
$this->objCollection->queryTime = $this->benchmark->elapsed_time('code_start', 'code_end');
return $this->objCollection;
}
}
class Accounts_Collection extends ArrayObject
{
public $queryTime = 0;
}
Search Model
class Search_model extends CI_Model
{
private $strSearchQuery = "";
public function getSearchObject()
{
if ($this->isValidSearch())
{
$this->load->model("Database_Model");
$this->load->model("Accounts_Model");
$objSearch = new Search;
$objDBCollection = $this->Database_Model->getCollection();
foreach($objDBCollection AS $objItem)
{
$this->db
->where("DatabaseID", $objItem->ID)
->where($this->input->post("searchBy"), $this->strSearchQuery);
$objItem->collection = $this->Accounts_Model->getCollection();
}
$objSearch->addResultCollection($objDBCollection);
return $objSearch;
}
return false;
}
public function isValidSearch()
{
$strSearchQuery = $this->security->xss_clean($this->input->post('query'));
$this->strSearchQuery = trim($strSearchQuery);
if (empty($this->strSearchQuery)) return false;
$arrValidSearchCriteria = array("Email", "Username", "IP", "FullName", "Phone");
return (in_array($this->input->post("searchBy"),arrValidSearchCriteria));
}
}
class Search
{
public $queryTime = 0;
private $objCollection;
public function addResultCollection(Database_Collection $objCollection)
{
$this->objCollection = $objCollection;
}
public function getRenderedTime()
{
if ($this->queryTime == 0)
{
$this->queryTime += $this->objCollection->queryTime;
foreach($this->objCollection AS $objItem)
{
if (isset($objItem->collection)
{
$this->queryTime += $objItem->collection->queryTime;
}
}
}
return $this->queryTime;
}
public function getCountSearchResults()
{
if (!$this->countSearchResults)
{
$this->countSearchResults = 0;
foreach($this->objCollection AS $objItem)
{
if (isset($objItem->collection)
{
$this->countSearchResults += $objItem->collection->count();
}
}
}
return $this->countSearchResults;
}
}
your controller
class Welcome extends CI_Controller
{
public function index()
{
$this->load->model("Search_model");
$data['title'] = "Welcome | randomsite";
if ($this->Search_model->isValidSearch()
{
$objSearch = $this->Search_model->getSearchObject();
$arrViewData = array("objSearch" => $objSearch);
$this->load->view("list-search", $arrViewData);
}
}
}
pS: maybe there are some typos because i just wrote it down
Related
Hello I am trying to build my first restful web service and im using the instruction from lorna jane mitchell blog.
If the req comes through this Url : http://localhost:8888/lorna/index.php/tree/getpath?node_id=75
i call the function getpath passing node_id
The function get path looks like this :
class NestedSet
{
public function getPath($id) {
$sql = "SELECT p." . $this->pk . ", p." . $this->name . " FROM ". $this->table . " n, " . $this->table . " p WHERE n.lft BETWEEN p.lft AND p.rgt AND n." . $this->pk ." = " . $id . " ORDER BY p.lft;";
$result = $this->db->query($sql);
if ($result->num_rows == 0) {
return $this->error(1, true);
}
$path = array();
$i = 0;
while ($row = $result->fetch_assoc()) {
$path[$i] = $row;
$i++;
}
return $path;
}
}
Now i want to pass this variable $path to the class JsonView that looks like this :
class JsonView extends ApiView {
public function render($path) {
header('Content-Type: application/json; charset=utf8');
echo json_encode($path);
return true;
}
}
class ApiView {
protected function addCount($data) {
if(!empty($data)) {
// do nothing, this is added earlier
} else {
$data['meta']['count'] = 0;
}
return $data;
}
}
Any Idea on how can I pass the variable $path or any other variable through this JsonView Class.
Thank you very much for your time :)
UPDATE This is the code for creating the nested class object
public function getAction($request) {
$data = $request->parameters;
if(isset($request->url_elements[2])) {
switch ($request->url_elements[2]) {
case 'getpath':
$id = $data['node_id'];
$nested = new NestedSet();
$nested->getPath($id);
$api = new JsonView();
$api->render($path);
break;
default:
# code...
break;
}
} else {
$nested = new NestedSet();
echo $nested->treeAsHtml();
}
}
Just create object of JsonView and then call the function render using that object.
$api = new JsonView;
$api->render($path);
I have three functions that returns all parents for specific child with user_id with recursive query.
All these functions works good ..but the problem begins when I start use foreach loop to return multiple user parent names in function
merge_comments_data..
note : t_relation means = parent_id
class News extends front_end {
public $parents_names;
function merge_comments_data($related_comments) {
foreach ($related_comments as $comment) {
$full_name = $this->get_parents_names($comment['cn_visitor_id']);
}
echo "<pre>";
print_r($names);
echo "</pre>";
exit;
}
//// all these function to get full parent names by user id
function get_parents_names($user_id = 0) {
$this->user_parent_name($user_id);
echo $this->parents_names;
}
function user_parent_name($user_id = 0) {
// clear the variable at first
$result = $this->get_parents($user_id);
if (is_object($result)) {
$this->parents_names .= ' ' . $result->t_name . ' ';
if ($result->t_relation != 0) {
$this->user_parent_name($result->t_relation);
}
}
}
public function get_parents($user_id = 0) {
$result = $this->db->query("SELECT * FROM d_tree where t_id = '$user_id'");
if (is_object($result->row())) {
$result = $result->row();
} else {
$result = '';
}
return $result;
}
i am trying to create a readmore function in codeigniter where the readmore link will be linked to a controller which would show all the data about that particular id....i am kind of confused on how to go about it... i tried...
<?php
$research_detail_url = site_url()."/research/research_details";
//echo json_encode($research)
if($research)
{
foreach ($research as $_research) {
$author = $_research->author;
$content = $_research->content;
$dsubmitted = $_research->dsubmitted;
echo "<div class='menu-collapse'> <h5>$author</h5>";
echo "<p>";
echo "<span class='support_text'>$content <span><br />";
echo "<span class='support_text'>$dsubmitted <span><br />";
echo "<a href='$research_detail_url' target='_blank' style='text-decoration:underline; color:#0088cc;'>
read more » </a>";
echo "</p> </div>";
}
}
?>
but i seem not be getting any results...i need help...
and this is my controller function.....
public function research_details($id='')
{
if(!$id)
{
echo "Project Id required";
return;
}
$_result = $this->projects_model->get_project($id);
if($_result)
{// success in fetching data hurray
$result['projects'] = $_result;
$users_ids = $this->users_model->get_user_ids(); //return available user id's
$groups_ids = $this->groups_model->get_group_ids(); //return available group id's
//echo json_encode($users_ids);
//echo json_encode($groups_ids);
$group_record = $this->map_names_to_ids($users_ids , $groups_ids );
$result['group_record'] = $group_record;
//load the view
$this->load->view('__includes__/header');
$this->load->view('__includes__/boostrap_responsive');
$this->load->view('projects/project_panel', $result);
$this->load->view('__includes__/footer_scripts');
$this->load->view('__includes__/wijmo_file_jquery');
$this->load->view('__includes__/footer');
}
else
{
exit("An Error occured in fetching the requested project");
}
}
and this is my model.....
<?php
class research_model extends CI_Model {
function add()
{
$this->db->insert('research',$_POST);
if($this->db->_error_number())
{
return $this->db->_error_number();
}
}
function update($article_id, $data_fields = NULL){
if($data_fields == NULL)
{
$this->db->where("article_id =".$article_id);
$this->db->update('research',$_POST);
}
else
{
$this->db->where("article_id =".$article_id);
$this->db->update('research',$data_fields);
}
$is_error = $this->db->_error_number();
if($is_error){
echo $is_error;
}
return TRUE;
}
function delete($id){
$this->db->where("article_id =".$id);
return $this->db->delete('research');
}
//return the research with this id
function get_research($id){
$this->db->where("article_id =".$id);
$query = $this->db->get('research');
if ($query->num_rows() > 0){
return $query->row_array();
}
else
echo $this->db->_error_message();
return FALSE;
}
//return the available research in the table
function get_research_all(){
$query = $this->db->get('research');
if ($query->num_rows() > 0)
{
foreach($query->result() as $row)
{
$result[] = $row;
}
return $result;
}
}
}
and my entire controller.....
<?php
class Research extends Public_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('research_model');
}
function index()
{
if($this->ion_auth->is_admin())
{
$result = $this->research_model->get_research_all();
$data = array(
'main_content' => 'research/index',
'research' => $result
);
$this->load->view("loader", $data);
}
else
{
redirect('home');
}
}//END INDEX
// public view
function current()
{
$result = $this->research_model->get_research_all();
$data = array('research' => $result);
$this->load->view('__includes__/header');
$this->load->view('__includes__/navbar');
$this->load->view('research/current', $data);
$this->load->view('__includes__/footer');
}
function add()
{
if($this->ion_auth->is_admin())
{
$this->load->view("loader",array('main_content'=>"research/add_research"));
}
}//END ADD
function edit($id='')
{
if(! $id)
{
echo "research Id required";
return;
}
$result = $this->research_model->get_research($id);
if( ! $result)
{
echo "Nothing to edit";
return;
}
$result['main_content'] = "research/add_research";
$this->load->view("loader",$result);
}//END EDIT
function delete($id='')
{
if(! $id)
{
echo "Id required";
return;
}
$this->research_model->delete($id);
$this->get_research();
}//END DELETE
function submit($id='')
{
//validate form [perform validation server-side to make sure of fields]
$this->load->library('form_validation');
$this->form_validation->set_rules('author', 'Author', 'trim|required|min_length[4]');
if ($this->form_validation->run() == FALSE){
//ajax data array
$data = array(
'server_validation' => validation_errors()
);
echo str_replace('\\/', '/', json_encode($data));
}
else{
if($id){
$result = $this->research_model->update($id);
$content = "article has been UPDATED successfully";
//$retArr["content"] = $content;
//echo json_encode($retArr);
}
else{
$result = $this->research_model->add();
$content = "article has been CREATED successfully";
//$retArr["content"] = $content;
//echo json_encode($retArr);
}
//if duplicate key
if($result == 1062){
//ajax data array
$data = array();
$data['is_valid'] = 0;
echo json_encode($data);
}else{
//ajax data array
$data = array(
'is_valid' => 1,
'content' => $content
);
echo json_encode($data);
}
}//end ELSE form valid
}//END SUBMIT
public function research_details($id='')
{
if(!$id)
{
echo "Project Id required";
return;
}
$_result = $this->research_model->get_research($id);
if($_result)
{// success in fetching data hurray
$result['article'] = $_result;
//load the view
$this->load->view('__includes__/header');
$this->load->view('__includes__/boostrap_responsive');
$this->load->view('research/research_details', $Aresult);
$this->load->view('__includes__/footer_scripts');
$this->load->view('__includes__/wijmo_file_jquery');
$this->load->view('__includes__/footer');
}
else
{
exit("An Error occured in fetching the requested project");
}
}//END EDIT
}
?>
my public controller
<?php
abstract class Public_Controller extends CI_Controller
{
public $about_data;
function __construct()
{
parent::__construct();
//Making This variable availale for the whole site
$this->load->model('about_model');
$this->load->model('captcha_model');
//get your data
$this->about_data = $this->about_model->get_abouts();
}
}
?>
I see a couple of problems:
In your view, you are not closing the span tags. You need
</span>
In your view, you are creating the link, but you are not
including an ID, which you need in your controller. What I mean by this is the following:
First,you create this $research_detail_url = site_url()."/research/research_details";.
Then echo "<a href='$research_detail_url' target='_blank' style=''>read more</a>";
As you can see, your URL does not have an ID when created. What you should do is something like this: $research_detail_url = site_url()."/research/research_details/31"; where 31 is a random ID. You need to come up with the right ID needed in order to pass it to your controller. Your controller is currently assigning a blank ID since none is being passed which is why you end up with a result of "Project Id required"
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;
}
}