I have one table korisnik with 3 columns (id, username, password).
I want some like:
$upit = "SELECT * FROM korisnik WHERE username = '" . $_POST['username'] . "'
AND password = SHA1('" . $_POST['password'] . "')";
$temp = $upit->fetch(PDO::FETCH_ASSOC);
$_SESSION['id'] = $temp['id'];
if ($pdo_izraz->num_rows() == 1) {
session_start();
$_SESSION['autorizovan'] = 1;
$temp = $pdo_izraz->fetch(PDO::FETCH_ASSOC);
$_SESSION['id'] = $temp['id'];
$upit = ("Select * from korisnici where id=" . $_SESSION['id']);*
$izraz = $dbh->query($upit);
$obj = $izraz->fetch(PDO::FETCH_ASSOC);
$username = $obj['username'];
echo "<p id='bbb'><b >$username</b>:Welcome</p>";
I want to do something like this in CodeIgniter (to get one row where id=array of one row ($_SESSION['id']
I think you are looking for result_array()
see the manual here
$query = $this->db->query("YOUR QUERY");
foreach ($query->result_array() as $row)
{
echo $row['title'];
echo $row['name'];
echo $row['body'];
}
UPDATE
public function login($user, $pass) // Takeing the username/pass from form
{
$this->db->where('username', $user);
$this->db->where('password', md5($pass));
$query = $this->db->get('korisnici');
if ($query->num_rows() == 1)
{
$_SESSION['id'] = $this->query->row()->id;
return TRUE;
}
else
{
return FALSE;
}
}
public function getData()//Get result of array
{
$this->db->where('id', $_SESSION['id']);
$query = $this->db->get('korisnici');
return $query->result(); // here you can change for result_array() if you want
}
Related
I am developing a website and I am stuck in a problem where I am not getting products by categories when I select "All Categories" its working fine but when I try to select a category it again displays me the products that are shown in "All Categories" I am not getting any clue why is it happening.
Shortly, I need to get all products as well as I need products from specific category.
i tried to do it like that:
Frontend Controller
Function for returning data into view
public function search_load($keyword) {
$Cat = "";
$Desc = 1;
$Model = 1;
$Filter = array();
if(isset($_GET['category'])) {
if($_GET['category'] != "") {
$Cat = $_GET['category'];
}
}
if(isset($_GET['desc'])) {
if($_GET['desc'] != "") {
$Desc = $_GET['desc'];
}
}
if(isset($_GET['model'])) {
if($_GET['model'] != "") {
$Model = $_GET['model'];
}
}
$Filter = ["category" => $Cat, "desc" => $Desc, "model" => $Model];
$search = $this->search_products($keyword, $Filter);
$cat = $this->get_categories();
$ProductNames = $this->product_names();
$cart_item = $this->get_cart_products();
return view("search-result", compact('cat','ProductNames','search','keyword','cart_item'));
}
Function for keyword related product searching Product
public function search_products($keyword, $filter = array()) {
$Products = Product::query();
if(!empty($filter)) {
if($filter['desc'] == "1") {
$Products = $Products->orWhere('description','like','%' . $keyword . '%');
}
if($filter['model'] == "1") {
$Products = $Products->orWhere('model_no','like','%' . $keyword . '%');
}
if($filter['category'] != "" && $filter['category'] > "0") {
$cat = $filter['category'];
// return $cat;
$Products = $Products->whereIn('parent_category', [$cat]);
}
$Products = $Products->where('name','like','%' . $keyword . '%')
->orWhere('upc_code','like','%' . $keyword . '%')
->orWhere('consumer_upc1','like','%' . $keyword . '%')
->orWhere('consumer_upc2','like','%' . $keyword . '%');
}
$Products = $Products->where('status','1')->paginate(20);
return $Products;
}
jQuery Function
function search22()
{
var SText = document.getElementById("text-search").value;
SText = SText.replace("&","amp;");
var Category = document.getElementById("category").value;
var PDesc = 1;
var PModel = 1;
var link = "/search/"+ SText;
var parameter = "";
if(SText != "")
{
if(Category != "")
{
parameter = "category=" + Category;
}
if(PDesc == "1"){
if(parameter != ""){
parameter += "&desc=1";
}
else{
parameter = "desc=1";
}
}
if(PModel == "1"){
if(parameter != ""){
parameter += "&model=1";
}
else{
parameter = "model=1";
}
}
if(parameter != ""){
link += "?" + parameter;
}
window.location.href = link;
}
}
`
There is a table foo and it has a column called fooPos. I ned to update the fooPos column with respect to id.
I have the following data
$id = [21,23,34,56,76];
$fooPos = [1,2,3,4,5];
How can I update this without using loops?
It's like 21(id) => 1(fooPos), 23 => 2, 34 =>3 etc.,
You have a solution with INSERT INTO ... ON DUPLICATE KEY UPDATE..., more details in here Multiple update
That solution can trigger an error if the ID doesn't exist and you have some other required fields. In that cas you ca use this solution:
$updateSets = [];
$ids = [21,23,34,56,76];
$fooPos = [1,2,3,4,5];
foreach ($ids as $key => $id) {
$updateSets[] = 'SELECT '.$id.' as set_id, '.$fooPos[$key].' as pos ';
}
$updateSetsString = implode(' UNION ALL ', $updateSets);
\DB::statement('UPDATE your_table JOIN ('.$updateSetsString.') up_set ON your_table.id = up_set.set_id SET your_table.pos = up_set.pos');
function updateTableWithoutQueryLoops()
{
try {
$id = collect([21,23,34,56,76]);
$fooPos = collect([1,2,3,4,5]);
// To check both parameters should have an equal number of elements.
if(count($id) == count($fooPos) ) {
$combinedValues = $id->combine($fooPos);
} else {
return 'Please check equal number of elements for give arrays.';
}
// Run foreach loop of Combined values
foreach ($combinedValues as $id => $fooPos) {
$id = (int) $id;
$cases[] = "WHEN {$id} then ?";
$params[] = $fooPos;
$ids[] = $id;
}
$ids = implode(',', $ids);
$cases = implode(' ', $cases);
$params[] = \Carbon\Carbon::now();
return \DB::update("UPDATE `foo` SET `fooPos` = CASE `id` {$cases} END, `updated_at` = ? WHERE `id` in ({$ids})", $params);
} catch (\Exception $e) {
return 'Exception message:' . $e->getMessage() . ' with code: ' . $e->getCode();
}
}
function updateTableWithoutQueryLoops()
{
try {
$id = collect([21,23,34,56,76]);
$fooPos = collect([1,2,3,4,5]);
// To check both parameters should have an equal number of elements.
if(count($id) == count($fooPos) ) {
$combinedValues = $id->combine($fooPos);
} else {
return 'Please check equal number of elements for give arrays.';
}
// Run foreach loop of Combined values
foreach ($combinedValues as $id => $fooPos) {
$id = (int) $id;
$cases[] = "WHEN {$id} then ?";
$params[] = $fooPos;
$ids[] = $id;
}
$ids = implode(',', $ids);
$cases = implode(' ', $cases);
$params[] = \Carbon\Carbon::now();
return \DB::update("UPDATE `foo` SET `fooPos` = CASE `id` {$cases} END, `updated_at` = ? WHERE `id` in ({$ids})", $params);
} catch (\Exception $e) {
return 'Exception message:' . $e->getMessage() . ' with code: ' . $e->getCode();
}
}
I want to build advanced search script but I have this error with search_all function in the model
A PHP Error was encountered
Severity: 4096
Message: Object of class CI_DB_mysql_result could not be converted to string
Filename: models/search_model.php
Line Number: 129
i have four fildes
1- input text to write the book name
2- select box for the author
3- select box for the publisher
3-select box for the section
the model is
class search_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
/* This function get all search in database sort by order asc.*/
function get_new_one($id)
{
$this->db->where('ne_id',$id);
$result=$this->db->get('d_search');
return $result->row();
}
//////////////frontend//////////////////////////////////////////////////////////
function show_new($id)
{
$result=$this->db->query("SELECT * , COUNT( d_comments_search.cn_new_id ) as count
FROM d_search
left JOIN d_comments_search ON d_search.ne_id = d_comments_search.cn_new_id and d_search.ne_hide='1'
inner join d_search_category on d_search_category.nc_id = d_search.ne_category_id and d_search_category.nc_hide= '1'
and d_search.ne_id= $id group by d_search.ne_id");
return $result->row() ;
}
function generate_results($keyword,$row=0){
$result1 = $this->db->query("SELECT bo_id,bo_name,bo_state,bo_about FROM d_book where (bo_name like '%$keyword%' or bo_about like '%$keyword%') and bo_state = '1' limit $row,20");
$result2 = $this->db->query("SELECT au_id,au_name,au_state,au_info FROM d_author where (au_name like '%$keyword%' or au_info like '%$keyword%') and au_state = '1' limit $row,20");
$result3 = $this->db->query("SELECT pub_id,pub_name,pub_state,pub_info FROM d_publishing where (pub_name like '%$keyword%' or pub_info like '%$keyword%') and pub_state = '1' limit $row,20");
$results = array_merge($result1->result_array(),$result2->result_array(),$result3->result_array());
return $results;
}
// get total number of users
function getNumUsers($keyword)
{
$result1 = $this->db->query("SELECT bo_id,bo_name,bo_state,bo_about FROM d_book where (bo_name like '%$keyword%' or bo_about like '%$keyword%') and bo_state = '1'");
$result1 = $result1->num_rows();
$result2 = $this->db->query("SELECT au_id,au_name,au_state,au_info FROM d_author where (au_name like '%$keyword%' or au_info like '%$keyword%') and au_state = '1'");
$result2 = $result2->num_rows();
$result3 = $this->db->query("SELECT pub_id,pub_name,pub_state,pub_info FROM d_publishing where (pub_name like '%$keyword%' or pub_info like '%$keyword%') and pub_state = '1'");
$result3 = $result3->num_rows();
return $result1 + $result2 + $result3;
}
//////////////////////////////////end paging///////////////////
function get_publishing()
{
$this->db->where('pub_state','1');
$result=$this->db->get('d_publishing')->result_array();
return $result;
}
function get_author()
{
$this->db->where('au_state','1');
$result=$this->db->get('d_author')->result_array();
return $result;
}
function get_section()
{
$this->db->where('sec_state','1');
$result=$this->db->get('d_section')->result_array();
return $result;
}
function search_name()
{
$bo_name=$_POST['bo_name'];
$this->db->order_by("bo_ord","asc");
$this->db->like('bo_name',$bo_name);
return $this->db->get('d_book')->result_array();
}
function search_all() {
$publish = $this->input->post('publish');
$author = $this->input->post('author');
$sec_name = $this->input->post('section');
$sql = $this->db->query("SELECT * FROM `d_book`");
$searches = array();
if ($publish != 'choose')
$searches[] = "`bo_pub_id` = '$publish'";
if ($author != 'choose')
$searches[] = "`bo_au_id` = '$author'";
if ($sec_name != 'choose')
$searches[] = "`bo_sec_id` = '$sec_name'";
if (count($searches) > 0) {
$sql .= "WHERE " . implode(" AND ", $searches);
}
$sql .= ';';
}
}
this is controller
class Search extends front_end {
var $temp;
function __construct(){
parent::__construct();
$this->load->library('form_validation');
//echo $this->input->post("keyboard");
}
public function index()
{
$this->overview();
}
/**
* This function display all search
* #param integer $row
*/
public function overview($row=0)
{
$this->form_validation->set_rules('keyword', 'كلمة البØØ«', 'trim|required|xss_clean|htmlspecialchars');
$this->form_validation->run();
$this->store_keyword();
//echo $this->session->flashdata('keyword');
if ($this->session->flashdata('keyword') != ''){
$keyword=$this->session->flashdata('keyword');
$this->generate_results($this->session->flashdata('keyword'),$row);
}else{
$this->generate_results($this->input->post("keyword"),$row);
}
//$this->session->set_flashdata('keyword', $this->input->post("keyword"));
$data = $this->temp;
//$this->session->keep_flashdata('keyword');
$this->view('search/site/results', $data);
}
/**
* This function generate result of search
* #param string $keyword
* #param integer $row
*/
public function generate_results($keyword,$row=0){
$this->load->model('search/search_model','search');
$this->load->library('pagination');
$config['base_url'] = base_url().'search/search/overview/';
$config['total_rows'] = $this->search->getNumUsers($keyword);
$config['per_page'] = '20';
$config['uri_segment'] = '4';
$this->pagination->initialize($config);
$data['page'] = $row;
$data['results'] = $this->search->generate_results($keyword,$row);
$data['total_rows'] = $this->search->getNumUsers($keyword);
$data['links']=$this->pagination->create_links();
$this->temp = $data;
}
/**
* This function display detail of new
* #param integer $id
*/
public function show($id)
{
$data['new']=$this->search->show_new($id);
$count=$data['new']->ne_count_visit;
$this->search->add_count($count,$id);
$data['comments']=$this->search->show_comments($id);
$this->view('site/new', $data);
}
/**
* This function store keyword to use in search
*/
private function store_keyword(){
if($this->input->post("keyword")){
$this->session->set_userdata('keyword', $this->input->post("keyword"));
}
}
public function search_form()
{
$this->load->model('search/search_model','search');
$data['publish']=$this->search->get_publishing();
$data['author']=$this->search->get_author();
$data['section']=$this->search->get_section();
$this->view('search/site/adv_search_form',$data);
}
public function search_adv()
{
$this->load->model('search/search_model','search');
$data['bo_name']=$this->input->post('bo_name');
$data['section']=$this->input->post('section');
$data['publish']=$this->input->post('publish');
$data['author']=$this->input->post('author');
$data['result1'] = '';
$data['result2'] = '';
$data['result3'] = '';
$data['result4'] = '';
if($data['bo_name'] == NULL and $data['section']== NULL and $data['publish']==NULL and $data['author']== NULL){
$this->search_form();
}else{
if(isset($data['bo_name']) and $data['bo_name']!= NULL)
{
$data['result1'] = $this->search->search_name();
}
if(isset($data['section']) and $data['section'] != NULL)
{
$data['result2']=$this->search->search_all();
}
if(isset($data['publish']) and $data['publish'] != NULL)
{
$data['result3']=$this->search->search_all();
}
if(isset($data['author']) and $data['author']!= NULL)
{
$data['result4']=$this->search->search_all();
}
$data['no_results'] = '';
if(! $data['result1'] && !$data['result2'] && !$data['result3'] && !$data['result4']){
$data['no_results'] = TRUE;
}else{
$data['no_results'] = FALSE;
}
$this->view('search/site/search_result',$data);
}
}
}
/* End of file dashboard.php */
$this->db->query() doesn't store a query string for later use. It actually executes the query right away and return an object of CI_DB_mysql_result. You should build the query string before you call $this->db->query() and store it into a variable, then pass it into the method.
$sql = "SELECT * FROM `d_book` ";
$searches = array();
if ($publish != 'choose')
{
$searches[] = "`bo_pub_id` = '__some_id__'";
}
if ($author != 'choose')
{
$searches[] = "`bo_au_id` = '__some_id__'";
}
if ($sec_name != 'choose')
{
$searches[] = "`bo_sec_id` = '__some_id__'";
}
if (count($searches) > 0)
{
$sql .= "WHERE " . implode(" AND ", $searches);
}
$sql .= ';';
$this->db->query($sql);
I after some help with codeIgniter pagination (fixign a bug).. I can see the number of records and the pagination link in the view but when click on the next link, it does not show the next/previous 10 records. Can someone please help me with this?
I have the following code in my controller
function customerlist_pagination()
{
$search = $this->input->post('search');
$data['title'] = "Customer Clist";
$data['heading'] = "List of customers";
$data['result'] = $this->customers_model->getAllcustomers_pagination($search_para, FALSE, "limit_rows");
$data['num_recs'] = $this->customers_model->getAllcustomers_pagination($search_para, FALSE, "num");
$config['base_url'] = base_url().'index.php/customer/customerlist_pagination/';
$config['total_rows'] = $data['num_recs'];
$config['per_page'] = 10;
$config['uri_segment'] = 3;
$config['next_link'] = 'Next >';
$config['prev_link'] = '< Previous ';
$this->pagination->initialize($config);
$this->load->view('customer_view_table',$data);
}
In the model, I have the following code:
function getAllSeizures_pagination($search_para, $archive_search = FALSE, $result_type)
{
$search_para = $search_para."%";
$selected_fields = "customer.firstName
customer.lastName, customer.address,
customer.city, customer.postcode";
$from = "customer";
$where = "customer.deleted=0 ";
if ($archive_search == TRUE) {
$where .= "AND customer.archived= 1 ";
}else{
$where .= "AND customer.archived= 0 ";
}
$where .= "AND (customer.firstName LIKE '$search_para' OR customer.postcode LIKE '$search_para' OR customer.city LIKE '$search_para')";
$query = $this->db->select($selected_fields, false)
->from($from)
->where($where)
->order_by('customer.idcustomer', 'desc');
if($result_type == "limit_rows")
{
$query = $this->db->limit(10, 0)
->get();
$query = $query->result();
}
if($result_type == "num") {
$query = $this->db->get();
$query = $query->num_rows();
}
return $query;
}
Thanks alot
Regards
Prats
The pagination class passes the offset to you in the uri_segment specified. Since you set it to 3, you should capture that info in the first variable of your controller method, like so:
function customerlist_pagination( $offset )
{
}
Then, when you call your $this->customers_model->getAllcustomers_pagination(), you have to pass it the $offset, so that later on in your code, where you limit your results:
$query = $this->db->limit(10, 0)->get();
you should instead use this $offset to limit your results:
$query = $this->db->limit(10, $offset)->get();
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');