MySQL NOW() in Doctrine DBAL insert? - mysql

I'm staring at http://doctrine-dbal.readthedocs.org/en/latest/reference/data-retrieval-and-manipulation.html#insert
I'd love to be able to do something like
$db->insert('mytable', [
'foo' => 'bar',
'created_on' => new MagicThatMakesNowWork()
]);
Is this impossible? The best solution I've seen is using PHP to get the datetime while setting the timezone, which is less than ideal. For some reason it seems only the ORM or query builder can handle expressions. I know in Zend I can do something like new Zend_Db_Expr('NOW()') and it knows by the object type not to quote NOW() in the built query. No query builder or ORM required.
Not sure if it's not possible or not documented well. The second answer on Doctrine DBAL: Updating timestamp field with 'NOW()' value shows a random string of datetime in the types array which seems weird/bad as well.

it seems you're trying to accomplish what the TIMESTAMP column type does automatically. That's been around for way longer than 2014. Use it, and stop trying to manage your created_on and updated_on fields manually. https://dev.mysql.com/doc/refman/5.1/en/datetime.html

A late answer but the easiest way I've found to do this is to run a query first to get the value of NOW() and then insert that string.
An example:
$now = $db->fetchColumn("SELECT NOW()");
$db->insert('table', array(
'field1' => $field1
,'created' => $now
));
A slightly less desirable alternative would be if you are able to make sure you PHP/MySQL times are in sync, you could always create the DateTime object in PHP and format it as a string ready for MySQL:
$created = new \Datetime('now', new \DateTimeZone('Europe/Paris'));
$created->format('Y-m-d H:i:s')

insert isn't much of an option. So the answer at Expression mysql NOW() in Doctrine QueryBuilder shows manually knowing what's coming for that variable.
This requires DBAL >= 2.5 which was recently released. You'd be out of luck in 2014. Note that datetime is a valid string, but doesn't appear to have a constant http://php.net/manual/en/pdo.constants.php.
public function insert($params) {
if (!isset($params[static::CREATED_ON])) {
$params[] = [static::CREATED_ON, new \Datetime('now'), 'datetime'];
}
if (!isset($params[static::MODIFIED_ON])) {
$params[] = [static::MODIFIED_ON, new \Datetime('now'), 'datetime'];
}
$conn = $this->_dbs['write'];
$query_builder = $conn->createQueryBuilder();
$query_builder->insert(static::TABLE);
foreach ( $params as $location => $data ) {
$field = $data[0];
$value = $data[1];
$type = (isset($data[2])) ? $data[2] : \PDO::PARAM_STR;
$prep = (isset($data[3])) ? $data[3] : '?';
$query_builder
->setValue($field, $prep)
->setParameter($location, $value, $type);
}
$return = $query_builder->execute();
if (!$return) {
throw new \Exception("Failed to execute statement");
}
return $conn->lastInsertId();
}
public function update($params, $where) {
$conn = $this->_dbs['write'];
$query_builder = $conn->createQueryBuilder();
$query_builder->update(static::TABLE);
foreach ( $params as $location => $data ) {
// can do arbitrary expressions via ['field', null, null, 'ANY EXPRESSION YOU WANT']
// ie ['votes', null, null,'votes=votes+25']
// or ['votes', '1', \PDO::PARAM_INT, 'votes + ?']
$field = $data[0];
$value = $data[1];
$type = (isset($data[2])) ? $data[2] : \PDO::PARAM_STR;
$prep = (isset($data[3])) ? $data[3] : '?';
$query_builder
->set($field, $prep)
->setParameter($location, $value, $type);
}
$query_builder->where($where);
return $query_builder->execute();
}

Related

Unique Profile Slug with PHP and PDO

I am using a class to generate a string name profile to slug and next use an SQL command to tell me whats the unique value to use in insert command, the problem is the command isn't working properly, sometimes it is possible to return a value which already exist...
Thats the class I am using to generate the slug: (composer require channaveer/slug)
And this the example code:
use Channaveer\Slug\Slug;
$string = "john doe";
$slug = Slug::create($string);
$profile_count_stmt = $pdo->prepare("
SELECT
COUNT(`id`) slug_count
FROM
`advogados_e_escritorios`
WHERE
`slug_perfil` LIKE :slug
");
$profile_count_stmt->execute([
":slug" => "%".$slug."%"
]);
$profile_count = $profile_count_stmt->fetchObject();
if ($profile_count && $profile_count->slug_count > 0) {
$profile_increment = $profile_count->slug_count + 1;
$slug = $slug . '-' . $profile_increment;
}
echo 'Your unique slug: '. $slug;
// Your unique slug: john-doe-5
This is the content of the table when the script run:
Do you know how can I improve the select command to prevent it to return existing slugs from DB?
Ok finally found a solution... Heres the code for who wants to generate unique profile slugs using PHP - PDO and MySQL
$string = "John Doe";
$string = mb_strtolower(preg_replace('/\s+/', '-', $string));
$slug = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
$pdo = Conectar();
$sql = "
SELECT slug_perfil
FROM advogados_e_escritorios
WHERE slug_perfil
LIKE '$slug%'
";
$statement = $pdo->prepare($sql);
if($statement->execute())
{
$total_row = $statement->rowCount();
if($total_row > 0)
{
$result = $statement->fetchAll();
foreach($result as $row)
{
$data[] = $row['slug_perfil'];
}
if(in_array($slug, $data))
{
$count = 0;
while( in_array( ($slug . '-' . ++$count ), $data) );
$slug = $slug . '-' . $count;
}
}
}
echo $slug;
//john-doe-1
You should check if the slug exists or not from your database. If it already exists then you can append some random string like the following
$slug = Slug::create($string);
$slugExists = "DB query to check if the slug exists in your database then you may return the count of rows";
//If the count of rows is more than 0, then add some random string
if($slugExists) {
/** NOTE: you can use primary key - id to append after the slug, but that has to be done after you create the user record. This will help you to achieve the concurrency problem as #YourCommenSense was stating. */
$slug = $slug.time(); //time() function will return time in number of seconds
}
//DB query to insert into database
I have followed the same for my blog articles (StackCoder) too. Even LinkedIn follows the same fashion.
Following is screenshot from LinkedIn URL

How do I use the between() after find() [duplicate]

Is it possible to do a "BETWEEN ? AND ?" where condition LIKE in cakephp 2.5?
In cakephp 2.5 I write something like
'conditions' => ['start_date BETWEEN ? AND ?' => ['2014-01-01', '2014-12-32']]
how can I migrate that?
additionally I would write something like
'conditions' => [ '? BETWEEN start_date AND end_date'] => '2014-03-31']
Expressions
Between expression are supported out of the box, however they only support the first case without additional fiddling:
$Query = $Table
->find()
->where(function($exp) {
return $exp->between('start_date', '2014-01-01', '2014-12-32', 'date');
});
If you'd wanted to handle the second case via the between method, then you'd have to pass all values as expressions, which can easily go wrong, as they will not be subject to escaping/parameter binding in that case, you'd have to do that on your own (which is anything but recommended! See the security notes in the manual for PDO::quote()), something along the lines of:
use Cake\Database\Expression\IdentifierExpression;
use Cake\Database\Expression\QueryExpression;
use Cake\ORM\Query;
// ...
$Query = $Table
->find()
->where(function(QueryExpression $exp, Query $query) {
return $exp->between(
$query->newExpr(
$query->connection()->driver()->quote(
'2014-03-31',
\PDO::PARAM_STR
)
),
new IdentifierExpression('start_date'),
new IdentifierExpression('end_date')
);
});
That might feel a little inconvenient for such a basic SQL expression that is supported by all SQL dialects that CakePHP ships with, so you may have a reason here to use a raw SQL snippet with value bindig instead.
It should be noted however that expressions are often the better choice when it comes to for example cross dialect support, as they can be (more or less) easily transformed at compile time, see the implementations of SqlDialectTrait::_expressionTranslators(). Also expressions usually support automatic identifier quoting.
Value binding
Via manual value binding you can pretty much create anything you like. It should however be noted that whenever possible, you should use expressions instead, as they are easier to port, which happens out of the box for quite a few expressions already.
$Query = $Table
->find()
->where([
'start_date BETWEEN :start AND :end'
])
->bind(':start', '2014-01-01', 'date')
->bind(':end', '2014-12-31', 'date');
That way the second case can also be solved very easily, like:
$Query = $Table
->find()
->where([
':date BETWEEN start_date AND end_date'
])
->bind(':date', '2014-03-31', 'date');
A mixture of both (safest and most compatible approach)
It's also possible to mix both, ie use an expression that makes use of custom bindings, something along the lines of this:
use Cake\Database\Expression\IdentifierExpression;
use Cake\Database\Expression\QueryExpression;
use Cake\ORM\Query;
// ...
$Query = $Table
->find()
->where(function(QueryExpression $exp, Query $query) {
return $exp->between(
$query->newExpr(':date'),
new IdentifierExpression('start_date'),
new IdentifierExpression('end_date')
);
})
->bind(':date', '2014-03-31', 'date');
That way you could handle the second case using possibly portable expressions, and don't have to worry about quoting/escaping input data and identifiers manually.
Regular comparison using array syntax
All that being said, in the end BETWEEN is just the same as using two separate simple conditions like this:
$Query = $Table
->find()
->where([
'start_date >=' => '2014-01-01',
'start_date <=' => '2014-12-32',
]);
$Query = $Table
->find()
->where([
'start_date >=' => '2014-03-31',
'end_date <=' => '2014-03-31',
]);
But don't be mad, if you read all the way down to here, at least you learned something about the ins and outs of the query builder.
See also
Cookbook > Database Access & ORM > Query Builder > Advanced Conditions
API > \Cake\Database\Query::bind()
Currently there seems to be only two options. The core now supports this out of the box, the following is just kept for reference.
Value binding (via the database query builder)
For now the ORM query builder (Cake\ORM\Query), the one that is being retrived when invoking for example find() on a table object, doesn't support value binding
https://github.com/cakephp/cakephp/issues/4926
So, for being able to use bindings you'd have to use the underlying database query builder (Cake\Database\Query), which can for example be retrived via Connection::newQuery().
Here's an example:
$conn = ConnectionManager::get('default');
$Query = $conn->newQuery();
$Query
->select('*')
->from('table_name')
->where([
'start_date BETWEEN :start AND :end'
])
->bind(':start', new \DateTime('2014-01-01'), 'date')
->bind(':end', new \DateTime('2014-12-31'), 'date');
debug($Query->execute()->fetchAll());
This would result in a query similar to this
SELECT
*
FROM
table_name
WHERE
start_date BETWEEN '2014-01-01' AND '2014-12-31'
A custom expression class
Another option would be a custom expression class that generates appropriate SQL snippets. Here's an example.
Column names should be wrapped into identifier expression objects in order to them be auto quoted (in case auto quoting is enabled), the key > value array syntax is for binding values, where the array key is the actual value, and the array value is the datatype.
Please note that it's not safe to directly pass user input for column names, as they are not being escaped! Use a whitelist or similar to make sure the column name is safe to use!
Field between values
use App\Database\Expression\BetweenComparison;
use Cake\Database\Expression\IdentifierExpression;
// ...
$between = new BetweenComparison(
new IdentifierExpression('created'),
['2014-01-01' => 'date'],
['2014-12-31' => 'date']
);
$TableName = TableRegistry::get('TableName');
$Query = $TableName
->find()
->where($between);
debug($Query->execute()->fetchAll());
This would generate a query similar to the one above.
Value between fields
use App\Database\Expression\BetweenComparison;
use Cake\Database\Expression\IdentifierExpression;
// ...
$between = new BetweenComparison(
['2014-03-31' => 'date'],
new IdentifierExpression('start_date'),
new IdentifierExpression('end_date')
);
$TableName = TableRegistry::get('TableName');
$Query = $TableName
->find()
->where($between);
debug($Query->execute()->fetchAll());
This on the other hand would result in a query similar to this
SELECT
*
FROM
table_name
WHERE
'2014-03-31' BETWEEN start_date AND end_date
The expression class
namespace App\Database\Expression;
use Cake\Database\ExpressionInterface;
use Cake\Database\ValueBinder;
class BetweenComparison implements ExpressionInterface {
protected $_field;
protected $_valueA;
protected $_valueB;
public function __construct($field, $valueA, $valueB) {
$this->_field = $field;
$this->_valueA = $valueA;
$this->_valueB = $valueB;
}
public function sql(ValueBinder $generator) {
$field = $this->_compilePart($this->_field, $generator);
$valueA = $this->_compilePart($this->_valueA, $generator);
$valueB = $this->_compilePart($this->_valueB, $generator);
return sprintf('%s BETWEEN %s AND %s', $field, $valueA, $valueB);
}
public function traverse(callable $callable) {
$this->_traversePart($this->_field, $callable);
$this->_traversePart($this->_valueA, $callable);
$this->_traversePart($this->_valueB, $callable);
}
protected function _bindValue($value, $generator, $type) {
$placeholder = $generator->placeholder('c');
$generator->bind($placeholder, $value, $type);
return $placeholder;
}
protected function _compilePart($value, $generator) {
if ($value instanceof ExpressionInterface) {
return $value->sql($generator);
} else if(is_array($value)) {
return $this->_bindValue(key($value), $generator, current($value));
}
return $value;
}
protected function _traversePart($value, callable $callable) {
if ($value instanceof ExpressionInterface) {
$callable($value);
$value->traverse($callable);
}
}
}
You can use one of following 2 methods.
Method 1 :
$start_date = '2014-01-01 00:00:00';
$end_date = '2014-12-31 23:59:59';
$query = $this->Table->find('all')
->where(function ($exp, $q) use($start_date,$end_date) {
return $exp->between('start_date', $start_date, $end_date);
});
$result = $query->toArray();
Method 2:
$start_date = '2014-01-01 00:00:00';
$end_date = '2014-12-31 23:59:59';
$query = $this->Table->find('all')
->where([
'start_date BETWEEN :start AND :end'
])
->bind(':start', new \DateTime($start_date), 'datetime')
->bind(':end', new \DateTime($end_date), 'datetime');
$result = $query->toArray();
I'm using it like this
$this->Table->find()->where(['data_inicio BETWEEN '.'\''.$data_inicio.'\''.' AND .'\''.$data_final.'\''.' ']);
Hello guys please use this query to get data on the basis of range of value
$query = $this->Leads->find('all',
array('conditions'=>array('postcode BETWEEN '.$postcodeFrom.' and'.$postcodeTo.''), 'recursive'=>-1));
debug($query);
print_r($query->toArray());

Set a value to null, when calling Zend_Db::update() and insert()

My question is the exact same as How to Set a Value to NULL when using Zend_Db
However, the solution given in that question is not working for me. My code looks like the following. I call updateOper on the Model class when update is clicked on the front end. Inside updateOper, I call another function trimData() where I first trim all whitespace and then I also check that if some of the fields are coming in empty or '' I want to set them to default values or NULL values. Therefore I am using new Zend_db_expr('null') and new Zend_db_expr('default') .
The code is as follows:
private function trimData(&$data ) {
//Trim whitespace characters from incoming data.
foreach($data as $key => $val)
{
$data[$key] = trim($val);
if($data['notes'] == '') {
error_log("set notes to null/default value");
$data['notes'] = new Zend_db_expr('DEFAULT');
}
}
}
public function updateOper($data, $id)
{
$result = 0;
$tData = $this->trimData($data);
error_log("going to add data as ".print_r($data, true));
$where = $this->getAdapter()->quoteInto('id = ?', $id);
$result = $this->update($data, $where);
return $result;
}
The error_log statement prints the $data array as follows:
[id] => 10
[name] => alpha
[notes] => DEFAULT
As a result, the notes column has value ='DEFAULT' instead of picking the default value given in the table definition.
I have been trying to figure out what is wrong, but have not been able to find a solution.
I would really appreciate your help.
Thanks so much!
Your $data['notes'] is being changed to the __toString() value of the Zend_Db_Expr instead of preserving the actual object.
Maybe the reference is clogging things up. Else you may need to move the expression declaration into the actual update query.

Parsing External Table Arguments in Wordpress

I have a client project that has posts assigned to their country of origin.
The client wants to be able to search the posts by continent and or region.
I have a separate table that assigns each country to its respective region, and I have the WP query that uses the resulting array:
$country_names = array('England','France','Germany',...); // this would be the result from fetching countries associated with a region.
$args = array(
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'country',
'value' => $country_names,
'compare' => 'IN'
)
)
);
$query = new WP_Query( $args );
What I'm having trouble with is the part in the middle. Normally, I'd use some standard PHP/MySQL to craft the array:
<?php
//Process incoming variable
if(!empty($_REQUEST['region'])){
$region = $_REQUEST['region'];
} else {
$region = NULL;
}
// Make a MySQL Connection
$query = "SELECT * FROM regions WHERE region='$region'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
echo $row['country'];
?>
However, I'm having trouble making it work within a WP template, since WP manages the incoming variables using its own internal functions.
Can anyone help me to connect the two together? I'm sure I'm overlooking some simple step here, or else I'm not using some built-in WP function.
Any help is appreciated.
Thanks!
ty
Add this in your functions.php
add_filter( 'query_vars', 'addnew_query_vars', 10, 1 );
function addnew_query_vars($vars)
{
$vars[] = 'region'; // region is the variable you want to add
$vars[] = 'anotherVar';
return $vars;
}
Then get it
$region=get_query_var('region')
Update
$regions = $wpdb->get_results("SELECT ".$region." FROM `".$wpdb->regions."`");
if($regions)
{
foreach($regions as $region)
{
// your code
}
}

Trouble insert date form to mysql in drupal 7

hi im having little trouble at inserting date from drupal to mysql
here the code that i'm trying
.....
$form['kotak']['tgl'] = array(
'#type' => 'date',
'#title' => t('Tanggal'),
);
.....
function awal_form_submit($form,&$form_state){
global $user;
$entry = array(
'tanggal' => $form_state['values']['tgl'],
);
$tabel = 'jp_1';
$return = insert_form($entry,$tabel);
}
.....
function insert_form($entry,$tabel){
$return_value = NULL;
try {
$return_value = db_insert($tabel)
->fields($entry)
->execute();
}
.....
everytime i'm submit, error code like this
db_insert failed. Message = SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1, query= INSERT INTO {jp_1} (tanggal) VALUES (:db_insert_placeholder_0_month, :db_insert_placeholder_0_day, :db_insert_placeholder_0_year)
any suggestion or correction?
From the mysql error it looks like the table you created has required fields (a columns Null property is set to 0, which means that there must be a value for tha column for every row you want to insert)
Check whether there are any columns which have null set to 0.
From your example I can't see what you're trying to achieve, but in many cases it's not necessary to write into db tables manually (using db_insert()) as you can get the same result easier by creating a content type (node type) which handles a lot of functionality for you.
I hope that helps, Martin
i'm finally managed to find the answer, all i need is download "Date" module and activate its "Date API". Here the code
.....
$datex = '2005-1-1';
$format = 'Y-m-d';
$form['kotak']['tgl'] = array(
'#type' => 'date_select',
'#default_value' => $datex,
'#date_format' => $format,
'#date_year_range' => '-10:+30',
'#title' => t('Tanggal'),
);
.....
function awal_form_submit($form,&$form_state){
global $user;
$entry = array(
'tanggal' => $form_state['values']['tgl'],
);
$tabel = 'jp_1';
$return = insert_form($entry,$tabel);
}
.....
function insert_form($entry,$tabel){
$return_value = NULL;
try {
$return_value = db_insert($tabel)
->fields($entry)
->execute();
}
.....
and now i have no problem delivering to mysql.
Hope that will help other drupal newbie developer like me. Thanks :D