How to create a select list using PHP OOP - php

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;
}

Related

PHP illegal offset type error

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

Insert data from session array to prestashop database using php

Im working on a custom prestashop module that retrieves data from another database(an external database) and then it inserts the data to the prestashop data base. I've made a php file that retrieves data from the external database and saves to a session variable.
I've got this array from that php file:
[0] => Array
(
[0] => 1
[productid] => 1
[1] => 0
[parent] => 0
[2] => 0
[3] => iPod Shuffle
[prodname] => iPod Shuffle
And this is the its code: `FILE) . "/settings.inc.php");
//database 1
//$data = array();
$conn = #mysql_connect($GLOBALS['VCS_CFG']["dbServer"],$GLOBALS['VCS_CFG']["dbUser"], $GLOBALS['VCS_CFG']["dbPass"]);
if ($conn){
if (mysql_select_db($GLOBALS['VCS_CFG']["dbDatabase"])) {
$SQL = "SELECT * FROM vc_products";
$q = mysql_query($SQL);
while($row = mysql_fetch_array($q))
{
$json_output[] = $row;
$_SESSION['myData'] = $json_output;
}
//echo json_encode($json_output);
print_r($_SESSION['myData']);
}
mysql_close($conn);
}
`
im trying to insert the row prodname at the product_name row of the table ps_order_detail table. Now im making the prestashop module that it will insert that data to Prestashop database. Here is my code:
This is my module's code for the data insert:
<?php
if (!defined('_PS_VERSION_'))
exit;
include 'test.php';
class PrestaBridge extends Module
{
public function __construct()
{
$this->name = 'PrestaBridge';
$this->tab = 'Front';
$this->version = 1.5;
$this->author = 'Sergio Kagiema';
$this->need_instance = 0;
parent::__construct();
$this->displayName = $this->l('PrestaBridge');
$this->description = $this->l('A module for transferring data from Vcart to Prestashop!');
$this->confirmUninstall = $this->l('Are you sure you want to uninstall?');
if (!Configuration::get('PrestaBridge'))
$this->warning = $this->l('No name provided');
}
//INSTALL TOY MODULE
public function install()
{
$parent_tab = new Tab();
foreach (Language::getLanguages(true) as $lang)
$parent_tab->name [$lang['id_lang']] = 'PrestaBridge';
$parent_tab->class_name = 'BridgePage';
$parent_tab->id_parent = 0;
$parent_tab->module = $this->name;
$parent_tab->add();
if (!parent::install()
|| !$this->installModuleTab('BridgePage', array((int)(Configuration::get('PS_LANG_DEFAULT'))=>'PrestaBridge'), $parent_tab->id)
)
return false;
return true;
}
//UNISTALL TOY MODULE
public function uninstall()
{
if (!parent::uninstall()
|| !$this->uninstallModuleTab('BridgePage')
)
return false;
return true;
}
private function installModuleTab($tabClass, $tabName, $idTabParent)
{
$idTab = Tab::getIdFromClassName($idTabParent);
$idTab = $idTabParent;
$pass = true ;
#copy(_PS_MODULE_DIR_.$this->name.'/logo.gif', _PS_IMG_DIR_.'t/'.$tabClass.'.gif');
$tab = new Tab();
$tab->name = $tabName;
$tab->class_name = $tabClass;
$tab->module = $this->name;
$tab->id_parent = $idTab;
$pass = $tab->save();
return($pass);
}
private function uninstallModuleTab($tabClass)
{
$pass = true ;
#unlink(_PS_IMG_DIR_.'t/'.$tabClass.'.gif');
$idTab = Tab::getIdFromClassName($tabClass);
if($idTab != 0)
{
$tab = new Tab($idTab);
$pass = $tab->delete();
}
return($pass);
}
public function getContent() {
$this->_html = '<h2>'.$this->displayName.'</h2>';
if (Tools::isSubmit('submit')) {
$sql = 'INSERT INTO '._DB_PREFIX_.'order_detail(product_id, product_name) VALUES';
$valuesArr = array();
if ($data = Db::getInstance()->Execute($sql))
foreach ($data as $row){
$product_id = (int) $row['productid'];
$product_name = $row['prodname'];
$valuesArr[] = "('$product_id', '$product_name')";
}
$sql .= implode(',', $valuesArr);
$this->_displayForm();
return $this->_html;
}
}
private function _displayForm() {
$this->_html .= '<div class="clear"></div>';
$this->_html .= '<div class="bridge" id="bridge">';
$this->_html .= '<form method="post" action="'.$_SERVER['REQUEST_URI'].'" id="test">';
$this->_html .= '<input type="text" name="username" id="username"/>';
$this->_html .= '<input type="text" name="password" id="password"/>';
$this->_html .= '<button id="myButton" onclick="myfunc()" type="submit">Transfer Data</button>';
$this->_html .= '</div>';
}
}
?>
Can you help me out please?
You should start with this http://doc.prestashop.com/display/PS15/DB+class+best+practices
Tells you everything you need to know about best practices. Anyways let's say you are creating a module. It means you are extending a Module class and your module starts like this
class yourCustomeModuleName extends Module
{
}
Between those tags you insert all the relevant data like public __construct function and all the other functions you need, including the hook functions that you want to display your data.
To insert something in to database through Prestashop you need to use execute() command what is a global variable in Prestashop. Here is a example from the link that I provided you with
$sql = 'DELETE FROM '._DB_PREFIX_.'product WHERE active = 0';
if (!Db::getInstance()->execute($sql))
die('Error etc.)';
So that means - you don't need to execute database connections when you are already inside of a class. If this is new to you then I suggest you to read about OOP (object oriented programming)

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;
}
}

MYSQL file size not showing

I'm learning how to build a photo_gallery using a PHP video book/tutorial. I was able to upload a photo, but in the MySQL database, it's not registering a size of the photo. It just says 0 (see image)
The instructor's Mysql gives the size of the file.
Any idea why the file size wouldn't show up in SQL?
UPDATE... This is the photograph class.
<?php
require_once(LIB_PATH.DS.'database.php');
class Photograph extends DatabaseObject {
protected static $table_name="photographs";
protected static $db_fields=array('id', 'filename', 'type', 'caption');
public $id;
public $filename;
public $type;
public $size;
public $caption;
private $temp_path;
protected $upload_dir="images";
public $errors=array();
protected $upload_errors = array(
UPLOAD_ERR_OK => "No errors.",
UPLOAD_ERR_INI_SIZE => "Larger than upload_max_filesize.",
UPLOAD_ERR_FORM_SIZE => "Larger than form MAX_FILE_SIZE.",
UPLOAD_ERR_PARTIAL => "Partial upload.",
UPLOAD_ERR_NO_FILE => "No file.",
UPLOAD_ERR_NO_TMP_DIR => "No temporary directory.",
UPLOAD_ERR_CANT_WRITE => "Can't write to disk.",
UPLOAD_ERR_EXTENSION => "File upload stopped by extension."
);
// Pass in $_FILE(['uploaded_file']) as an argument
public function attach_file($file) {
//perform error checking on the form parameters
if(!file || empty($file) || !is_array($file)){
//error: nothing uploaded or wrong usage
$this->errors[] = "No file was uploaded.";
return false;
} elseif($file['error'] !=0) {
//error: report what PHP says went wrong
$this->errors[] = $this->upload_errors[$file['error']];
return false;
} else {
//set object attributes to the form parameters.
$this->temp_path = $file['tmp_name'];
$this->filename = basename($file['name']);
$this->type = $file['type'];
$this->size = $file['size'];
//don't worry about saving anything to the database yet
return true;
}
}
public function save() {
// a new record won't have an id yet.
if(isset($this->id)) {
//really just to update the caption
$this->update();
} else {
//make sure there are no errors
//Can't save if there are pre-existing errors
if(!empty($this->errors)) {return false; }
//make sure the caption is not too long for the DB
if(strlen($this->caption) > 255) {
$this->error[] = "The caption can only be 255 characters long.";
return false;
}
//Can't save without filename and temp location
if(empty($this->filename) || empty($this->temp_path)){
$this->errors[] = "The file location was not available.";
return false;
}
//Determine the target_path
$target_path = SITE_ROOT .DS. 'public' .DS. $this->upload_dir .DS. $this->filename;
//Make sure a file doesn't already exist
if(file_exists($target_path)) {
$this->errors[] = "The file {$this->filename} already exists.";
return false;
}
//attempt to move the file
if(move_uploaded_file($this->temp_path, $target_path)) {
//success
//save a corresponding entry to the database
if($this->create()) {
//we are done with temp_path, the file isn't there anymore
unset($this->temp_path);
return true;
}
} else {
//failure
$this->errors[] = "The file upload failed, possibly due to incorrect permissions
on the upload folder.";
return false;
}
}
}
//common database methods
public static function find_all(){
return self::find_by_sql("SELECT * FROM ".self::$table_name);
}
public static function find_by_id($id=0) {
global $database;
$result_array = self::find_by_sql("SELECT * FROM ".self::$table_name." WHERE id={$id} LIMIT 1");
return !empty($result_array) ? array_shift($result_array) : false;
}
public static function find_by_sql($sql=""){
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_array($result_set)) {
$object_array[] = self::instantiate($row);
}
return $object_array;
}
private static function instantiate($record){
$object = new self;
//$object->id = $record['id'];
//$object->username = $record['username'];
//$object->password = $record['password'];
//$object->first_name = $record['first_name'];
//$object->last_name = $record['last_name'];
foreach($record as $attribute=>$value) {
if($object->has_attribute($attribute)) {
$object->$attribute = $value;
}
}
return $object;
}
private function has_attribute($attribute) {
$object_vars = $this->attributes();
return array_key_exists($attribute, $object_vars);
}
protected function attributes() {
//return an array of attribute keys and their values
$attributes = array();
foreach(self::$db_fields as $field) {
if(property_exists($this, $field)) {
$attributes[$field] = $this->$field;
}
}
return $attributes;
}
protected function sanitized_attributes() {
global $database;
$clean_attributes = array();
//sanitize the values before submitting
//Note: does not alter the actual value of each attribute
foreach($this->attributes() as $key=> $value) {
$clean_attributes[$key] = $database->escape_value($value);
}
return $clean_attributes;
}
//replaced with a custom save()
//public function save() {
//return isset($this->id) ? $this->update() : $this->create();
//}
public function create() {
global $database;
$attributes = $this->sanitized_attributes();
$sql = "INSERT INTO ".self::$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;
}
}
public function update() {
global $database;
$attributes = $this->sanitized_attributes();
$attribute_pairs = array();
foreach($attributes as $key => $value) {
$attribute_pairs[] = "{$key}='{$value}'";
}
$sql = "UPDATE ".self::$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 ".self::$table_name." ";
$sql .= "WHERE id=". $database->escape_value($this->id);
$sql .= " LIMIT 1";
$database->query($sql);
return($database->affected_rows() == 1) ? true : false;
}
}
?>
I think you forget to put size in your $db_fields
protected static $db_fields=array('id', 'filename', 'type', 'size', 'caption');
if you look at your attributes() function it checks to see if property_exists within the $db_fields and then assign the value to $attributes array and since 'size' was not within the array that you are checking against, it basically gets filtered out is what i am guessing:
protected function attributes() {
//return an array of attribute keys and their values
$attributes = array();
foreach(self::$db_fields as $field) {
if(property_exists($this, $field)) {
$attributes[$field] = $this->$field;
}
}
return $attributes;
}

Categories