Cakephp 3 case sensitive query - mysql

$date = date("Y-m-d");
$prev_date = date('m-d-Y', strtotime($date .' -1 day'));
$q = "SELECT `id`, `external_id`, `status`, DATE_FORMAT(from_unixtime(`created`),'%m-%d-%Y') as crt, `extras`
FROM `gshuplogs` WHERE DATE_FORMAT(from_unixtime(`created`),'%m-%d-%Y') = '$prev_date' and
(BINARY `status` in ('success','DEFERRED') or `status` IS NULL)";
$conn = \Cake\Datasource\ConnectionManager::get('default');
$res = $conn->execute($q)->fetchAll('assoc');
debug($res);exit;
The above query I have written in mysql now I just wanted to write in cakephp 3.
I have tried
$res = $this->Gshuplogs->find()->select([
'id', 'external_id', 'status', 'created'
])->where([
"DATE_FORMAT(from_unixtime(`created`),'%m-%d-%Y')" => $prev_date,
'OR' => [
['LOWER status' => 'success'],
['status' => 'DEFERRED'],
['status IS NULL']
]
]);
AND
$res = $this->Gshuplogs->find()->select([
'id', 'external_id', 'status', 'created'
])->where([
"DATE_FORMAT(from_unixtime(`created`),'%m-%d-%Y')" => $prev_date,
'OR' => [
['BINARY status' => 'success'],
['status' => 'DEFERRED'],
['status IS NULL']
]
]);
But it is throwing error.
Error: SQLSTATE[42000]: Syntax error or access violation: 1064 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
'`),'%m-%d-%Y'`) = '06-01-2016' AND (`LOWER` status 'success' OR `status` =
'DEFE' at line 1

Thanks for your response. I got the solution.
$date = date("Y-m-d");
$prev_date = date('m-d-Y', strtotime($date .' -1 day'));
$res = $this->Gshuplogs->find()->select([
'id', 'external_id', 'status', "created"
])->where([
"FROM_UNIXTIME(`created`,'%m-%d-%Y')" => $prev_date,
'OR' => [
['BINARY(status) in ' => ['success','DEFERRED']],
['status IS NULL']
]
]);
debug($res->toArray());exit;

Related

CakePHP - Virtual field issue using Paginator?

The following SQL query in phpMyAdmin returns exactly what I expect:
SELECT d.office_id, o.city, sum(d.`nb_followers`) as total_followers FROM `data` as d
LEFT JOIN offices as o on d.office_id = o.id
WHERE d.`year` = 2014 AND d.`month` = 10 AND d.`day` = 01
Group by d.`office_id`
ORDER BY total_followers DESC limit 10
In my Controller :
$this->Paginator->virtualFields = array(
'followers' => 'SUM(Data.nb_followers)',
'id' => 'Office.office_id'
);
$this->Paginator->settings = array(
'fields' => array('id', 'Office.city', 'Data.followers'),
'joins' => array(
array(
'table' => 'data',
'alias' => 'Data',
'type' => 'inner',
'conditions' => array(
'Office.id = Data.office_id',
'year = ' . date('Y', mktime(0, 0, 0, date('m'), 1, date('Y'))),
'month = ' . date('m', mktime(0, 0, 0, date('m'), 1, date('Y'))),
'day = 01'
)
)
),
'group' => array('Data.id'), //Mal positionné à la base mais vérifier si activé n'impacte pas les résultats
'order' => array('Data.followers' => 'desc')
//'limit' => 1
);
$dataTop = $this->paginate('Office');
But I get this Error :
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Data.followers' in 'field list'
SQL Query: SELECT Office.id, Office.city, Data.followers FROM ebd.offices AS Office inner JOIN ebd.data AS Data ON (Office.id = Data.office_id AND year = 2014 AND month = 10 AND day = 01) WHERE 1 = 1 GROUP BY Data.id LIMIT 20
Need Your Help Thank you
I did a test in my web app and putted a virtual field in one of my models. The virtual field was a field from a related table and it seems that it does not work. It outputs an sql error. So i remembered from the documentation the subquery command.
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#sub-queries
I dont know if this works but i will try to give you an example that might suite your needs
$db = $this->Office->getDataSource();
$subQuery = $db->buildStatement(
array(
'fields' => array('followers' => 'SUM(Data.nb_followers)'),
'table' => 'datas',
'alias' => 'Data'
),
$this->office);
$fields[] = $subQuery;
$fields[] = 'id';
$fields[] = 'Office.city';
I hope this guides you to the right direction.

Selecting column alias filled with NULLs with Zend_Db

Is there any way you can select NULL as a column with Zend_db.
To make it clear, you could write a query:
SELECT id, name, age, NULL as ssn from dummy_table;
The result would have 4 columns id, name, age and ssn(filled with null). Is there any way to do this in Zend_Db. My guess was:
$columns = [
'id' => 'id',
'name' => 'name',
'age' => 'age',
NULL => 'ssn'
];
$select = $this->_db->select();
$select
->from('dummy_table', $columns)
But that won't work it will generate:
SELECT `dummy_table`.`id` AS `id`, `dummy_table`.`name` AS `name`, `dummy_table`.`age` AS `age`, `dummy_table`.`ssn` AS `` FROM `dummy_table`;
This query will fail. Is there any way you could do this using only Zend_Db ($this->_db->query('') is not an option)?
Have you tried using new Zend_Db_Expr('NULL') ?
You could do :
$null = new Zend_Db_Expr('NULL');
$columns = [
'id' => 'id',
'name' => 'name',
'age' => 'age',
$null => 'ssn'
];
$select = $this->_db->select();
$select
->from('dummy_table', $columns);

DATEDIFF in YII MYSQL

$criteria = new CDbCriteria();
$criteria->addCondition(array('where' => 'select DATEDIFF(CURDATE(),t.due_date) < 0'));
$dataProvider = new CActiveDataProvider('Loan', array(
'criteria' => $criteria
));
$this->render('index', array(
'dataProvider' => $dataProvider,
));
This is my code, I want to retreive all data from 'Loan' model with some criteria, but I found problem like so:
CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1305 FUNCTION libraryng.DATEDIFF does not exist. The SQL statement executed was: SELECT COUNT(*) FROM `loans` `t` WHERE (select DATEFIFF(CURDATE(),t.due_date) < 0)
I hope someone can help me.
change this line to
$criteria->condition('DATEDIFF(CURDATE(),`t`.due_date) < 0');

Two prepared statements on one page - first works, second fails

I'm using MDB2 for prepared statements. I'm using the name-based example from the PEAR MDB2 site as a guide, and this is what I have so far:
$q = '
UPDATE
abc_news
SET
newstitle = :newstitle,
categoryid = :categoryid,
facilityid = :facilityid,
user_id_mod = :user_id_mod,
user_id_add = :user_id_add,
display = :display,
locked = :locked,
datemodified = NOW()
WHERE
newsid = :newsid
';
$types = array(
'text',
'integer',
'integer',
'integer',
'integer',
'integer',
'integer',
'integer',
);
$res = $mdb2_dbx->prepare($q, $types,MDB2_PREPARE_MANIP);
$data = array(
'newstitle' => $n_newstitle,
'categoryid' => $n_categoryid,
'facilityid' => $n_facilityid,
'display' => 1,
'locked' => 1,
'user_id_add' => $n_user_id_add,
'user_id_mod' => $n_user_id_mod,
'newsid' => $newsid,
);
$affected_rows = $statment->execute($data);
if (PEAR::isError($res))
die('error');
$statement->free();
$q = '
UPDATE
abc_news_text
SET
newstext = :newstext
WHERE
newsid = :newsid
';
$types = array(
'text',
'integer',
);
$statment = $mdb2_dbx->prepare($q, $types,MDB2_PREPARE_MANIP);
$data = array(
'newstext' => $n_newstext,
'newsid' => $newsid,
);
$affected_rows = $statment->execute($data);
if (PEAR::isError($res))
die('error');
$statement->free();
The first query works - an autoincremented $newsid is printed to the screen (it increases with each new submission).
Directly below, I get this error:
Fatal error: Call to undefined method MDB2_Error::execute() in news.php on line 160
Line 160 is the second $affected_rows = $statment->execute($data); line.
I'm freeing up the statement, and the syntax appears to be the same on both prepared statements.
What am I doing wrong here?
that is because You are getting an MDB2_ERROR object not a statement object. Your prepare() obviously didn't work and you are not checking for the success of the prepare() at all to know this.
Also, I am not sure how your first is working since you set the prepare result to $res variable instead of $statment. I also notice your variable name $statment has no e (not sure if this was a typo).

wordpress query 2 sets of meta keys

I am trying to do a custom sql query to get 2 lots of post_meta keys and there values. Here is my code:
<?php
$queried_post = get_post($post_id);
$title = $term->name ;
$userid = $current_user->user_email;
$result = mysql_query("SELECT * FROM wp_postmeta WHERE meta_key='user_programme_name' AND meta_value='".$title."' AND meta_key='user_email' AND meta_value='".$userid."' ");
$num_rows = mysql_num_rows($result);
if ($num_rows > 0 ) {
?>
<p style="width:430px;">You have already requested a place on this course</p>
<?php } ?>
The first part of the query works when i jsut query the first set of keys and values:
meta_key='user_programme_name' AND meta_value='".$title."'
But as soon as i add the second lot:
AND meta_key='user_email' AND meta_value='".$userid."'
It doesn't work. Is there something I'm doing wrong?
Any help would be greatly appreciated.
Cheers, Dan
Use something like this :
$args = array( 'post_type' => 'myposttype',
'posts_per_page' => …,
'offset' => …,
'meta_query'=>array(
'relation' => 'AND',
array(
'key'=>'_first_key',
'value'=> youvalue,
'type' => 'DATE', // etc.
'compare' => '='
),
array(
'key'=>'_second_key',
'value'=> youvalue,
'type' => 'DATE', // etc.
'compare' => '='
)
)
);
$yourloop = new WP_Query( $args );
Fix your SQL syntax for selecting multiple values on the same column:
<?php
$result = mysql_query("SELECT * FROM wp_postmeta WHERE meta_key IN ('user_programme_name', 'user_email') AND meta_value IN ('.$title.', '.$userid.') ");
?>