Why do I get DB error after migrating from codeigniter 2.6 to codeigniter 3? - codeigniter-3

Why do I get DB error after migrating from CodeIgniter 2.6 to CodeIgniter 3?
It adds ",0" after table name.
Ex- SELECT id, title, title_url FROM tablename, 0 WHERE isEnabled = 'Y' ORDER BY date DESC LIMIT 1

public function functionName()
{
$this->db->select('id, title, title_url');
$this->db->from('tablename');
$this->db->where('isEnabled','Y');
$this->db->order_by('date','desc');
$this->db->limit(1);
$query = $this->db->get()->result();
return $query;
}
Try this once.

Related

Issue displaying count results in WebApi call

I have a stored procedure that return a record count in SQL based on certain criteria. I am trying to retrieve this count in EF Core 3 so I can pass it into an angular app. When I test the SP in SQL it returns the expected result. In the controller I configured an action route to call the SP
[Route ("[action]")]
public async Task<IActionResult> GetCountOverdueLowPriorityWorkOrders()
{
var GetCountOverdueLowPriorityWorkOrders = await _repo.GetCountOverdueLowPriorityWorkOrders();
return Ok(GetCountOverdueLowPriorityWorkOrders);
}
When I test this call from Postman, I get the following error:
System.InvalidOperationException: The required column 'ID' was not present in the results of a 'FromSql' operation.
I am fairly new to programming, so any help would be greatly appreciated.
Thanks!
The column containing the values for COUNT(id) needs to be aliased as id.
Try this
SELECT COUNT(id) as ID FROM Workorders WHERE Severity = 1 AND Due < CAST(Current_TimeStamp AS DATE)

Error when using "ALL" operator when execute query

I need to execute following query using phalcon framework:
"SELECT id FROM table GROUP BY id HAVING '31' = ALL(array_agg(status))"
How can I execute this query using phalcon?
When I do following:
Model::query()
->columns(['id'])
->groupBy('id')
->having('31 = ALL(array_agg(status))')
->execute();
I get this error message:
Syntax error, unexpected token ALL, near to '(array_agg(status)) ', when parsing: SELECT id FROM [SomeNameSpace\Model] GROUP BY [id] HAVING 31 = ALL(array_agg(status)) (137)
I'm not 100% sure which Postgres functions are supported, but you can try like this:
Model::query()
->columns([
'id',
'ALL(array_agg(status)) AS statusCounter'
])
->groupBy('id')
->having('31 = statusCounter')
->execute();
Notice that I moved the aggregation functions in the select, rather in having clause.
UPDATE: here is an example of very custom query. Most functions used are not supported and it's sometimes cleaner just to write a simple SQL query and bind the desired Model to it:
public static function findNearest($params = null)
{
// A raw SQL statement
$sql = '
SELECT *, 111.045 * DEGREES(ACOS(COS(RADIANS(:lat))
* COS(RADIANS(X(coords)))
* COS(RADIANS(Y(coords)) - RADIANS(:lng))
+ SIN(RADIANS(:lat))
* SIN(RADIANS(X(coords)))))
AS distance_in_km
FROM object_locations
ORDER BY distance_in_km ASC
LIMIT 0,5;
';
// Base model
$model = new ObjectLocations();
// Execute the query
return new \Phalcon\Mvc\Model\Resultset\Simple(
null,
$model,
$model->getReadConnection()->query($sql, $params)
);
}
// How to use:
\Models\ObjectLocations::findNearest([
'lat' => 42.4961756,
'lng' => 27.471543300000008
])
You need to add ALL as dialect extension. Check this topic for example https://forum.phalconphp.com/discussion/16363/where-yearcurrenttimestamp-how-to-do-this

How can i ignore: PSQLException: The column name clothStyle was not found in this ResultSet

I created a a query to only get 4 items from a row in a table which does not include the column cloth style, so i understand why i get the error, but how can i tell Spring Jpa or JPA it is on purpose. and i just want the id, name and color table ?
this is my code:
#RequestMapping(value = "/query/material",method = RequestMethod.GET)
public String QueryMaterialTable(HttpServletRequest request){
DataTableRequest<Material> dataTableInRQ = new DataTableRequest<Material>(request);
PaginationCriteria pagination = dataTableInRQ.getPaginationRequest();
String baseQuery = "SELECT id as id, time as time, name as name, color as color, price as price, (SELECT COUNT(1) FROM MATERIAL) AS totalrecords FROM MATERIAL";
String paginatedQuery = AppUtil.buildPaginatedQuery(baseQuery, pagination);
System.out.println(paginatedQuery);
Query query = entityManager.createNativeQuery(paginatedQuery, Material.class);
#SuppressWarnings("unchecked")
List<Material> materialList = query.getResultList();
DataTableResults<Material> dataTableResult = new DataTableResults<Material>();
dataTableResult.setDraw(dataTableInRQ.getDraw());
dataTableResult.setListOfDataObjects(materialList);
if (!AppUtil.isObjectEmpty(materialList)) {
dataTableResult.setRecordsTotal(String.valueOf(materialList.size())
);
if (dataTableInRQ.getPaginationRequest().isFilterByEmpty()) {
dataTableResult.setRecordsFiltered(String.valueOf(materialList.size()));
} else {
dataTableResult.setRecordsFiltered(String.valueOf(materialList.size()));
}
}
return new Gson().toJson(dataTableResult);
}
If I got the question right, your problem is with the following two lines:
Query query = entityManager.createNativeQuery(paginatedQuery, Material.class);
List<Material> materialList = query.getResultList();
You have various options to fix this:
provide a complete column list, i.e. provide the missing column in the SQL statement and just make them NULL;
Don't use Material but a new class that has the matching attributes.
Don't use a native query but JPQL and a constructor expression.
Use a ResultTransformer.
Use Spring Data and a Projection.
Use a Spring JdbcTemplate.

rethinkdb get records by createdDate

we are using rethinkdb with nodejs. I have a user table and i want to get all user records inserted today and yesterday like below sql query.
select * from user where DATEDIFF(day,createdDate ,GETDATE()) = 1
https://rethinkdb.com/api/javascript/#date
r.table("users").filter(function(user) {
return user("birthdate").date().eq(r.now().date())
})

Using php DateTime object in mysql query

I'm trying to create a query that pulls information about sellers from my database, but only if their store has launched in the last 3 days. The easiest way I can think of to calculate the date for the query is using a new DateTime() object. When I output my code to test it, it's in the proper string for MySQL to query it with, but whenever I try to bind the variable, I get an error. I'm using Zend_Db to query, (PDO adapter)
action:
public function indexAction()
{
$dateMod = new DateTime();
$dateMod->modify('-2 days');
$dateMod->format('Y-m-d H:i:s');
// get sellers initialized in last 3 days
$sellerTable = new Application_Model_DbTable_Sellers();
$select = $sellerTable->select()->setIntegrityCheck(false);
$select->from(array('s' => 'seller'),array('sellerID', 'businessName'));
// select firstName, lastName, picture from user table, and businessName and sellerID from seller table.
$select->join(array('u' => 'user'), 's.userID = u.userID', array('firstName', 'lastName', 'picture'));
$select->where('s.active = 1 AND s.contentApproval = 1 AND s.paymentApproval = 1 AND s.featured = 1');
$select->where('s.launchDate > ?', $dateMod);
$select->order('s.launchDate DESC');
$newSellers = $sellerTable->fetchAll($select);
When I assign $dateMod to the view, it outputs the correct Y-m-d H:i:s format. But when I plug it into the query, I get the following error:
Message: 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 ') ORDER BY `b`.`launchDate` DESC' at line 2
If I hardcode a value into dateMod in the mysql timestamp format, the query works fine. How can I access just the string value of the timestamp in the DateTime object? getTimestamp returns a unix formatted timestamp, even after assigning a format.
The format() function returns the formatted date, so you need to assign that to a variable for use in the query:
$dateFormatted = $dateMod->format('Y-m-d H:i:s');
$select->where('s.launchDate > ?', $dateFormatted);