Unique Case of "Call to a member function set_type() on null" - debugging

Hello guys i have gone through all 25 questions relating to the title of my question and i am made to believe my scenario is totally different.
Here is the error
Fatal error: Uncaught Error: Call to a member function set_type() on null in /path_to_file/login.php:55 Stack trace: #0 /path_to_call_page/login.php(24): login->authenticate() #1 {main} thrown in /path_to_file/login.php on line 55
Here is my code
<?php
class login
{
public $username;
public $password;
public $err;
public $table_name;
public $session_data;
public $md5 = true;
public $username_column = "username";
public $password_column = "password";
public $builder;
function _construct($username,$password)
{
$this->username = $username;
$this->password = $password;
$this->builder = new queryBuilder();
}
function set_table($tablename)
{
$this->table_name = $tablename;
}
/*
* Tells the login class where to find the username and password in database table
*/
function set_columns($username_col,$password_col)
{
$this->username_column = $username_col;
$this->password_column = $password_col;
}
function md5_on()
{
$this->md5 = true;
}
function md5_off()
{
$this->md5 = false;
}
function authenticate()
{
$db = new mySQLConnection();
$db->select();
// if md5 is turned on
if($this->md5)
$this->password = md5($this->password);
$this->builder->set_type("SELECT");
$this->builder->set_table_name($this->table_name);
$this->builder->set_where("WHERE $this->username_column = '$this->username' and $this->password_column = '$this->password'");
$query = $this->builder->build_query();
if($db->execute_query($query))
$data = $db->fetch($db->result);
else
{
die($db->error);
}
if($db->rows_affected() == 1)
{
$this->session_data = $data[0];
return true;
}
else
{
$this->err = "Invalid username or password. Please try again";
return false;
}
}
function get_error()
{
return $this->err;
}
}
?>
The error occurs everywhere i have
$this->builder
And i have defined it in the _construct method.
This is the queryBuilder class
class queryBuilder
{
var $data;
var $field;
var $tableName;
var $databaseName;
var $where;
var $order;
var $group;
var $limit;
var $queryString;
var $error;
private function put_quotes1($field)
{
$field = trim($field);
$field = "`".$field."`";
return $field;
}
private function put_quotes2($field)
{
$field = trim($field);
$field = "'".$field."'";
return $field;
}
function set_type($type)
{
$this->type = $type;
}
function set_data($data)
{
$this->data = $data;
}
function set_field($field = null)
{
$this->field = $field;
}
function set_where($where)
{
$this->where = $where;
}
function set_limit($limit)
{
$this->limit = $limit;
}
function set_order($order)
{
$this->order = $order;
}
function set_table_name($name)
{
$this->tableName = $name;
}
function prepare_data($data)
{
if(is_array($data))
{
foreach($data as $k => $v)
{
$this->field[] = $k; //setting the column names
$this->data[] = $v; // setting the values
}
}
}
function build_query()
{
switch($this->type)
{
case 'SHOW':
$database_name = $this->put_quotes1($this->databaseName);
$this->queryString = "SHOW ";
if(!isset($this->field) || is_null($this->field))
$this->queryString .= "DATABASES LIKE 'thirdeye%'; ";
else{
$noFields = count($this->field); //no of fields in table
for($i = 0; $i < $noFields; $i++)
{
if($i == ($noFields- 1)) // if on the last field
$this->queryString .= $this->put_quotes1($this->field[$i]).' ';
else
$this->queryString .= $this->put_quotes1($this->field[$i]).',';
}
}
break;
case 'INSERT':
$table_name = $this->put_quotes1($this->tableName);
$this->queryString = "INSERT INTO ".$table_name." (";
$noFields = count($this->field);
$noData = count($this->data);
if($noFields > 0 && $noData > 0)
{
for($i = 0; $i < $noFields; $i++)
{
if($i == ($noFields- 1))
$this->queryString .= $this->put_quotes1($this->field[$i]).')';
else
$this->queryString .= $this->put_quotes1($this->field[$i]).',';
}
$this->queryString.= " VALUES (";
for($i = 0; $i < $noData; $i++)
{
if($i == ($noData -1))
$this->queryString .= $this->put_quotes2($this->data[$i]).');';
else
$this->queryString .= $this->put_quotes2($this->data[$i]).',';
}
}
else
{
$this->error = "No column name or data was supplied";
}
break;
case 'SELECT':
$table_name = $this->put_quotes1($this->tableName);
$this->queryString = "SELECT ";
if(!isset($this->field) || is_null($this->field))
$this->queryString .= "* ";
else{
$noFields = count($this->field); //no of fields in table
for($i = 0; $i < $noFields; $i++)
{
if($i == ($noFields- 1)) // if on the last field
$this->queryString .= $this->put_quotes1($this->field[$i]).' ';
else
$this->queryString .= $this->put_quotes1($this->field[$i]).',';
}
}
$this->queryString .= "FROM ".$table_name;
if(isset($this->where))
$this->queryString .= " ".$this->where;
if(isset($this->order))
$this->queryString .= " ".$this->order;
if(isset($this->limit))
$this->queryString .= " ".$this->limit;
else
$this->queryString .= ";";
break;
case 'UPDATE':
$table_name = $this->put_quotes1($this->tableName);
$this->queryString = "UPDATE ". $table_name. " SET ";
$noFields = count($this->field); //no of fields in table
if(is_array($this->field) && is_array($this->data) && isset($this->where))
{
for($i = 0; $i < $noFields; $i++)
{
if($i == ($noFields -1))
$this->queryString .= $this->put_quotes1($this->field[$i])." = ". $this->put_quotes2($this->data[$i]).' ';
else
$this->queryString .= $this->put_quotes1($this->field[$i])." = ". $this->put_quotes2($this->data[$i]).',';
}
$this->queryString .= " ".$this->where.";";
}
else
{
$this->error = "Cannot build query. One of the following was not set";
}
break;
case 'DELETE':
$table_name = $this->put_quotes1($this->tableName);
$this->queryString = "DELETE FROM ".$table_name;
if(isset($this->where))
{
$this->queryString .= " ".$this->where.";";
}
else
{
$this->error = "Connot build. No condition was set";
}
break;
}
return $this->queryString;
}
}
Any pointers would help. Remember i have been through previous questions so a suggested edit or code answer would be great.

Related

Find the error that array_combine(): Both parameters should have an equal number of elements

I am importing CSV file to Laravel controller and insert data into two tables, but I got error-
array_combine() Both parameters should have an equal number of elements
function csvToArray ($filename = '', $delimiter = ',')
{
If (! file_exists ($filename) ||!is_readable($filename))
return false;
$header = null;
$data = array ();
if (($handle = fopen ($filename,'r')) !== false)
{
while (($row = fgetcsv($handle, 300000, $delimiter)) !== false)
{
if (!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
public function importCsv()
{
$file = public_path('file/city_master.csv');
$customerArr_data = $this->csvToArray($file);
for ($i = 0; $i < count($customerArr_data); $i++)
{
dd($customerArr_data);
}
return 'not in array';
}
Please try using array_merge() instead. Hope this helps

DataBase Schema File (.sql file ) Download with laravel

Schenario :
1) suppose that i have a database called myDataBase
2) Assume that myDataBase have some tables like A,B,C,D
3) i have to download the schema of the table A,B from the database with name myDataBase
Hope you have done the migration of all the table of your project . If you are using a xampp server then goto http://localhost/phpmyadmin and select your database and then goto export tab on the top tab bar and simply export with go button
<?php
//ENTER THE RELEVANT INFO BELOW
$mysqlUserName = "root";
$mysqlPassword = "";
$mysqlHostName = "localhost";
$DbName = "ukkoteknik";
$backup_name = "mybackup.sql";
$tables = array("admin", "sample");
Export_Database($mysqlHostName,$mysqlUserName,$mysqlPassword,$DbName, $tables, $backup_name=false );
function Export_Database($host,$user,$pass,$name, $tables=false, $backup_name=false )
{
$mysqli = new mysqli($host,$user,$pass,$name);
$mysqli->select_db($name);
$mysqli->query("SET NAMES 'utf8'");
$queryTables = $mysqli->query('SHOW TABLES');
while($row = $queryTables->fetch_row())
{
$target_tables[] = $row[0];
}
if($tables !== false)
{
$target_tables = array_intersect( $target_tables, $tables);
}
foreach($target_tables as $table)
{
$result = $mysqli->query('SELECT * FROM '.$table);
$fields_amount = $result->field_count;
$rows_num=$mysqli->affected_rows;
$res = $mysqli->query('SHOW CREATE TABLE '.$table);
$TableMLine = $res->fetch_row();
$content = (!isset($content) ? '' : $content) . "\n\n".$TableMLine[1].";\n\n";
for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter=0)
{
while($row = $result->fetch_row())
{ //when started (and every after 100 command cycle):
if ($st_counter%100 == 0 || $st_counter == 0 )
{
$content .= "\nINSERT INTO ".$table." VALUES";
}
$content .= "\n(";
for($j=0; $j<$fields_amount; $j++)
{
$row[$j] = str_replace("\n","\\n", addslashes($row[$j]) );
if (isset($row[$j]))
{
$content .= '"'.$row[$j].'"' ;
}
else
{
$content .= '""';
}
if ($j<($fields_amount-1))
{
$content.= ',';
}
}
$content .=")";
//every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num)
{
$content .= ";";
}
else
{
$content .= ",";
}
$st_counter=$st_counter+1;
}
} $content .="\n\n\n";
}
//$backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').")__rand".rand(1,11111111).".sql";
$date = date("Y-m-d");
$backup_name = $backup_name ? $backup_name : $name.".$date.sql";
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$backup_name."\"");
//echo $content; exit;
}
?>

N-tier navigation in codeigniter

How to create top navigation in code-igniter?
In controller I have declare a function and call model
private function getNavigation(){
$this->load->model('xx');
$data['nav'] = $this->xx->prepareTree();
$this->load->view('index',$data);
}
And In model I have declare three functions
public function prepareTree(){
$this->db->select("`catalog_parent` as parent_id, `catalog_name` as menu_item, `catalog_id` as id, `catalog_template` as pager_id");
$this->db->from("catalog_category");
$this->db->where("`catalog_navigation` = '1'");
$this->q = $this->db->get();
$create = '';
if ($this->q->num_rows() > 0) {
$create = $this->prepareList($this->q->result_array());
}
if(!empty($create)){
return $this->category_tree($create);
} else {
return '';
}
}
private function prepareList(array $items, $pid = 0) {
$output = array();
foreach ($items as $item) {
if ((int) $item['parent_id'] == $pid) {
if ($children = $this->prepareList($items, $item['id'])) {
$item['children'] = $children;
}
$output[] = $item;
}
}
return $output;
}
private function category_tree($menu_items, $child = false){
$output = '';
if (count($menu_items)>0) {
$output .= ($child === false) ? '<ul id="main-menu" class="sm sm-blue">' : '<ul>' ;
foreach ($menu_items as $item) {
$output .= '<li>';
$output .= ''.$item['menu_item'].'';
if (isset($item['children']) && count($item['children'])) {
$output .= $this->category_tree($item['children'], true);
}
$output .= '</li>';
}
$output .= '</ul>';
}
return $output;
}
If some suggest an more easy way please suggest us.
Thanks

Get the information you entered to ID

This file is the database ID information all the fields and went and came to a Blade, I want to an ID information entered in the same panel Blade I send my face.
class DataGrid extends DataSet
{
protected $fields = array();
/** #var Column[] */
public $columns = array();
public $headers = array();
public $rows = array();
public $output = "";
public $attributes = array("class" => "table");
public $checkbox_form = false;
protected $row_callable = array();
/**
* #param string $name
* #param string $label
* #param bool $orderby
*
* #return Column
*/
public function add($name, $label = null, $orderby = false)
{
$column = new Column($name, $label, $orderby);
$this->columns[$column->name] = $column;
if (!in_array($name,array("_edit"))) {
$this->headers[] = $label;
}
if ($orderby) {
$this->addOrderBy($column->orderby_field);
}
return $column;
}
//todo: like "field" for DataForm, should be nice to work with "cell" as instance and "row" as collection of cells
public function build($view = '')
{
($view == '') and $view = 'rapyd::datagrid';
parent::build();
Persistence::save();
foreach ($this->data as $tablerow) {
$row = new Row($tablerow);
foreach ($this->columns as $column) {
$cell = new Cell($column->name);
$sanitize = (count($column->filters) || $column->cell_callable) ? false : true;
$value = $this->getCellValue($column, $tablerow, $sanitize);
$cell->value($value);
$cell->parseFilters($column->filters);
if ($column->cell_callable) {
$callable = $column->cell_callable;
$cell->value($callable($cell->value, $tablerow));
}
$row->add($cell);
}
if (count($this->row_callable)) {
foreach ($this->row_callable as $callable) {
$callable($row);
}
}
$this->rows[] = $row;
}
$routeParamters = \Route::current()->parameters();
return \View::make($view, array('dg' => $this, 'buttons'=>$this->button_container, 'label'=>$this->label,
'current_entity' => $routeParamters['entity']));
}
public function buildCSV($file = '', $timestamp = '', $sanitize = true,$del = array())
{
$this->limit = null;
parent::build();
$segments = \Request::segments();
$filename = ($file != '') ? basename($file, '.csv') : end($segments);
$filename = preg_replace('/[^0-9a-z\._-]/i', '',$filename);
$filename .= ($timestamp != "") ? date($timestamp).".csv" : ".csv";
$save = (bool) strpos($file,"/");
//Delimiter
$delimiter = array();
$delimiter['delimiter'] = isset($del['delimiter']) ? $del['delimiter'] : ';';
$delimiter['enclosure'] = isset($del['enclosure']) ? $del['enclosure'] : '"';
$delimiter['line_ending'] = isset($del['line_ending']) ? $del['line_ending'] : "\n";
if ($save) {
$handle = fopen(public_path().'/'.dirname($file)."/".$filename, 'w');
} else {
$headers = array(
'Content-Type' => 'text/csv',
'Pragma'=>'no-cache',
'"Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Content-Disposition' => 'attachment; filename="' . $filename.'"');
$handle = fopen('php://output', 'w');
ob_start();
}
fputs($handle, $delimiter['enclosure'].implode($delimiter['enclosure'].$delimiter['delimiter'].$delimiter['enclosure'], $this->headers) .$delimiter['enclosure'].$delimiter['line_ending']);
foreach ($this->data as $tablerow) {
$row = new Row($tablerow);
foreach ($this->columns as $column) {
if (in_array($column->name,array("_edit")))
continue;
$cell = new Cell($column->name);
$value = str_replace('"', '""',str_replace(PHP_EOL, '', strip_tags($this->getCellValue($column, $tablerow, $sanitize))));
$cell->value($value);
$row->add($cell);
}
if (count($this->row_callable)) {
foreach ($this->row_callable as $callable) {
$callable($row);
}
}
fputs($handle, $delimiter['enclosure'] . implode($delimiter['enclosure'].$delimiter['delimiter'].$delimiter['enclosure'], $row->toArray()) . $delimiter['enclosure'].$delimiter['line_ending']);
}
fclose($handle);
if ($save) {
//redirect, boolean or filename?
} else {
$output = ob_get_clean();
return \Response::make(rtrim($output, "\n"), 200, $headers);
}
}
protected function getCellValue($column, $tablerow, $sanitize = true)
{
//blade
if (strpos($column->name, '{{') !== false ||
strpos($column->name, '{!!') !== false) {
if (is_object($tablerow) && method_exists($tablerow, "getAttributes")) {
$fields = $tablerow->getAttributes();
$relations = $tablerow->getRelations();
$array = array_merge($fields, $relations) ;
$array['row'] = $tablerow;
} else {
$array = (array) $tablerow;
}
$value = $this->parser->compileString($column->name, $array);
//eager loading smart syntax relation.field
} elseif (preg_match('#^[a-z0-9_-]+(?:\.[a-z0-9_-]+)+$#i',$column->name, $matches) && is_object($tablerow) ) {
//switch to blade and god bless eloquent
$_relation = '$'.trim(str_replace('.','->', $column->name));
$expression = '{{ isset('. $_relation .') ? ' . $_relation . ' : "" }}';
$fields = $tablerow->getAttributes();
$relations = $tablerow->getRelations();
$array = array_merge($fields, $relations) ;
$value = $this->parser->compileString($expression, $array);
//fieldname in a collection
} elseif (is_object($tablerow)) {
$value = #$tablerow->{$column->name};
if ($sanitize) {
$value = $this->sanitize($value);
}
//fieldname in an array
} elseif (is_array($tablerow) && isset($tablerow[$column->name])) {
$value = $tablerow[$column->name];
//none found, cell will have the column name
} else {
$value = $column->name;
}
//decorators, should be moved in another method
if ($column->link) {
if (is_object($tablerow) && method_exists($tablerow, "getAttributes")) {
$array = $tablerow->getAttributes();
$array['row'] = $tablerow;
} else {
$array = (array) $tablerow;
}
$value = ''.$value.'';
}
if (count($column->actions)>0) {
$key = ($column->key != '') ? $column->key : $this->key;
$keyvalue = #$tablerow->{$key};
$routeParamters = \Route::current()->parameters();
$value = \View::make('rapyd::datagrid.actions', array('uri' => $column->uri, 'id' => $keyvalue, 'actions' => $column->actions,
'current_entity' => $routeParamters['entity']));
}
return $value;
}
public function getGrid($view = '')
{
$this->output = $this->build($view)->render();
return $this->output;
}
public function __toString()
{
if ($this->output == "") {
//to avoid the error "toString() must not throw an exception"
//http://stackoverflow.com/questions/2429642/why-its-impossible-to-throw-exception-from-tostring/27307132#27307132
try {
$this->getGrid();
}
catch (\Exception $e) {
$previousHandler = set_exception_handler(function (){ });
restore_error_handler();
call_user_func($previousHandler, $e);
die;
}
}
return $this->output;
}
public function edit($uri, $label='Edit', $actions='show|modify|delete', $key = '')
{
return $this->add('_edit', $label)->actions($uri, explode('|', $actions))->key($key);
}
public function getColumn($column_name)
{
if (isset($this->columns[$column_name])) {
return $this->columns[$column_name];
}
}
public function addActions($uri, $label='Edit', $actions='show|modify|delete', $key = '')
{
return $this->edit($uri, $label, $actions, $key);
}
public function row(\Closure $callable)
{
$this->row_callable[] = $callable;
return $this;
}
protected function sanitize($string)
{
$result = nl2br(htmlspecialchars($string));
return Config::get('rapyd.sanitize.num_characters') > 0 ? str_limit($result, Config::get('rapyd.sanitize.num_characters')) : $result;
}
public function rowCount()
{
return count($this->rows);
}
}
This is the source of a rapyd-laravel widget/package, not a custom code.
According to DataGrid/DataSet documentation, you can use many sources:
https://github.com/zofe/rapyd-laravel/wiki/DataSet
DataSet/DataGrid are presenters, you can retrieve all data of your data source using
{{ $item->field }} or {{ $row->field }} respectively
See the docs please
https://github.com/zofe/rapyd-laravel/wiki

error reading db in joomla

While i run a component i am getting 500 - An error has occurred error reading db in joomla.
My configuration file is perfect.
I don't know what else to change..
Any guidance will be helpful
Thanks in advance...
//No direct acesss
defined('_JEXEC') or die();
jimport('joomla.application.component.model');
class DealsModelDeals extends JModel {
function getDeals(){
$db = $this->getDBO();
$db->setQuery('SELECT * from #__todaysdeal');
$deals = $db->loadObjectList();
if ($deals === null)
JError::raiseError(500, 'Error reading db');
return $deals;
}
function getDeal($id){
$query = ' SELECT * FROM #__todaysdeal '. ' WHERE id = '.$id;
$db = $this->getDBO();
$db->setQuery($query);
$deal = $db->loadObject();
if ($deal === null)
JError::raiseError(500, 'Deal with ID: '.$id.' not found.');
else
return $deal;
}
/**
* Method that returns an empty greeting with id 0
*
* #access public
*/
function getNewDeal(){
$dealTableRow =& $this->getTable('deals');
$dealTableRow->id=0;
$dealTableRow->clientName='';
return $dealTableRow;
}
/**
* Method to store a greeting in the DB
*
* #access public
*/
function saveDeal($deal)
{
//Parameter not necessary because our model is named DealsModelDeals (used to ilustrate that you can specify an alternative name to the JTable extending class)
$dealTableRow =& $this->getTable('deals');
//print_r($dealTableRow);
//print_r($_FILES); exit;
// Bind the form fields to the todaysdeal table
if (!$dealTableRow->bind($deal)) {
JError::raiseError(500, 'Error binding data');
}
// Make sure the deal record is valid
if (!$dealTableRow->check()) {
JError::raiseError(500, 'Invalid data');
}
// Insert/update this record in the db
if (!$dealTableRow->store()) {
$errorMessage = $dealTableRow->getError();
JError::raiseError(500, 'Error binding data: '.$errorMessage);
}
$id = $dealTableRow->id;
if(!empty($_FILES['dealImage']))
{
$file = $_FILES['dealImage'];
$id = $dealTableRow->id;
if ((($_FILES["dealImage"]["type"] == "image/gif") || ($_FILES["dealImage"]["type"] == "image/jpeg") || ($_FILES["dealImage"]["type"] == "image/pjpeg")) && ($_FILES["dealImage"]["size"] < 150000))
{
if ($_FILES["dealImage"]["error"] > 0)
{
echo "Return Code: " . $_FILES["dealImage"]["error"] . "<br />";
}
else
{
if (file_exists("components/com_deals/dealImages/" . $_FILES["dealImage"]["name"])) {
$_FILES["dealImage"]["name"] . " already exists. ";
} else {
move_uploaded_file($_FILES["dealImage"]["tmp_name"], "components/com_deals/dealImages/" .$id."_".$_FILES["dealImage"]["name"]);
echo "Stored in: " . "dealImages/" . $_FILES["dealImage"]["name"];
}
}
}
else
{
}
}
$dealImage = $_FILES['dealImage']['name'];
$dealImage .= (!empty($_FILES['dealImage']['name'])) ? ' ' . $_FILES['dealImage']['name'] : '';
$query = "UPDATE #__todaysdeal SET dealImage='".$id."_".$_FILES['dealImage']['name']."' WHERE id='".$id."'";
$db = $this->getDBO();
$db->setQuery($query);
$db->query();
//If we get here and with no raiseErrors, then everythign went well
}
function deleteDeals($arrayIDs)
{
$query = "DELETE FROM #__todaysdeal WHERE id IN (".implode(',', $arrayIDs).")";
$db = $this->getDBO();
$db->setQuery($query);
if (!$db->query()){
$errorMessage = $this->getDBO()->getErrorMsg();
JError::raiseError(500, 'Error deleting Deals: '.$errorMessage);
}
}
function dealsUploadPhoto($file, $id)
{
//UPLOAD FILE
$config = & JComponentHelper::getParams('com_deals');
$allowed = array('image/pjpeg', 'image/jpeg', 'image/jpg', 'image/png', 'image/x-png', 'image/gif', 'image/ico', 'image/x-icon');
$pwidth = $config->get('pwidth');
$pheight = $config->get('pheight');
$maxsize = $config->get('maxsize');
if($file['size'] > 0 && ($file['size'] / 1024 < $maxsize)){
if(!file_exists(JPATH_SITE . DS. 'images' . DS . 'deals'))
{
if(mkdir(JPATH_SITE . DS . 'images' . DS . 'deals')) {
JPath::setPermissions(JPATH_SITE . DS . 'images' . DS . 'deals', '0777');
if(file_exists(JPATH_SITE . DS . 'images' . DS . 'index.html')) {
copy(JPATH_SITE . DS . 'images' . DS . 'index.html', JPATH_SITE . DS . 'images' . DS . 'deals/index.html');
}
}
}
if($file['error'] != 0){
tpJobsMsgAlert('Upload file photo error.');
exit ();
}
if($file['size'] == 0){
$file = null;
}
if(!in_array($file['type'], $allowed)) {
$file = null;
}
if ($file != null){
$dest = JPATH_SITE.DS.'images'.DS.'deals'.DS.$id.'.jpg';
if(file_exists($dest))
{
$del = unlink($dest);
}
$soure = $file['tmp_name'];
jimport('joomla.filesystem.file');
$uploaded = JFile::upload($soure,$dest);
$fileAtr = getimagesize($dest);
$widthOri = $fileAtr[0];
$heightOri = $fileAtr[1];
$type = $fileAtr['mime'];
$img = false;
switch ($type)
{
case 'image/jpeg':
case 'image/jpg':
case 'image/pjpeg':
$img = imagecreatefromjpeg($dest);
break;
case 'image/ico':
$img = imagecreatefromico($dest);
break;
case 'image/x-png':
case 'image/png':
$img = imagecreatefrompng($dest);
break;
case 'image/gif':
$img = imagecreatefromgif($dest);
break;
}
if(!$img)
{
return false;
}
$curr = #getimagesize($dest);
$perc_w = $pwidth / $widthOri;
$perc_h = $pheight / $heightOri;
if(($widthOri<$pwidth) && ($heightOri<$height))
{
return;
}
if($perc_h > $perc_w)
{
$pwidth = $pwidth;
$pheight = round($heightOri * $perc_w);
}
else
{
$pheight = $pheight;
$pwidth = round($widthOri * $perc_h);
}
$nwimg = imagecreatetruecolor($pwidth, $pheight);
imagecopyresampled($nwimg, $img, 0, 0, 0, 0, $pwidth, $pheight, $widthOri, $heightOri);
imagejpeg($nwimg, $dest, 100);
imagedestroy($nwimg);
imagedestroy($img);
}
}else{
if($file['size'] / 1024 > $maxsize){
dealsMsgAlert('Size of file photo is too big. Maximum size".$maxsize." KB');
exit ();
}
}
}
function dealsMsgAlert($msg)
{
if (!headers_sent())
{
while(#ob_end_clean());
ob_start();
echo "<script> alert('".$msg."'); window.history.go(-1); </script>\n";
$out = ob_get_contents();
ob_end_clean();
echo $out;
exit();
}
echo "<script> alert('".$msg."'); window.history.go(-1); </script>\n";
exit();
}
}
?>
The problem that causes the red screen with 500 Error is happening because you are raising an exception if the requested quote is does not exist. You should not use JError::raiseError().
Use one of the following instead:
// This will set error to the model. You can get the errors from
// the model by your controller $model->getErrors() and output them to the screen.
$this->setError('ERROR MESSAGE GOES HERE');
OR
// This will output errors to the screen right the way
JFactory::getApplication()->enqueueMessage('ERROR MESSAGE GOES HERE', 'message');
Model already has _db property, you do not need to get db into variable. You can access it like this $this->_db. You can read about Joomla Model class here.
Also within your model you are using
$db = $this->getDBO();
$db->setQuery('SELECT * from #__todaysdeal');
$deals = $db->loadObjectList();
Model has simplified method to load list of object, like so
$deals =& $this->_getList('SELECT * from #__todaysdeal');

Resources