How to display data from mysql using condition date NOW - mysql

There any one know how to implementation my sql code using data record
SELECT *
FROM `jadwal`
WHERE YEAR(tgl) = YEAR(NOW())
AND MONTH(tgl) = MONTH(NOW())
AND DAY(tgl) = DAY(NOW())
Thanks in advance

You can do it as follows -
$where = array('YEAR(tgl)' => YEAR(NOW()),
'MONTH(tgl)' => MONTH(NOW()),
'DAY(tgl)' => DAY(NOW())
);
$this->db->select('*');
$this->db->where($where);
$query = $this->db->get('jadwal');
$res1 = $query->result(); // as object
$res2 = $query->result_array(); // as array
try and let me know.

Related

Get data from specific timestamp Database laravel-api

i try to get data from specific timestamp into database DT.
i try this but not work
code :
Route::get('/l', function(){
$day = date('Y-m-d H:i:s', strtotime($_GET['day']));
$users = DB::select('select * from DT where (`timestamp` = "'.$day.'")' );
return $users;
})->middleware('auth:api');
in postman i put into params : day 2020-07-01
Any help?
Solved !
Route::get('/l', function(){
$day = date('Y-m-d ', strtotime($_GET['day']));
$users = DB::select('select * from DT where (`timestamp` like "'.$day.'%")' );
})->middleware('auth:api');

adding a condition to a WHERE clause based on a passed variable value mysql

I am a relative novice and could use some help with this problem.
This will be used in a search filter situation.
Users need to search by a value and 1 or more other values passed by the search form.
$name = $_POST['name'];
$sdate = $_POST['sdate'];
$startdate = $_POST['startdate'];
$enddate = $_POST['enddate'];
$vehicle = $_POST['vehicle'];
$triptype = $_POST['triptype'];
If any of these values are '' I do not want them in the query, If they contain a value I do want them in the query.
SELECT * FROM form_data WHERE `resp_person` = '$name',
IF $sdate != '' then `sdate` = '$sdate',
IF $startdate != '' then `sdate` = *all values between $startdate and $enddate*,
IF $triptype != '' then `triptype` = '$vehicle',
IF $vehicle != '' then `vehicle` = '$vehicle', `sdate`
ORDER BY `sdate` DESC, `stime` DESC")
I know the code is wrong but it should give you a good idea of what I am trying to accomplish. Any guidance would be greatly appreciated.
A better way is to not use string concatenation to build the entire query, but rather use an sql library that supports prepared statements, such as PDO.
$pdo = new PDO('... connection string ...', username, password);
$where = '';
$possible_values = array('name', 'sdate', 'startdate', 'enddate', 'vehicle', 'triptype' );
$params = array();
foreach($possible_values as $val)
{
if(isset($_POST[$val]))
{
$params[] = $_POST[$val];
if($where == '')
{
$where = "WHERE $val = ?";
}
else
{
$where .= " AND $val = ?";
}
}
}
$stmt = $pdo->prepare("SELECT * FROM form_data " . $where);
$stmt->execute($params);
In cases like this, I prefer to build the query in pieces...
$wheres = array(); // Collect things to AND together
if ($searchterm != 'All') $wheres[] = "subject LIKE '%searchterm'";
if (...) $wheres[] = "...'";
...
if (count($wheres) > 0)
$where_str = "WHERE " . implode(' AND ', $wheres);
else
$where_str = '';
$order_str = (...) ? "ORDER BY ..." : '';
$limit_str = $limit ? "LIMIT $limit" : '';
$query = "SELECT ... FROM foo $where_str $order_str $limit_str";
Oh, and don't forget to use escape the strings on any data coming in from a form -- else a user can do nasty things to the SQL statement!

Convert this SQL query to Codeigniter Active Record

This is the query that I need to convert
SELECT pdg_matriculas.id_matricula, aluno.nome_aluno, pdg_serie.nome_serie, pdg_turma.nome_turma, aluno.status_aluno, pdg_matriculas.ano_letivo
FROM pdg_matriculas, pdg_serie, pdg_turma, aluno
WHERE pdg_matriculas.id_aluno = aluno.id_aluno
AND pdg_matriculas.id_serie = pdg_serie.id_serie
AND pdg_matriculas.id_turma = pdg_turma.id_turma
ORDER BY `aluno`.`nome_aluno` ASC
LIMIT 0 , 30
I tried to use direct query, It did not work.
$this->db->select('SELECT pdg_matriculas.id_matricula, aluno.nome_aluno, pdg_serie.nome_serie, pdg_turma.nome_turma, aluno.status_aluno, pdg_matriculas.ano_letivo
FROM pdg_matriculas, pdg_serie, pdg_turma, aluno
WHERE pdg_matriculas.id_aluno = aluno.id_aluno
AND pdg_matriculas.id_serie = pdg_serie.id_serie
AND pdg_matriculas.id_turma = pdg_turma.id_turma');
$this->db->limit(10);
$query = $this->db->get();
tried with Active Record and also failed
$this->db->select('T1.id_matricula, T2.nome_aluno, T3.nome_serie, T4.nome_turma, T2.status_aluno, T1.ano_letivo',FALSE);
$this->db->from('pdg_matriculas T1, aluno T2, pdg_serie T3, pdg_turma T4');
$this->db->where('T1.id_matricula','T2.id_aluno');
$this->db->where('T1.id_serie','T3.id_serie');
$this->db->where('T1.id_turma','T4.id_turma');
$this->db->order_by('T2.nome_aluno', 'asc');
$this->db->limit(10);
$query = $this->db->get();
Can anyone help me convert to Active Record?
Thanks!
Try this code:
$this->db->select('T1.id_matricula, T2.nome_aluno, T3.nome_serie, T4.nome_turma, T2.status_aluno, T1.ano_letivo',FALSE);
$this->db->from('pdg_matriculas as T1');
$this->db->join('aluno as T2','T1.id_matricula = T2.id_aluno');
$this->db->join('pdg_serie as T3','T1.id_serie = T3.id_serie');
$this->db->join('pdg_turma as T4','T1.id_turma = T4.id_turma');
$this->db->order_by('T2.nome_aluno', 'asc');
$this->db->limit(10);
$query = $this->db->get();
Sorry for the delay, now it worked, of course a few minor changes, more myth thanks to everyone and keep your reference.
$this->db->select('T1.id_matricula,aluno.nome_aluno,pdg_serie.nome_serie,pdg_turma.nome_turma,T1.ano_letivo,T1.id_aluno as id_aluno_m,aluno.id_aluno as id_aluno_a,aluno.status_aluno');
$this->db->from('pdg_matriculas T1');
$this->db->join('aluno', 'aluno.id_aluno = T1.id_aluno');
$this->db->join('pdg_serie', 'pdg_serie.id_serie = T1.id_serie');
$this->db->join('pdg_turma', 'pdg_turma.id_turma = T1.id_turma');
$page_data ['alunos_lista'] = $this->db->get ()->result_array ();
Worked Perfect

Symfony 1.4 select query with selected columns is not working

I want to run following query in symfony doctrine.
SELECT p.id AS id FROM skiChaletPrice p WHERE ski_chalet_id = ? AND month = ?
I wrote my doctrine query as following.
$q = Doctrine_Query::create()
->select('p.id AS id')
->from('skiChaletPrice p')
->andWhere('ski_chalet_id = ?', $chaletId)
->andWhere('month = ?', $from);
$result = $q->fetchOne();
if ($result->count() > 0) {
return $result->toArray();
} else {
return null;
}
But my result always include all columns in the table. What the issue? Please help me.
The issue is that fetchOne() will return a Doctrine object, which implicitly contains all the columns in the table. $result->toArray() is converting that doctrine object to an array, which is why you get all the columns.
If you only want a subset of column, don't hydrate an object, instead do something like this:
$q = Doctrine_Query::create()
->select('p.id AS id')
->from('skiChaletPrice p')
->andWhere('ski_chalet_id = ?', $chaletId)
->andWhere('month = ?', $from);
$results = $q->execute(array(), Doctrine::HYDRATE_SCALAR);
See http://docs.doctrine-project.org/projects/doctrine1/en/latest/en/manual/data-hydrators.html
This is how I should do it:
$result = Doctrine_Query::create()
->select('id')
->from('skiChaletPrice')
->andWhere('ski_chalet_id = ?', $chaletId)
->andWhere('month = ?', $from)
->limit(1)
->fetchOne(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR);
// result will be a single id or 0
return $result ?: 0;
// if you want array($id) or array() inseatd
// return (array) $result;

Make Zend\Db (zf2) between clause inclusive

I'm currently using Zend Framework 2 and a query with date ranges to obtain data out of a MySQL DB, and I came across the between clause that was previously not available in ZF1.
However, my code which looks something like this is not working correctly:
$dateStart = '2012-12-20';
$dateEnd = '2012-12-31';
$sql = new Sql($_db);
$select = $sql->select()
->from(array("t" => $table))
->columns(array("col1" => "col_as_1", "col2" => "col_as_2"));
$select->where->between("date", $dateStart, $dateEnd);
$stmt = $sql->prepareStatementForSqlObject($select);
$result = $stmt->execute()->getResource()->fetchAll(\PDO::FETCH_ASSOC);
Apparently the between clause is not inclusive, I can only get results until 2012-12-30, is there a way to make it inclusive? I've been taking a look at the ZF2 docs but they are not very helpful and running the same query on MySQL query browser returns all of the data I need.
So you can try lessThanOrEqualTo and greaterThanOrEqualTo.
Between doesn't seem to provide this functionality: between($identifier, $minValue, $maxValue)
If you trace out your query with $select->__toString() you can see the query as string.
I don't have ZF2 on my computer but I could imagine that between in ZF2 will output date > '2012-12-20' AND date < '2012-12-31'.
NOTE THIS : WHEN USING between on Mysql
date_column_name between 'startDate' AND 'endDate'
NOTE : you should want to insert +1 date to endDate . Because of when you insert 2015-05-18 date to endDate.you can not get data of 2015-05-18.So you need to plus one date to endDate.
You can do it using this
$plusToDate = date('Y-m-d H:i:s', strtotime($toDate . ' + 1 day'));
The BETWEEN should be inclusive, are you sure there are no hours, minutes and seconds after the date, that would cause it not to select dates on 2012-12-31 since 2012-12-31 00:00:01 would technically be > 2012-12-31
Format must be same, use mysql DATE function
$select->where->between("DATE(date)", DATE('.$dateStart.'), DATE('.$dateEnd.'));
$from_date = date('Y-m-d', strtotime($AppCleaner->from_date ));
$to_date = date('Y-m-d', strtotime($AppCleaner->to_date ));
$select->where->between('appointment_date', $from_date . ' 00:00:00', $to_date . ' 23:59:59');
also, Use the between clause as below:
$sql = new Sql($this->adapter);
$select = $sql->select();
$select->from('app_posts');
$select->where->NEST->between( 'id', 30,40);
$select->group('app_posts.id');
// echo $select->getSqlString($this->adapter->getPlatform());
// exit;
$statement = $sql->prepareStatementForSqlObject($select);
$result = $statement->execute();
$resultSet = new ResultSet();
$resultSet->initialize($result);
$posts = $resultSet->buffer()->toArray();
return $resultSet;
Try this:
//I have a static function to make conversion Data Format
public static function convertBrazilianDate2MySQLDatabase($dataBrazil) {
$array = explode("/", $dataBrazil);
$array = array_reverse($array);
$str = implode($array, "/");
return date("Y-m-d", strtotime($str));
}
//In My Service I built my sentence
$dtStart = \Estrutura\Helpers\Data::convertBrazilianDate2MySQLDatabase($dt_start) . ' 00:00:01';
$dtEnd = \Estrutura\Helpers\Data::convertBrazilianDate2MySQLDatabase($dt_end) . ' 23:59:59';
$select->where->between('field name in table', $dtStart, $dtEnd);
[...]