sql statement with where clause in function - mysql

I have written a function that will query the database. The sql statement includes a where clause. However, I keep getting this error
"Message: odbc_exec(): SQL error: [Microsoft][ODBC SQL Server
Driver][SQL Server]Invalid column name 'home'., SQL state S0022 in
SQLExecDirect".
The column name should be banner_category while "home_banner) is the value.
How should I go about achieving it?
public function get_landing_banners()
{
$query = $this->db->query(
'SELECT *
FROM o2o_banner
WHERE banner_category='home_banner'');
$data = array();
foreach ($query->result_array() as $row)
{
$data[] = $row;
}
return $data;
}

If you want to return an array try this:
public function get_landing_banners()
{
$this->db->select('*')->from('o2o_banner')->where('banner_category', 'home_banner');
$q = $this->db->get();
if ($q->num_rows() > 0) {
return $q->result_array();
}
}

Try this coding
public function get_landing_banners()
{
$query = $this->db->query(
'SELECT *
FROM o2o_banner
WHERE banner_category="home_banner"');
$data = array();
foreach ($query->result_array() as $row)
{
$data[] = $row;
}
return $data;
}

Related

Multi-parameterized SQL syntax invalid using WHERE AND

Below is the code in my model, I'm using Codeigniter, I'm sure there's a simple problem with it but I've been trying for a long time, any ideas?
<?php
class Users_model extends CI_Model {
public function __construct() {
parent::__construct();
$this->load->database();
}
public function checkLogin($username, $pass) {
$sql = "SELECT COUNT(*) FROM Users WHERE username=? AND password=?;";
$query = $this->db->query($sql, $username, sha1($pass));
if ($query -> num_rows() == 1) {
return True;
} else {
return False;
}
}
}
?>
Error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? AND password=?' at line 1
If $this->db is a PDO object, than its query method doesn't allow you to use argument binding.
You will have to use a prepared statement. Your code would then look like:
$sql = "SELECT COUNT(*) as count FROM Users WHERE username=:user AND password=:pass";
$sth = $this->db->prepare($sql);
$sth->execute(array(':user' => $username, ':pass' => sha1($pass)));
$count = $sth->fetch(PDO::FETCH_COLUMN, 'count');
Today I found that the below worked, the parameters for the SQL statement just needed to be in a array.
$query = $this->db->query($sql, array($username, sha1($pass)));

encodejson is not giving proper format of json

if ($tag == 'get_rajkot')
{
$data=$db->get_rajkot();
if($data!=false)
{
$valueresult=array();
foreach ($data as $value)
{
$valueresult=$value;
echo json_encode($valueresult);
}
}
else
{
// failed to store
$response["error"] = 1;
$response["error_msg"] = "Error occured..No get_headlines image found...";
echo json_encode($response);
}
}
db_function.php
public function get_rajkot()
{
$result = mysql_query("SELECT * FROM wp_term_relationships join wp_posts where ID=`object_id` and term_taxonomy_id=19 ORDER BY object_id DESC LIMIT 10") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0)
{
$rows = array();
while($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
//print_r($rows);
}
return $rows;
}
else
{
// profile not found
return false;
}
}
Result:
It's not giving comma between two objects and brakets [] at the start and at the end.
set my sql char set after mysql_connect query like this...
this problem was occurring due to Gujarati font
$con = mysql_connect($host,$username,$password) or die(mysql_error());
mysql_set_charset('utf8mb4',$con);

i want to fetch value like 52,100 but it returns only52 mysql codeigniter

comma separated by value fetch from the database
public function get_data()
{ $this->db->select_sum("total_sale");
$this->db->from('one_month_report');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result();
} else {
return FALSE;
}
}
Controller From Comment
public function profit_in_last_month_view() {
$this->load->view('pages/header');
$data['listProduct'] = $this->mproduct->get_data();
$this->load->view('pages/profit_in_last_month', $data);
echo $this->db->last_query();
exit;
$this->load->view('pages/footer');
}
This should return the sum of total_sale of the most recent 52000 results.
$this->mproduct->get_data(52000)
public function get_data($limit,$offset=0){
$limit = ($limit) ? $limit : 20;
$q = $this->db
->select_sum('total_sale')
->limit($limit, $offset)
->order_by('created_at', 'desc')
->get('one_month_report');
return ($q->num_rows() > 0) ? $q->result() : null;
}

show tables get only the last name of table

I'm trying to show the name of table in my database. I write this code :
function affiche_liste()
{
$db=new PDO('mysql:host=localhost;dbname=testf','root','');
$result = $db->query("SHOW TABLES");
foreach($result->fetch(PDO::FETCH_NUM) as $data) {
$tableList = $data[0];
}
return $tableList;
}
It give to me only the last table ?
For a simple query without parameters and the SQL hard coded you can use a generic function passing the connection and SQL to the function.
The following function () returns an array containing all rows in the result set.
function queryAll($db,$query){
$sth = $db->query($query);
$result = $sth->fetchAll(PDO::FETCH_NUM);
return $result;
}
For a simple query without parameters and the SQL hard coded you can use a generic function passing the connection and SQL to the function.
The following function () returns an array containing all rows in the result set.
function queryAll($db,$query){
$sth = $db->query($query);
$result = $sth->fetchAll(PDO::FETCH_NUM);
return $result;
}
$db=new PDO('mysql:host=localhost;dbname=testf','root','');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SHOW TABLES";
$tables = queryAll($db,$query);
print_r($tables);
Each time you are looping through the results, your are overwriting the variable tableList. Instead, you need to append to an array of results.
function affiche_liste()
{
$db=new PDO('mysql:host=localhost;dbname=testf','root','');
$result = $db->query("SHOW TABLES");
$tableList = array();
foreach($result->fetch(PDO::FETCH_NUM) as $data) {
array_push($tableList, $data[0]);
}
return $tableList;
}
try this
`
function affiche_liste()
{$db=new PDO('mysql:host=localhost;dbname=testf','root','');
$result = $db->query("SHOW TABLES");
foreach($result->fetch(PDO::FETCH_NUM) as $data) {
$tableList[] = $data[0];
}
return $tableList;
}
`
i hope it'll work...
here your array is overwitting every time...that's the reason you were getting the last table name....so you need to append to the existing array...

Kohana - Insert record with ignore duplicate

How to implement "insert ignore"? using kohana orm While adding multiple records, if few of them may already exist in database using below code adding of all 100 records will be declined.
$query = DB::insert('tablename', array('column1', 'column2','column3'));
foreach ($data as $d) {
$query->values($d);
}
try {
$result = $query->execute();
} catch ( Database_Exception $e ) {
echo $e->getMessage();
}
UPDATE:
Here is how i did This, i have to insert multiple records,
$Xtransactions = "INSERT IGNORE INTO `tablename` (`tid`, `tdate`, `appid`,
`userid`, `user_ip`) VALUES";
foreach ($objSas->trecord as $trow) {
$Xtransactions .= "(".$trow->tid.",'".
date('Y-m-d H:i:s', strtotime($trow->tdate))."',".
$trow->userid.",".
$trow->Xnumber.",'".
$trow->ip."'),";
}
$Xtransactions = substr($Xtransactions , 0, -1);
try {
DB::query(Database::INSERT, $Xtransactions )->execute();
} catch ( Database_Exception $e ) {
echo $e->getMessage();
}
With query builder this is impossible, try to write a raw query.
DB::query(Database::INSERT, 'INSERT IGNORE INTO table VALUES (...)')->execute();
I usually collect such modifications in static helper class, for example
<?php defined('SYSPATH') or die('No direct script access.');
class Helper_DB_Query{
/**
* #param Database_Query_Builder_Insert $insert query thant need to be converted
* #return Database_Query converted query
*/
public static function insert_to_insert_ignore( Database_Query_Builder_Insert $insert ){
$insert = (string) $insert;
$query = preg_replace("/^INSERT(.*)$/", "INSERT IGNORE $1", $insert);
return DB::query(Database::INSERT, $query);
}
}