Query where substr Codeigniter - postgresql

I have to check two characters of a string in the database.
here is my code but it does not work.
function getby_substr() {
$query = $this->db
->where('substr(ipv6, 4,2 )', 'c1')
->get('computer_information');
if ($query->num_rows() > 0) {
return $query->result();
}
return array();
}
Thank you,

Hope this helps you :
With where clause
/*replace column_name with your table field name*/
$query = $this->db
->where('column_name', SUBSTRING(ipv6, 2, 5))
->get('computer_information');
With like clause
$query = $this->db
->like('column_name', SUBSTRING(ipv6, 2, 5))
->get('computer_information');
for more : https://www.codeigniter.com/user_guide/database/query_builder.html#selecting-data

Related

Laravel-mongo DB

I'm using https://github.com/jenssegers/laravel-mongodb
$query = $this->proposal->where('status', 'approved')
->with(['evaluations', 'user', 'contributions'])
->with(['reviews' => function ($q) {
$q->where('status','approved')->orderBy('created_at', 'desc');
}]);
if( .... ) {
dd($query->toSql()); // "select * from "proposals" where "status" = ?"
$proposalsFoundByTile = $query->where('title','like',"%$request->search%")->get();
dd($query->toSql()); // "select from "proposals" where "status" = ? and "title" like ?"
...
}
Why $query value changed? How can I "clear" this changes to initial value?
After this line,
$proposalsFoundByTile = $query->where('title','like',"%$request->search%")->get();
put this,
$key = array_search("title", array_column($query->getQuery()->wheres,
'column'));
unset($query->getQuery()->wheres[$key]);
Then this will return,
dd($query->toSql()); // "select from "proposals" where "status" = ?"
As adviced in comments solved this problem with clone() function.
$query = $this->proposal->where('status', 'approved')
->with(['evaluations', 'user', 'contributions'])
->with(['reviews' => function ($q) {
$q->where('status','approved')->orderBy('created_at', 'desc');
}]);
if( .... ) {
$subQuery = clone($query);
$proposalsFoundByTile = $subQuery->where('title','like',"%$request->search%")->get();
...
$subQuery = clone($query);
$some_var = $subQuery->... ;
}

syntax for selecting the last recordset in my model

I tried different possibilities but nothing worked, in the tutorial I couldn't find an example either.
I have a method in my modelclass:
public function getlastImport($filename)
{
//$id = (int) $id;
$rowset = $this->tableGateway->select(['Path' => $filename]);
$row = $rowset->current();
if (! $row) {
throw new RuntimeException(sprintf(
'Could not find row with identifier %d',
$id
));
}
return $row;
}
I want to retrieve the last import of a given filename, so ist must be like in sql:
select max(ID) from table where filename = $filename;
But how would be the right syntax in this case?
The sql query should be
"SELECT * FROM table_name WHERE filename={$filename} ORDER BY id DESC LIMIT 1"
Use as the following in your model
public function getlastImport($filename)
{
$select = $this->tableGateway->getSql()->select();
$select->columns(array('id', 'filename', 'label'));
$select->where(array('filename' => $filename));
$select->order("id DESC");
$select->limit(1);
$result = $this->tableGateway->selectWith($select);
$row = $result->current();
if (! $row) {
throw new RuntimeException(sprintf(
'Could not find row with identifier %d',
$id
));
}
return $row;
}
Hope this would help you!

change mysqli check exit and insert into pdo statement

i want to change my mysqli check exist and insert into pdo.. my statement look like below:
<?php
$addSearch = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $search);
if ($CheckMusic = $mysqli->query("SELECT * FROM search WHERE term='$addSearch'")) {
$CheckRow = mysqli_fetch_array($CheckMusic);
$CheckId = $CheckRow['id'];
$CheckCnt = $CheckMusic->num_rows;
$CheckMusic->close();
} else {
printf("Error: %s\n", $mysqli->error);
}
$Now = strtotime("now");
$addSearch = $mysqli->escape_string($addSearch);
if ($CheckCnt < 1) {
$mysqli->query("INSERT INTO search (term, datetime) VALUES('$addSearch','$Now') ") or die(mysqli_error());
} else {
$mysqli->query("UPDATE search SET datetime='$Now' WHERE id='$CheckId'") or die(mysqli_error());
}
?>
hope someone can help with sample if can ;q thanks for your advance!
<?php
$addSearch = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $search);
$CheckMusic = $mysqli->query("SELECT * FROM search WHERE term='$addSearch'");
$Now = strtotime("now");
if($CheckMusic->num_rows == 0){
$mysqli->query("INSERT INTO search (term, datetime) VALUES('$addSearch','$Now') ") or die(mysqli_error());
}else{
$CheckRow = mysqli_fetch_array($CheckMusic);
$CheckId = $CheckRow['id'];
$addSearch = $mysqli->escape_string($addSearch);
$mysqli->query("UPDATE search SET datetime='$Now' WHERE id='$CheckId'") or die(mysqli_error());
}
I hope it will work.

Querying for dates in doctrine

I have a table called active_plans in which there are two columns: activated_date and last_billed_at. Basically, I want to create a query that looks at these two columns like this:
select all from active_plans
where last_billed_at = null AND activated_date + 1 month = today,
or if last_billed_at + 1 month = today.
I can't seem to figure out how to do this, though.
I wound up doing something a lot different:
public function getBillToday()
{
$activePlans = $this->entityManager
->createQuery('SELECT adp FROM adp
WHERE adp.activationDate IS NOT NULL')
->getResult();
$data = array();
foreach ($activePlans as $plan) {
$recur = $plan->getPlan()->getRecurringInMonths();
$nextBillTime = strtotime('-'.$recur.' months', time());
$nextBill = date('Y-m-d', $nextBillTime);
$activationDate = $plan->getActivationDate();
$lastBilledAt = $plan->getLastBilledAt() != NULL ? $plan->getLastBilledAt()->format('Y-m-d') : 0;
if ($activationDate == $nextBill || $lastBilledAt == $nextBill) {
$data[] = $plan->getId();
}
}
return $data;
}

Incorrect `update statement` using IN operator with Zend

I have a function which is wanted to execute a statement like below:
UPDATE coupon_users SET status = status | '1' WHERE id IN ('3','4')
And in coupon_users model, I wrote a method like below do to:
/**
* #param array $ids #array(3,4)
* #param array $status #1
*/
public function updateStatus(array $ids, $status)
{
$result = $this->_db->query(
"UPDATE {$this->_name} SET status = status | ? WHERE id IN (?)",
array(
$status,
$ids
)
)->execute();
return $result;
}
But the query is always:
UPDATE coupon_users SET status = status | '1' WHERE id IN ('Array')
I don't know what am I wrong here, please help me, many thanks.
According to the PDO documentation (Zend_Db uses PDO as its DB access backend):
You cannot bind multiple values to a single named parameter in, for
example, the IN() clause of an SQL statement.
So, you'll probably need to prepare a bit further your query, so that it contains as many markers as elements in the array. A possible solution could be the following:
// Compose the query
$queryToExecute = "UPDATE {$this->_name} SET status = status | ? WHERE id IN (";
$questionMarks = array();
for ($id in $ids) {
$questionMarks[] = '?';
}
$queryToExecute .= implode(',', $questionMarks);
$queryToExecute .= ')';
// $queryToExecute should have the format "UPDATE ... WHERE id IN (?,?,?,...?)"
// Execute it
$result = $this->_db->query(
$queryToExecute,
array($status, $ids)
)->execute();
Hope that helps,
try:
public function updateStatus(array $ids, $status)
{
$result = $this->_db->query(
"UPDATE {$this->_name} SET status = ? WHERE id IN (?)",
array(
$status,
implode(',',$ids)
)
)->execute();
return $result;
}
Update:
Have you tried?:
$this->_db->update($this->_name, array('status'=>$status), array('id IN (?)'=>$ids));
I haven't tested it, it also depends on what $this->_db is an instance of
http://framework.zend.com/manual/en/zend.db.adapter.html#zend.db.adapter.write.update
Try this..
public function updateStatus(array $ids, $status)
{
$inarray= implode(',',$ids);
$result = $this->_db->query(
"UPDATE {$this->_name} SET status = status | ? WHERE id IN (?)",
array(
$status,
$inarray
)
)->execute();
return $result;
}
Its working fine for me.
$existingImagesIds = array(1, 2, 3, 7);
$where = $pImgModel->getAdapter()->quoteInto("id in (?) ", $existingImagesIds);
$pImgModel->update(array('status' => '0'), $where);