Multi-parameterized SQL syntax invalid using WHERE AND - mysql

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

Related

Want to convert a function from Mysql to PDO

function get_country($code){
$query = mysql_query("SELECT country FROM `list_countries` WHERE `code`='".$code."' LIMIT 1");
$country = mysql_fetch_array($query);
return $country['country'];
}
Very new to PDO and have absolutely no idea how to turn this from a mysql function to a PDO one. Any help would be appreciated :)
You need to take PDO database connection handler with you :) From your code I would suggest setting it as global, or you can add additional parameter to all the functions.
$dbconn = new PDO("mysql:host=localhost;dbname=your_db","your_user","your_password");
// this line is important - throw an exception if there is an error
$dbconn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
function get_country( $dbconn, $code ) {
$res = $dbconn->prepare('SELECT country FROM `list_countries` WHERE `code`=? limit 1');
$res->execute( array( $code) )
$country = $res->fetch();
return $country['country'];
}

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...

sql statement with where clause in function

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

JOIN on a subquery with Zend Framework 2 TableGateway

I'm trying to do a query with Zend Framework 2 where I have a SELECT inside a JOIN statement. So far, here's what I've tried, but injecting the SELECT object into the first parameter of join() doesn't seem to be working. I've resorted to such an approach since I need to order the results first before doing any grouping. Any ideas on how to get it working?
public function getSearchKeyword($keyword, $limit)
{
$select = $this->keywords->getSql()->select();
$subquery = $this->pages->getSql()->select();
$subWhere = new \Zend\Db\Sql\Where();
$subWhere->equalTo('delete_flag', 'n')
->equalTo('published_flag', 'y');
$subquery->where($subWhere);
$where = new \Zend\Db\Sql\Where();
$where->like('keyword', '%' . $keyword . '%')
->equalTo('delete_flag', 'n');
$select->columns(array('display' => 'keyword', 'url'))
->join(array('sub' => $subquery), 'sub.page_id = keywords.page_id', array())
->where($where)
->group(array('keywords.page_id', 'keywords.keyword'))
->order(array('rank', 'keyword'))
->limit($limit);
$row = $this->tableGateway->selectWith($select);
return $row;
}
The query I'm trying to write is below:
SELECT keywords.keyword AS display, keywords.url
FROM keywords
INNER JOIN
(
SELECT * FROM pages WHERE published_flag = 'y' AND delete_flag = 'n' ORDER BY page_id DESC
) pages
ON pages.page_id = keywords.page_id
WHERE published_flag = 'y'
AND delete_flag = 'n'
AND keywords.keyword LIKE '%?%'
GROUP BY display, page_id;
I was working around the same problem and did not found a standard way to solve it. So I got a working but not zf2 standard one
Create a small interface to mannage Db conections
Implements it as a small class to get a connection PDO object to
your database
execute your arbitrary querys
Code sample
// Filename: /module/MyTools/src/MyTools/Service/DbModelServiceInterface.php
namespace MyTools\Service;
interface DbModelServiceInterface
{
/**
* Will return the result of querying the curret database
*
* #param type $query
* #result mixed
*/
public function dbQuery($query);
/**
* Will return a connection object that links to curret database
*
* #result mixed
*/
public function getConnection();
}
The class implementing the interface. It creates and offers a PDO connection. Note: It needs extra code to close conns and to perfeorm security adm...
It test it and is completely functional.
code:
// Filename: /module/MyTools/src/MyTools/Service/DbModelServiceMySql.php
namespace MyTools\Service;
use MyTools\Service\DbModelServiceInterface;
use PDO;
class DbModelServiceMySql implements DbModelServiceInterface
{
protected $driverConfig;
protected $connection;
protected $isconnected = FALSE;
protected $dbname = '';
/**
* Creates a connection to main database
*/
public function __construct()
{
$driverConfig = self::getDriverDef();
$this->driverConfig = $driverConfig; // new PDO($driverConfig['dsn'], $driverConfig['username'], $driverConfig['password']);
$this->_connect();
}
protected function _connect(){
$dsn = (isset($this->driverConfig['dsn'])) ? $this->driverConfig['dsn'] : '';
$username = (isset($this->driverConfig['username'])) ? $this->driverConfig['username'] : '';
$password = (isset($this->driverConfig['password'])) ? $this->driverConfig['password'] : '';
if( ($dsn) && ($username) && ($password)){
$options = [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', ];
try {
$this->connection = new PDO($dsn, $username, $password, $options);
$this->isconnected = TRUE;
$this->_setdbname($dsn);
} catch (Exception $ex) {
throw new RuntimeException('YOUR ERROR MESSAGE.');
}
}
return $this->isconnected;
}
protected function _setdbname($dsn){
if($dsn){
$chunks = explode(';', ''.$dsn);
foreach($chunks as $chunk){
if(strpos('***'.$chunk, 'dbname') > 2){
$nombre = explode('=', $chunk);
$this->dbname = $nombre[1];
break;
}
}
}
}
/**
* {#inheritDoc}
*/
public function dbQuery($query) {
if($this->connection){
$resultset = $this->connection->query($query);
if($resultset){
return $resultset->fetchAll(PDO::FETCH_ASSOC);
}else{
return ['Error' => 'YOUR CUSTOM ERROR MESSAGE.'];
}
}else{
return ['Error' => 'OTHER CUSTOM ERROR MESSAGE'];
}
}
public static function getDriverDef()
{
$autoloadDir = __DIR__ . '../../../../../../config/autoload/';
$credentialsdb = include $autoloadDir . 'local.php';
$globaldb = include $autoloadDir . 'global.php';
$def = (isset($globaldb['db'])) ? $globaldb['db'] : array();
$credentials = (isset($credentialsdb['db'])) ? $credentialsdb['db'] : $credentialsdb;
return array_merge($def, $credentials);
}
/**
* {#inheritDoc}
*/
public function getConnection() {
if($this->connection){
return $this->connection;
}else{
return 'Error: YOUR CUSTOM ERROR MESSAGE';
}
}
/**
* {#inheritDoc}
*/
public function getDbName(){
return $this->dbname;
}
}
Now you have a class you can instantiate elsewhere to perform the querys you need.
use:
code:
$myQuery = 'the very very complex query you need to execute'
$myDbConn = new MyTools\Service\DbModelServiceMySql();
$result = $myDbConn->dbQuery($myQuery);
If success you got a resulset array of pairs columnName => value
You can try this one.
$select->columns(array('display' => 'keyword', 'url'))
->join(array('sub' => 'pages'), 'sub.page_id = keywords.page_id',
array(), $select::JOIN_INNER)
->where($where)
->group(array('keywords.page_id', 'keywords.keyword'))
->order(array('rank', 'keyword'))
->limit($limit);
In your code, you are getting all keywords which page_id's is in sub page_id where delete_flag = 'n' and published_flag = 'y'.
join(..., 'sub.page_id = keywords.page_id', array())
When you don't need any columns of pages table, you can use IN instead of JOIN.
For example when you need to know which keywords are in which pages, you should use JOIN, but when you need to know which keyboards are in any pages, you can use IN statement.
Anyway :
There is no standard way in ZF2 but you can try following code.
public function getSearchKeyword($keyword, $limit)
{
$select = $this->keywords->getSql()->select();
$subquery = $this->pages->getSql()->select();
$subWhere = new \Zend\Db\Sql\Where();
$subWhere->equalTo('delete_flag', 'n')
->equalTo('published_flag', 'y');
$subquery->columns(array('page_id'))
->where($subWhere);
$where = new \Zend\Db\Sql\Where();
$where->like('keyword', '%' . $keyword . '%')
->equalTo('delete_flag', 'n')
->in('keywords.page_id', $subquery);
$select->columns(array('display' => 'keyword', 'url'))
->where($where)
->group(array('keywords.page_id', 'keywords.keyword'))
->order(array('rank', 'keyword'))
->limit($limit);
$row = $this->tableGateway->selectWith($select);
return $row;
}
I've faced a similar issue. Since the FROM table and Subquery's FROM table were different i got an error.
My workaround was to extract the SQL and create a statement.
$sql = $select->getSqlString(new \Zend\Db\Adapter\Platform\Mysql());
$stmt = $this->getAdapter()->createStatement($sql);
$stmt->prepare($sql);
$result = $stmt->execute();
$resultSet = new ResultSet(); \\ Class Zend\Db\ResultSet\ResultSet
$resultSet->initialize($result);

mysql_num_rows() expects parameter 1 to be resource, boolean in joomla component

When I execute the function below query execute successfully but I get a warning above the result the query:
mysql_num_rows() expects parameter 1 to be resource, boolean
How do I fix this?
public function retrieve()
{
$id=JRequest::getVar('id');
$db =JFactory::getDBO();
$sql="select *
from
#__npco_car,#__npco_namayeshgah,#__npco_agahi
where
#__npco_car.car_id='$id' and
#__npco_namayeshgah.id_namayeshgah=#__npco_agahi.id_namayeshgah and
#__npco_car.car_id=#__npco_agahi.car_id
";
$db->setQuery($sql);
$db->query();
$row = $db->getNumRows();
if($row == 1) {
return $db->loadAssocList();
} else {
$db = JFactory::getDBO();
$sql="select *
from
#__npco_car,#__npco_useragahi,#__npco_user
where
#__npco_car.car_id='$id' and
#__npco_user.id_user=#__npco_useragahi.id_user and
#__npco_car.car_id=#__npco_useragahi.car_id
";
$db->setQuery($sql);
return $db->loadAssocList();
}
}
Your code has several issues.
Never use unchecked/unvalidated request values, not even in examples!
Use the query builder.
Reduce coupling by a) setting the database in the constructor, which is done already in models, and b) retrieve the id in the controller.
You try to get all fields (*) from multiple tables, which have some column names in common. That will not work.
Have a look at JOINs.
This will work:
public function retrieve($id)
{
$query = $this->_db->getQuery(true);
$query->select('#__npco_car.*')->from(array('#__npco_car', '#__npco_namayeshgah', '#__npco_agahi'));
$query->where('#__npco_car.car_id = ' . (int) $id);
$query->where('#__npco_namayeshgah.id_namayeshgah = #__npco_agahi.id_namayeshgah');
$query->where('#__npco_car.car_id = #__npco_agahi.car_id');
$this->_db->setQuery($sql);
$rows = $this->_db->loadAssocList();
if (empty($rows))
{
$query = $this->_db->getQuery(true);
$query->select('#__npco_car.*')->from(array('#__npco_car, #__npco_useragahi, #__npco_user'));
$query->where('#__npco_car.car_id = ' . (int) $id);
$query->where('#__npco_user.id_user = #__npco_useragahi.id_user');
$query->where('#__npco_car.car_id = #__npco_useragahi.car_id');
$db->setQuery($sql);
$this->_db->setQuery($sql);
$rows = $this->_db->loadAssocList();
}
return $rows;
}
may be this is your issue..
Change your query as following
$sql="select *
from
#__npco_car,#__npco_namayeshgah,#__npco_agahi
where
#__npco_car.car_id='".$id."' and
#__npco_namayeshgah.id_namayeshgah=#__npco_agahi.id_namayeshgah and
#__npco_car.car_id=#__npco_agahi.car_id
";
$sql="select *
from
#__npco_car,#__npco_useragahi,#__npco_user
where
#__npco_car.car_id='".$id."' and
#__npco_user.id_user=#__npco_useragahi.id_user and
#__npco_car.car_id=#__npco_useragahi.car_id
";