Zend Framework how to echo value of SUM query - zend-framework

I created a query for the zend framework, in which I try to retrieve the sum of a column, in this case the column named 'time'. This is the query I use:
$this->timequery = $this->db_tasks->fetchAll($this->db_tasks->select()->from('tasks', 'SUM(time)')->where('projectnumber =' . $this->value_project));
$this->view->sumtime = $this->timequery;
Echoing the query tells me this is right. But I can't echo the result properly. Currently I'm using:
echo $this->sumtime['SUM(time)'];
Returning the following error:
Catchable fatal error: Object of class Zend_Db_Table_Row could not be converted to string in C:\xampp\htdocs\BManagement\application\views\scripts\tasks\index.phtml on line 46
Line 46 being the line with the echo in my view.
I've been searching now for two days on how to figure this out, or achieve the same result in a different way. Tried to serialize the value, but that didn't work either.
Is there somebody who knows how to achieve the total sum of a database column?
Any help is greatly appriciated!
note: Pretty new to zend framework...

Zend_Db has some nice utility methods like fetchAll (which you're using) to fetch different types of data:
fetchAll - for a set of rows
fetchRow - for a single row
fetchOne - for a single cell
Most simply:
$sum = $db->fetchOne('SELECT SUM(time) FROM tasks WHERE project_number = ?', $this->value_project);
You can use Zend_Db_Select with these methods too, like in your question:
//note that the SUM(time) part is passed as a Zend_Db expression, as it is not a column
$select = $this->db_tasks->select()
->from('tasks', new Zend_Db_Expr('SUM(time)'))
->where('projectnumber =' . $this->value_project);
$this->timequery = $this->db_tasks->fetchOne($select);
This works because the Zend_Db_Select object implements a toString method, to produce SQL.

$timequery= $timequeriestb->select(Zend_Db_Table::SELECT_WITH_FROM_PART)
->columns('SUM(time) AS Totaltime')
->where('projectnumber ='. $this->value_project));

The SQL you want is probably:
SELECT SUM(time) AS time_sum FROM tasks ...
Not sure how to do this in Zend. Then:
echo $this->sumtime['time_sum'];

Related

EF Core raw query with Like clause

I want to create queries using EF FromSqlInterpolated or FromSqlRaw that allows me to use Like clauses, but I don't know what is the right way to do it without opening the application to SqlInjection attacks.
One first approach has took me to the following code
var results = _context.Categories.FromSqlInterpolated(
$"Select * from Category where name like {"%" + partialName + "%"}");
First test worked fine, it returns results when providing expected strings, and returns nothing when i provide something like ';select * from Category Where name='Notes'--%';
Still I don't know much about SqlInjection, at least not enough to feel safe with the query shown before.
Does someone know if the query is safe, or if there is a right way to do it?
Thanks
From this document
The FromSqlInterpolated and ExecuteSqlInterpolated methods allow using
string interpolation syntax in a way that protects against SQL injection attacks.
var results = _context.Categories.FromSqlInterpolated(
$"Select * from Category where name like {"%" + partialName + "%"}");
Or you can also change your query to Linq-to-Entity like this way
var results = _context.Categories.Where(p => p.name.Contains(partialName ));

How do I use a PostgreSQL function that returns a table as a CakePHP 3 Model?

Using Cake PHP 3.x and we have a PostgreSQL 9.6.3 db.
We make extensive use of PG functions that return tables - for example
select * from getStudies(cid,UID, SID);
Functions are used for various applications - one of them is more complex filtering of rows from a table - where Cake has difficulty.
One option is to implement the logic as a custom Cake Model method in PHP, but the SQL code and amount of joins makes it messy in PHP.
We think we should be able to create a Cake Model from the function and then pass the parameters via Cake Model methods but so far - it is unclear how to do that.
This code works but it returns the data without the columns and I have not been able to figure out how to use reflection to get the _columns properties from the Model schema.
public function getStudies($data = array()) {
$customer_id = $data['customer_id'];
$connection = ConnectionManager::get('default');
$sql = "select * from getStudies($customer_id)";
$results = $stmt->fetch();
return $results; }
So -
Option 1 - figure out how to model a function that returns tables as a cake model
Option 2 - use reflection to get the _columns and merge it with the query result
Thanks
As you've mentioned in the comments, the schema columns details can be accessed via its columns() method. You could process the results manually using the schema information, or use the function as the source, just like in your example.
The query builders from() method supports raw SQL as well as expressions, so you can basically add whatever you like, however expressions will be wrapped in parentheses, which will be invalid SQL in case of a function call, so you'd have to go with raw SQL, and bindings (please never inject (user)data into queries directly):
public function getStudies($customerId)
{
return $this
->find()
->from([
$this->alias() => 'getStudies(:customerId)'
])
->bind(':customerId', $customerId, 'integer');
}
That should generate a query similar to
SELECT
Alias.column1, Alias.column2, ...
FROM
getStudies(:customerId) Alias

FindBy property in TYPO3 Extbase MVC is not working

I'm unable to run the FindBy magic function property in Extbase MVC
$title=array(0 =>'Books Day');
$each_event=$this->eventRepository->findByTitle($title);
$each_event is returning an object of type TYPO3\CMS\Extbase\Persistence\Generic\QueryResult .
How do I make this work?
I also tried passing in a string to findByTitle and findByOne. Both don;t work! :(
I'm using TYPO3 6.1 and extension builder.
The last part of those magic functions always needs to be a field in the database. So "title" must be in your model. You might have a field "one" for your object, but I guess you meant findOneByTitle?
The object type QueryResult is correct. You can turn it into an array for debugging purpose for example:
$foo = $query->execute()->toArray();
By the way: check wether your eventRepository is null or not and you could try this to see if it works at all:
$result = $this->myRepository->findAll();
Try
$each_event=$this->eventRepository->findByTitle($title)->toArray();
Reference to the QueryResult.
As said in the documentation, it returns a QueryResultInterface|array.
As a consequence you have to loop over the result like this:
foreach($each_event as $single_event) {
$single_event->getProperty();
}
If you are sure that it returns only one single value you could also access it by the index 0:
$each_event[0]->getProperty();

Versant OQL Statement with an Arithmetic operator

I'm working on a c# project that use a Versant Object Database back end and I'm trying to build a query that contains an arithmetic operator. The documentation states that it is supported but lack any example.
I'm trying to build something like this:
SELECT * FROM _orderItemObject WHERE _qtyOrdered - _qtySent > 0
If I try this statement in the Object Inspector I get a synthax error near the '-'.
Anyone has an example of a working VQL with that kind of statement?
Thanks
I am not sure that the Object Inspector will know the syntax for the arithmtic expression. However, in your code you should be referring to the fully qualified class. Then the syntax you are using should be perfectly fine.
Query query = new Query( session,
"select * from com.yourCompany.yourClass where _qtyOrdered - _qtySent > 0 ");
QueryResult result = query.execute();
I just tried this out on one of my classes and it worked fine.
Cheers,
-Robert
With C# and OQL you have to make sure you select the proper class extent. This is done by adding the "Extent" suffix to the class name. For example, in my Pet class I would identify all the pets with "PetExtent" in the OQL string.
Class members are accessed in the predicate by defining a local moniker, p in the code below. Any arithmetic expressions will be evaluated by the query engine.
string query="SELECT * FROM PetExtent AS p WHERE p.Name = \"Ferris\" AND (p.age + 5) > 4";
IQueryResult result = scope.GetOqlQuery(query).Execute();
foreach (object o in result)
Out(o.ToString());
The best way to test OQL with Versant's C# binding is to use the OQL Query Browser integrated into Visual Studio. Look under the Versant Menu drop down in Visual Studio.
Best Regards,
Derek

How can I use a stored procedure in a MySql database with Zend Framework?

I'm recently have learned to use Zend Framework. I did a simple CRUD application. But now I want to use a existing database for a more complex application and I want to know how I call a stored procedure in the Model, how to send parameters, how to read the results and store them in an array in PHP. Please. I appreciate any kind of help :)
It's not too hard. Here's an example of a MySQL stored procedure with an IN parameter, an OUT parameter, and a result set:
CREATE PROCEDURE MyProc(IN i INTEGER, OUT o INTEGER)
BEGIN
SELECT i+10 INTO o;
SELECT i, o;
END
You can call this with the query() method, and pass a parameter:
$stmt = $db->query("CALL MyProc(?, #output)", array(25));
print_r( $stmt->fetchAll() );
The trick is that MySQL stored procs might return multiple result sets (if the proc had multiple SELECT queries for instance). So the API must advance through all result sets before you can execute another SQL query. Or else you get the "Commands out of sync" error.
If you use the PDO_MySQL adapter:
while ($stmt->nextRowset()) { }
If you use the MySQLi adapter, you'll find that Zend_Db_Statement_Mysqli doesn't implement nextRowset(), so you have to call the internal mysqli connection object:
while ($db->getConnection()->next_result()) { }
Once you clear the result sets, you can run subsequent SQL queries, for example to fetch the value of the procedure's OUT parameter:
$stmt = $db->query("SELECT #output");
print_r( $stmt->fetchAll() );
Great answer from Bill. Just for completeness, if you encounter:
SQLSTATE[HY000]: General error: 2053
When using this method to get a result set from your procedure, check your arguments. I refactored a method and was passing NULLs as arguments to the procedure as the variables I'd used were out of scope. Once I'd fixed this silly mistake the problem went away (to be replaced by another):
SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other
unbuffered queries are active. Consider using PDOStatement::fetchAll().
I'm using $stmt->fetchAll() though. I switched to using prepare() and execute() in place of query(). Switching to mysqli from pdo_mysql in my Zend_Db config finally got things working for me. I found this information from the following SO question:
Call Multiple Stored Procedures with the Zend Framework
If someone is looking for ZendFramework 2 \ Zend Expressive using Zend\Db :
There is another way to do this using createStatement() method.
// prepare create statement from adapter
$stmt = $this->getAdapter()->createStatement();
$stmt->prepare('CALL myproc("myVal")');
// execute sql query
$records = $stmt->execute();
// manipulate results
if ($records instanceof ResultInterface && $records->isQueryResult()) {
$resultSet = new ResultSet;
$resultSet->initialize($records);
// return records if found
if (count($resultSet)) {
// return array of result set
return $resultSet->toArray();
}
// if no records found
return array()
}
$db = Zend_Db_Table::getDefaultAdapter();
$stmt = $db->query("CALL procedure()");
$data = $stmt->fetchAll();