ZF3 Create SELECT query from expression - php

I want to create a ZF3 \Zend\Db\Sql\Select object where table is pgsql expression:
generate_series('2017-01-01'::date, '2017-02-01'::date, '1 day'::interval)
but if I pass expression as \Zend\Db\Sql\Expression object, like this:
$select = new \Zend\Db\Sql\Select();
$select->from(['dd' => new \Zend\Db\Sql\Expression("generate_series('2017-01-01'::date, '2017-02-01'::date, '1 day'::interval)")]);
I'm getting following error:
Catchable fatal error: Object of class Zend\Db\Sql\Expression could not be converted to string
but if I pass my expression as string, it's getting automatically wrapped and looks like this:
SELECT "dd".* FROM "generate_series('2017-01-01'::date, '2017-02-01'::date, '1 day'::interval)" AS "dd"
which is of course wrong. Is it possible to achieve without overwriting ZF3 Select class?

Select::form() method takes table name as its argument. You may try this way:
$select = new \Zend\Db\Sql\Select();
$select->columns(['AliasName' => new \Zend\Db\Sql\Expression("YourExpression")]);
This would produce following query:
SELECT YourExpression AS "AliasName"
Updated
The working example of the above method is down here. First, create an instance of database adapter providing database information. In this case, we are using PDO driver for Postgresql.
$adapter = new \Zend\Db\Adapter\Adapter([
'driver' => 'Pdo_Pgsql',
'database' => 'YourDatabaseName',
'username' => 'YourDatabaseUsername',
'password' => 'PasswordForDatabase',
]);
Next up, we are going to create an another instance of Sql::class from zend-db component. It is not mandatory if you are using TableGateway::class in your controller action.
$sql = new \Zend\Db\Sql\Sql($adapter);
Now here is the one you want, the Select object, which we are creating from the previous Sql object. Here we are also querying through zend-db's Expression::class to generate some date series.
$select = $sql->select();
$select->columns(["dd" => new \Zend\Db\Sql\Expression("generate_series('2007-02-01'::timestamp, '2007-03-01'::timestamp, '1 day'::interval)")]);
If we output the sql as string we would then get as the following
SELECT generate_series('2007-02-01'::timestamp, '2007-03-01'::timestamp, '1 day'::interval) AS "dd"
As we are using PDO driver for postgresql, we would prepare the statement at the moment, and finally execute the sql.
$statement = $sql->prepareStatementForSqlObject($select);
$results = $statement->execute();
If we output the results we fetched we would then get a series of dates as the following
foreach ($results as $row) {
print $row['dd'] ."</br>";
}
// Outputs
2007-02-01 00:00:00
2007-02-02 00:00:00
2007-02-03 00:00:00
2007-02-04 00:00:00
...
Hope this would help you!

Related

MongoDB new driver manager regex query same as MySQL LIKE query

I am using php7 and MongoDB new driver manager in my project. I want one query which is same mysql LIKE query
Below are my search feild in my MongoDB collection:-
fullAddress: 1013 BISMARCK ROAD PUNTA GORDA FL 33983 US
I want one query to find all records who belongs to "33983" value.
Below are my code:-
new MongoDB\BSON\Regex("^33983", 'i')
but its not working it s showing no records found error but this result set actully present in database i want LIKE query which is same in mysql Like query ('%LIKE%').
Here is an updated Query with like query using MongoDB. Here is full documentation https://docs.mongodb.com/manual/reference/operator/query/regex/
$requestlist = '33983';
$options = ['limit' => 10, 'skip' => 0, 'sort' => ['listprice.listprice' => 1]];
$dataSend = array('listingStatus' => 'Active');
$nameCondition = []; $nameCondition[] = array('fullAddress' => new MongoDB\BSON\Regex($requestlist));
$nameCondition[] = array('mlsNumber' => new MongoDB\BSON\Regex($requestlist));
$dataSend['$or'] = $nameCondition;
$query = new MongoDB\Driver\Query($dataSend,$options);
$rows = $manager->executeQuery("TableName.Collection", $query);
Hope this will help :)

On ZF2 how can use an expression instead of a quoted table name?

How can I generate a query like this on PHP's ZF2?
SELECT timestamp FROM generate_series(0,20,5) AS timestamp
I have tried:
$select = $this->select()
->columns(array("timestamp"))
->from("timestamp" => array("generate_series(0,20,5)"))
Which generates:
SELECT "timestamp" FROM "generate_series(0,20,5)" AS "timestamp"
But then it's looking for a table named generate_series(0,20,5) which doesn't exists
And also:
$select = $this->select()
->columns(array("timestamp"))
->from(array("timestamp" => new \Zend\Db\Sql\Expression('generate_series(0,20,5)')))
But it also generates an error:
SELECT "timestamp"."timestamp" AS "timestamp" FROM "Object" AS "timestamp"
Any ideas on how to turn the table name into an expression instead of a quoted table name?
FYI, be aware there is another Zend\Sql\Predicate\Expression class in ZF2. If you look at the Select::from(), i think you can not pass any Expression object as table name.
So a quick solution would be to use a sub select. But it is some kind of ugly ;)
$prefixColumns = false;
$select2 = new Select();
$select2->columns(array('*'), $prefixColumns);
$select2->from('generate_series(0,20,5)');
$select = new Select();
$select->columns(array('timestamp')); // or disable prefixed columns like in $select 2
$select->from(array('tblAlias' => $select2));
This should provide the following query:
var_dump($select->getSqlString());
SELECT
tblAlias.timestamp AS timestamp
FROM (
SELECT * FROM generate_series(0,20,5)
) AS tblAlias

Create a new column or field with PHP PDO

How do I create a new column or field (idnew) in an existing Access database (resultdb) using PHP PDO?.
You are able to create new columns with the query function as well as the prepared statement function. Whitch one you should use depends on what you want to do with it.
Example 1
$pdo->query('ALTER TABLE resultdb ADD idnew INT(11)');
Example 2
function addColumn($column, $type)
{
$query = $pdo->prepare('ALTER TABLE resultdb ADD :column :type');
$query->execute(array(':column' => $column, ':type' => $type));
}
addColumn('idnew', 'INT(11)');
Be careful that you are not destroying any functions built in you website by doing this.

ZF2 - How do I insert into select?

I am trying to perform an insert into select from a table method in zf2.
The following procedure is what I used as an example.
How to perform an INSERT INTO SELECT query in ZF2
My table method is contained in a table class in ZF2 which is a separate table in the db from the tables I am trying to insert into.
public function addCategoryName($val)
{
$data = array (
'CategoryName' => $val);
$this->tableGateway->insert($data);
$id = $this->tableGateway->lastInsertValue;
$on = "categoryid = $id";
$select = new Select('actionitems');
$select->columns(array('actionitemid', 'categoryid'))->join('categories', $on, array('actionitemid', 'categoryid'), 'cross');
$adapterInsert = new \Zend\Db\Adapter\Adapter(array(
'driver' => 'pdo_mysql',
'database' => 'actionitemmanager',
'username' => 'username',
'password' => 'password'
));
$insert = new Insert();
$insert->into('actionitemcategories');
$insert->columns(array('actionitemid', 'categoryid'));
$insert->values($select);
//insert with select
$adapterInsert->insertWith($insert);
}
Neither
$insert->values($select)
or
$insert->select($select)
work...
The first attempt gives an error that the $select must be an array, whereas $insert->select($select) gives an error that select() is not a method of Insert.
How can I get this query to work?
The Zend Framework feature you're referencing was introduced in v2.3:
Zend\Db\Sql\Insert can use a Select object as the value source (INSERT INTO ... SELECT)
I suspect you're using an older version. You can compare Zend\Db\Sql\Insert in v2.2.10 to v2.3.0 to see the different exceptions thrown for invalid arguments.
You should upgrade Zend Framework to v2.3 or greater to use this feature.

Executing SQL Stored Procedures with Input and Output parameters

I am very new to stored procedures and the PDO library so please take it easy on me. I am trying to execute a stored procedure using a PDO function and retrieve the recordsets along with the output parameters. Which function should I use and what parameters are necessary?
If I want to execute basic statements using the function like the following example, what PDO method should I use? e.g.
$mssql = new mssql;
$mssql->sql('stored_procedure()');
$mssql->sql('SELECT * FROM [test]');
I want the function to return the correct results dependant on the statement type. Is this going to be possible?
UPDATE
Just in case I didnt make it very clear, the 'mssql' class uses the PDO class to execute queries. At the moment I am using:
$PDO->prepare();
$PDO->exec();
After researching around the internet, I found it is in fact very simple using the PDO prepare, bindParam and execute methods.
An example of a store procedure using my class:
$mssql->bind_params = array(
'BatchNum' => array(
'value' => 'SS000008'
),
'RecCount' => array(
'value' => 0,
'type' => PDO::PARAM_INT,
'length' => 8
)
);
$mssql->sql("{CALL sp_Batch_Sales(#paramOne=:paramOne,#paramTwo=:paramTwo)}");
This is converted to:
$query = $PDO->prepare({CALL sp_Batch_Sales(#paramOne=:paramOne,#paramTwo=:paramTwo)});
$query->bindParam(':paramOne',$returned_parameters['paramOne']);
$query->bindParam(':paramTwo',$returned_parameters['paramTwo'],PDO::PARAM_INT,8);
$query->execute();
The recordsets can then be retrieved using:
do{
// Get the results
$results = $query->fetchAll(PDO::FETCH_ASSOC);
// Only place the results into the array if they exist
if(!empty($results)){
$data[$i]['results'] = $results;
}
// Set the number of rows in the result array
$data[$i]['rows'] = $query->rowCount();
// Increment i
$i++;
}while($query->nextRowset());
And the input and output parameters can be retrieved using the array:
$returned_parameters
I hope this helps

Categories