How use between cakephp - mysql

it does not return any error but neither any row but if there are fields but it does not collect them, which may be failing the query
$tarea = $this->Signs
->find('all', [
'conditions'=> array(
'date_inicio BETWEEN "' .
$horaInicio->format('Y-m-d H:i:s') .
'" and "' .
$horaFin->format('Y-m-d H:i:s') .
'"'
)
])
->where([
'user_id' => $horario->user_id,
'date_fin IS NOT' => null
]);
This works if I remove the condition between, but if I put it it doesn't give an error but it doesn't return anything.

Related

Use OR conditions on associated model in CakePHP 3

I have 3 models, the base model is Jobs and Customers, Contacts are the models associated with jobs. Here is the association.
$this->belongsTo('Customers', [
'className' => 'Customers',
'foreignKey' => 'customer_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Contacts', [
'className' => 'Contacts',
'foreignKey' => 'contact_id',
'joinType' => 'INNER'
]);
I want to search a text in all the 3 tables and return the job records which are having the search text at least any one of the tables... I want to achieve this using CakePHP's ORM...
This is the raw SQL you may want as the reference,
$searchText = 'Bikash';
$JobQ->query("SELECT *
FROM Jobs
LEFT JOIN Customer ON Jobs.CustomerID=Customers.CustomerID
LEFT JOIN Contacts ON Jobs.ContactID=Contacts.ContactID
WHERE (
Job.JobName LIKE '%" . $searchText . "%' or
Customer.Name LIKE '%" . $searchText . "%' or
Contact.FirstName LIKE '%" . $searchText . "%' or
Contact.Surname LIKE '%" . $searchText . "%');
If you are following cake conventions should be simply:
$jobs = $this->Jobs->find()
->contain(['Customers', 'Contacts'])
->where([
'OR' => [
'Jobs.JobName LIKE' => '%" . $searchText . "%',
'Customers.Name LIKE' => '%" . $searchText . "%',
'Contacts.FirstName LIKE' => '%" . $searchText . "%',
'Contacts.Surname LIKE' => '%" . $searchText . "%'
]
]);
or using query expressions
$jobs = $this->Jobs->find()
->contain(['Customers', 'Contacts'])
->where(function ($exp, $query) {
return $exp->or_([
$exp->like('Jobs.JobName', "%$searchText%"),
$exp->like('Customers.Name, "%$searchText%"),
$exp->like('Contacts.FirstName, "%$searchText%"),
$exp->like('Contacts.Surname', "%$searchText%")'
]);
});

Optimize Multiple database update

I am using laravel in my app.
So now I need to update many rows on DB once a day with Cron job.
If I will use the update option built-in laravel I need to do something like this:
// for example, the update info in array
$arrayToUpadte = [
[
'numberId' => '0500000000',
'usagePer' => '4.5'
],
[
'numberId' => '0500000001',
'usagePer' => '5.6'
],
[
'numberId' => '0500000002',
'usagePer' => '8.1'
],
[
'numberId' => '0500000003',
'usagePer' => '0.3'
]
];
// update will do one query to db every update!!
foreach( $arrayToUpadte as $updates ){
\App\Phonelines::where( 'numberId', '=', $updates['numberId'] )->update([
'usagePer' => $updates['usagePer']
]);
}
So my question is how I can Improve code to have as few queries as possible?
If I have this in a regular PHP project I would do it like this:
$newValues = [];
foreach( $arrayToUpadte as $updates ){
$newValues[] = $updates['numberId'] . ',' . $updates['usagePer'];
}
$newValues = implode( '),(', $newValues );
$mysqli -> query( "
INSERT INTO `phonelines` ( `numberId`, `usagePer` ) VALUES (" . $newValues . ")
ON DUPLICATE KEY
UPDATE `usagePer` = VALUES( `usagePer` );
" );
Is there a way to do this in Laravel's Framework?
you can use this :
DB::raw("INSERT INTO `phonelines` ( `numberId`, `usagePer` )
VALUES (" . $newValues . ") ON DUPLICATE KEY
UPDATE `usagePer` = VALUES( `usagePer` )") ;

php : show error on mysql query using concatenation

I try to make new datatables and following this tutorial.
But, I got an error message :
"Error occuered during query execution: (<small>SELECT a.idrec,a.date, a.model, a.serial, a.item,a.symptom, a.remark
FROM second_sampling AS a
WHERE 1=1 ORDER BY LIMIT , </small>): 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 'LIMIT ,' at line 3";
the syntax is :
$requestData= $_REQUEST;
$columns = array(
// datatable column index => database column name
0 => 'idrec',
1 => 'date',
2 => 'model',
3 => 'serial',
4 => 'item',
5 => 'symptom',
6 => 'remark'
);
$sql = "SELECT a.idrec,a.date, a.model, a.serial, a.item,a.symptom, a.remark
FROM second_sampling AS a
WHERE 1=1";
if( !empty($requestData['search']['value']) ) { // if there is a search parameter, $requestData['search']['value'] contains search parameter
$sql.=" AND ( a.date LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR a.model LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR a.serial LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR a.item LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR a.symptom LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR a.remark LIKE '".$requestData['search']['value']."%' )";
}
$query=mysql_query($sql) or _doError(_ERROR30 . ' (<small>' . htmlspecialchars($sql) . '</small>): ' . mysql_error() );
$totalFiltered = mysql_num_rows($query);
$sql. =" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." ";
$query=mysql_query($sql) or _doError(_ERROR30 . ' (<small>' . htmlspecialchars($sql) . '</small>): ' . mysql_error() );
try to close the root cause and put:
<?php
echo "<pre>";
print_r($_REQUEST);
echo "</pre>";
?>
then show :
{"draw":0,"recordsTotal":49,"recordsFiltered":49,"data":[]}
Array( [sEcho] => 1 [iColumns] => 7 [sColumns] => ,,,,,, [iDisplayStart] => 0 [iDisplayLength] => 10
Your vars
$columns[$requestData['order'][0]['column']]
$requestData['start']
$requestData['length']
so the
$sql. =" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".
$requestData['order'][0]['dir'].
" LIMIT ".$requestData['start']." ,".$requestData['length']." ";
produce wrong query clause
ORDER BY LIMIT ,
In the output SQL there should be a column name between the ORDER BY and the LIMIT, and then two numbers separated by a comma after the LIMIT.
The fact this is not happening seems to indicate that the variable $requestData is empty, or at least not filled with the values you were expecting.
I would try:
var_dump($requestData);
to find out what is really in the variable $requestData.
Your Statement is invalid
WHERE 1=1 ORDER BY LIMIT ,
This part is the problem:
$sql. =" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." ";
The requestData $columns[$requestData['order'][0]['column']],
$requestData['order'][0]['dir'],
$requestData['start'],
and $requestData['length'] is empty.

Opencart retriving data from 2 tables

I´m trying to join 2 tables in opencart to make an sales report that specifies taxes (by class, there can be many tax%) for every order. I can only get the values from 1 table, but not 2.
How should I do this?
<?php $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "order`, `" . DB_PREFIX . "order_total`");
$ordersr = array();
// Check if there are any rows returned from the query
if ($query->num_rows > 0) {
// Loop through the returned rows for processing
foreach ($query->rows as $result) {
$ordersr[] = array(
'order_id' => $result['order_id'],
'invoice_no' => $result['invoice_no'],
'total' => $result['total'],
'order_status_id' => $result['order_status_id'],
'date_added' => $result['date_added'],
'date_modified' => $result['date_modified'],
'firstname' => $result['firstname'],
'lastname' => $result['lastname'],
'payment_country' => $result['payment_country'],
'payment_method' => $result['payment_method'],
'payment_code' => $result['payment_code'],
'shipping_method' => $result['shipping_method'],
'shipping_code' => $result['shipping_code'],
'currency_code' => $result['currency_code'],
'currency_value' => $result['currency_value'],
'order_status_id' => $result['order_status_id'],
'date_payed' => $result['date_payed']
);
}
} ?>

PDO inserting and updating

So after my recent topic i learned about PDO. I'm trying my best to understand it and thats working to. But now the problem is that my new pdo script wont insert and update if exists in database. Now i'm asking it here because i'm a starter in PDO and i'm trying my best on it.
Now this is the code i'm using.
$db->prepare(
'INSERT INTO track (`rsname`, `overallranknow`, `overalllevelnow`, `overallxpnow` )' .
'VALUES (' .$name. '. ' .$Overalln. ', ' .$Overall[1]. ', ' .$Overall2. ') '.
'ON DUPLICATE KEY UPDATE ' .
"rsname = ' .$name. '" .
"overallranknow = ' .$Overalln. ' " .
"overalllevelnow = ' .$Overall[1].' " .
"overallxpnow = ' .$Overall2. ' "
);
The code is like doing nothing now
-it is not inserting into the database.
-it is not updating into the database.
Also my database connect file is this
<?php
$config['db'] = array(
'host' => 'localhost',
'username' => '',
'password' => '',
'dbname' => ''
);
$db = new PDO('mysql:host=' . $config['db'] ['host'] . ';dbname=' . $config['db'] ['dbname'], $config['db'] ['username'], $config['db'] ['password'] );
Maybe i'm posting mutch question's here and i know but i want to learn it.
~Kev (bad english = sorry)
A prepared statement needs to be executed in order to actually hit the database.
You should adjust it to look more like this:
$sth = $db->prepare(
'INSERT INTO track (`rsname`, `overallranknow`, `overalllevelnow`, `overallxpnow` )' .
'VALUES (:name, :Overalln, :Overall1, :Overall2) '.
'ON DUPLICATE KEY UPDATE ' .
"rsname = :name" .
"overallranknow = :Overalln" .
"overalllevelnow = :Overall1" .
"overallxpnow = :Overall2"
);
$sth->execute(array('name' => $name, 'Overalln' => $Overalln, 'Overall1' => $Overall[1], 'Overall2' => $Overall[2]));