$dbAdapter = $this->adapter;
$sql = new Sql($dbAdapter);
$sQuery = $sql->select()
->from(array('c' => 'company'), array('name', 'jobtitle', 'experience', 'skill'))
->joinInner(array('j' => 'jobpost'), 'c.cid = j.cid');
In this query, I am getting error:
PHP Fatal error: Call to undefined method Zend\Db\Sql\Select::joinInner().
And classes i used in this :
use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Sql;
use Zend\Db\TableGateway\AbstractTableGateway;
You should remove joinInner and add join
$dbAdapter = $this->adapter;
$sql = new Sql($dbAdapter);
$sQuery = $sql->select()
->from(array('c' => 'company'), array('name', 'jobtitle', 'experience', 'skill'))
->join(array('j' => 'jobpost'), 'c.cid = j.cid');
By default it will do an Inner join. If you want to specify the join then the documentation example from zend
should make it clear.
$select->join(
'foo' // table name,
'id = bar.id', // expression to join on (will be quoted by platform object before insertion),
array('bar', 'baz'), // (optional) list of columns, same requiremetns as columns() above
$select::JOIN_OUTER // (optional), one of inner, outer, left, right also represtned by constants in the API
);
You will also need the two lines Hary added in his answer,
$statement = $sql->prepareStatementForSqlObject($sQuery);
$result = $statement->execute();
and the you can return your result
return $result->toArray();
use Zend\Db\Sql\Sql;
use Zend\Db\Adapter\Adapter;
$dbAdapterConfig = array(
'driver' => 'Mysqli',
'database' => 'dbname',
'username' => 'dbusername',
'password' => 'dbuserpassword'
);
$dbAdapter = new Adapter($dbAdapterConfig);
$sql = new Sql($dbAdapter);
$sQuery = $sql->select();
$sQuery->from(array('c' => 'company'), array('name', 'jobtitle', 'experience', 'skill'));
$sQuery->joinInner(array('j' => 'jobpost'), 'c.cid = j.cid');
$statement = $sql->prepareStatementForSqlObject($sQuery);
$result = $statement->execute();
Doc:http://framework.zend.com/manual/2.1/en/index.html#zend-db / http://framework.zend.com/manual/2.1/en/modules/zend.db.sql.html
Related
I'm trying to use MongoDB on my local machine using the advice in this stack overflow. I'm using XAMPP on Windows 10, php version 8.01, and MongoDB extension 1.9.0.
It's a very basic script that connects to MongoDB and tries to use one of the databases.
But I am still getting this warning:
Connection to database successfully
Warning: Undefined property: MongoDB\Driver\Manager::$aws_inventories in C:\xampp\htdocs\mongo_connect.php on line 8
This is my code:
<?php
require 'C:\xampp\htdocs\vendor\autoload.php'; // include Composer's autoloader
$DB_CONNECTION_STRING="mongodb://localhost:27017";
// connect to mongodb
$m = new MongoDB\Driver\Manager( $DB_CONNECTION_STRING );
echo "Connection to database successfully";
// select a database
$db = $m->aws_inventories;
?>
How can I get rid of the warning and connect to the DB correctly?
First, you're trying to access a property which doesn't exists in MongoDB\Driver\Manager class object.
Second, $db = $m->aws_inventories; works with MongoDB\Client library.
Here are few example to get collections list or find all/specific document/s or insert/bulk insert, update a document or to perform a distinct query
Get all collections of aws_inventories:
try {
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$command = new MongoDB\Driver\Command(["listCollections" => 1]);
$cursor = $manager->executeCommand("aws_inventories", $command);
// list of all collections in aws_inventories
$collections = $cursor->toArray();
var_dump($collections);
} catch (\MongoDB\Driver\Exception\Exception $e) {
}
Get all documents from a collection:
try {
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
// setting options and filter
$filter = [];
$options = [];
/*
// or to find specific documents based on a condition and limit records
$filter = [
'service' => 'ec2',
'instance' => 'co',
'type' => 'c5',
'vCPU' => [
'$gt' => 2
]
];
$options = [
'limit' => 10,
'maxTimeMS' => 1000, // to limit the execution time of a query
'sort' => [
'vCPU' => -1
]
];
*/
// constructing the query
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery('aws_inventories.test', $query);
foreach ($cursor as $document) {
var_dump($document);
}
} catch (\MongoDB\Driver\Exception\Exception $e) {
}
To perform distinct query:
try {
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$query = [
'size' => '2xlarge'
];
$command = new MongoDB\Driver\Command([
'distinct' => 'test', // Collection name
'key' => 'instance', // field for which we want to get distinct values
'query' => $query // criteria to filter documents
]);
$cursor = $manager->executeCommand("aws_inventories", $command);
// to get distinct values as array
$instances = current($cursor->toArray())->values;
var_dump($instances);
} catch (\MongoDB\Driver\Exception\Exception $e) {
}
To insert single/multiple document/s:
try {
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert([
'service' => 'ec2',
'instance' => 'co',
'type' => 'c5',
'size' => 'large',
'model' => 'c5.large',
'vCPU' => 2,
'memory' => 4,
'storage' => 'ebs-only',
'network_bandwidth' => 10,
'ebs_bandwidth' => 4750
]);
$bulk->insert([
'service' => 'ec2',
'instance' => 'gp',
'type' => 't3',
'size' => 'nano',
'model' => 't3.nano',
'vCPU' => 2,
'memory' => 0.5,
'storage' => 'ebs-only',
'network_bandwidth' => 5
]);
$result = $manager->executeBulkWrite('aws_inventories.test', $bulk);
} catch (\MongoDB\Driver\Exception\Exception $e) {
}
To update existing document/s: (Taken from executeUpdate example)
try {
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$criteria = [
'service' => 'ec2',
'type' => 'c5'
];
$document = [
'$set' => [
'features' => [
'Powered by the AWS Nitro System, a combination of dedicated hardware and lightweight hypervisor'
]
]
];
$updateOptions = array(
'multi' => true, // false - to update only first matching document, true - update all matching documents
'upsert' => 0
);
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 100);
$result = $manager->executeUpdate('aws_inventories.test', $criteria, $document, $updateOptions, $writeConcern);
printf("Updated %d document(s)\n", $result->getModifiedCount());
printf("Matched %d document(s)\n", $result->getMatchedCount());
printf("Upserted documents: %d\n", $result->getUpsertedCount());
foreach ($result->getUpsertedIds() as $index => $id) {
printf("upsertedId[%d]: ", $index);
var_dump($id);
}
/* If the WriteConcern could not be fulfilled */
if ($writeConcernError = $result->getWriteConcernError()) {
printf("%s (%d): %s\n", $error->getMessage(), $error->getCode(), var_export($error->getInfo(), true));
}
/* If the write could not happen at all */
foreach ($result->getWriteErrors() as $writeError) {
printf("%s (%d)\n", $error->getMessage(), $error->getCode());
}
} catch (\MongoDB\Driver\Exception\Exception $e) {
}
$m->aws_inventories That looks like as the older/deprecated approach. Could you try to follow this tutorial?
https://zetcode.com/db/mongodbphp/
<?php
try {
$mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$stats = new MongoDB\Driver\Command(["dbstats" => 1]);
$res = $mng->executeCommand("aws_inventories", $stats);
$stats = current($res->toArray());
print_r($stats);
} catch (MongoDB\Driver\Exception\Exception $e) {
$filename = basename(__FILE__);
echo "The $filename script has experienced an error.\n";
echo "It failed with the following exception:\n";
echo "Exception:", $e->getMessage(), "\n";
echo "In file:", $e->getFile(), "\n";
echo "On line:", $e->getLine(), "\n";
}
?>
This example is adapted from the official doc https://www.php.net/manual/en/mongodb-driver-manager.executequery.php
<?php
require 'vendor/autoload.php';
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$db = 'test_database';
$col = 'mycol';
$namespace = $db.'.'.$col;
// insert data
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->insert(['x' => 2]);
$bulk->insert(['x' => 3]);
$manager->executeBulkWrite($namespace, $bulk);
// query
$query = new MongoDB\Driver\Query(['x' => ['$gt' => 1]], []);
$cursor = $manager->executeQuery($namespace, $query);
foreach ($cursor as $document) {
var_dump($document);
}
As the document suggests, MongoDB\Driver\Manager is a generic abstraction to manage any type of MongoDB connection (standalone server, replica set, or sharded cluster) so the methods will look a bit too complicated for simple CRUD on standalone server.
If you just want to connect to a standalone server, you may want to check MongoDB\Client. Here is the code that do exactly the same thing:
<?php
require 'vendor/autoload.php';
$client = new MongoDB\Client("mongodb://localhost:27017");
$col = $client->test_database->mycol;
// insert data
$col->insertMany([
['x' => 1],
['x' => 2],
['x' => 3],
]);
// query
$docs = $col->find(['x' => ['$gt' => 1]]);
foreach ($docs as $document) {
var_dump($document);
}
image for mongo info
MongoDB shell version v3.4.1
mongodb driver v1.6.14
xampp v3.2.1, Apache/2.4.16 (Win32) OpenSSL/1.0.1p PHP/5.6.12
i m running for first time and getting this problem plz help me.
Fatal error: Class 'MongoDB\Driver\Manager' not found in H:\xampp\htdocs\www\phpmongodb\vendor\mongodb\mongodb\src\Client.php on line 81
I had the same error before I set up the mongodb added the following link to 'vendor/autoload.php'. In many cases you need to check your hosting. It started working after my code looked like the following:
$DB_CONNECTION_STRING="mongodb://YourCredentials";
require '../../vendor/autoload.php';
$manager = new MongoDB\Driver\Manager( $DB_CONNECTION_STRING );
Then if you use MongoDB\Driver\Manager, a modern version of MongoDB driver, you have something looks such as this:
Create a document in the collection:
$bulkWrite = new MongoDB\Driver\BulkWrite;
$doc = ['name' => 'John', age => 33, profession => 'Guess what?'];
$bulkWrite->insert($doc);
$manager->executeBulkWrite('db.MyCollection', $bulkWrite);
Read document in the collection by name with a limit:
$filter = ['name' => 'John'];
$options = ['limit' => 2];
$query = new MongoDB\Driver\Query($filter, $options);
$manager->executeQuery('db.MyCollection', $query);
Read document in the collection by MongoDb _id with a limit:
$filter = ['_id' => new MongoDB\BSON\ObjectID( '5bdf54e6d722dc000f0aa6c2' )];
$options = ['limit' => 2];
$query = new MongoDB\Driver\Query($filter, $options);
$manager->executeQuery('db.MyCollection', $query);
Update document in the collection: (Read more about options upsert and multi here)
$bulkWrite = new MongoDB\Driver\BulkWrite;
$filter = ['name' => 'John'];
$update = ['$set' => ['name' => 'Smith', age: 35, profession => 'Guess what?']];
$options = ['multi' => false, 'upsert' => false];
$bulkWrite->update($filter, $update, $options);
$manager->executeBulkWrite('db.MyCollection', $bulkWrite);
Delete document in the collection - Delete:
$bulkWrite = new MongoDB\Driver\BulkWrite;
$filter = ['name' => 'John', age => 35];
$options = ['limit' => 1];
$bulkWrite->delete($filter, $options);
$manager->executeBulkWrite('db.MyCollection', $bulkWrite);
Okay, had no luck with the ZETA email client, so now I tried installing the Horde IMAP Client library. I've managed to login to my account, and make a search for e-mails, also got back the results, but I don't know how to fetch the email data, and the documentation is not really helping:|
I presume that I would have to use the Horde_Imap_Client_Base::fetch() method to get some e-mails, which accepts two parameters, a mailbox name, and a Horde_Imap_Client_Fetch_Query object, but I don't know how to get this second object:|
Should this object be returned by one of the Base functions, or should I build this object with the query parameters I want? If the second, how should I rebuild my search query in the fetch query object from the below example?
Here's how I am searching my INBOX, for mails from a specific contact on a specific day:
$client = new Horde_Imap_Client_Socket(array(
'username' => 'my.email#address.com',
'password' => 'xxxxxxxxxx',
'hostspec' => 'my.mail.server',
'port' => '143',
'debug' => '/tmp/foo',
));
$query = new Horde_Imap_Client_Fetch_Query();
$query->dateSearch(new Date(), Horde_Imap_Client_Search_Query::DATE_ON);
$query->headerText("from","mycontact#contact.email");
$results = $client->search('INBOX', $query);
The Horde_Imap_Client_Base::search() returns an array, which contains the search results(the message id's of the searched emails), and some additional data.
Not completely answering your questions. This is how I search for messages which are not deleted.
$client = new Horde_Imap_Client_Socket(array(
'username' => $user,
'password' => $pass,
'hostspec' => $server,
'secure' => 'ssl'
));
$query = new Horde_Imap_Client_Search_Query();
$query->flag(Horde_Imap_Client::FLAG_DELETED, false);
$results = $client->search('INBOX', $query);
foreach($results['match'] as $match) {
$muid = new Horde_Imap_Client_Ids($match);
$fetchQuery = new Horde_Imap_Client_Fetch_Query();
$fetchQuery->imapDate();
$list = $client->fetch('INBOX', $fetchQuery, array(
'ids' => $muid
));
var_dump($list);
}
$results = $client->search($mailbox, $searchquery, array('sort' => array($sSortDir, $sSort)));
$uids = $results['match'];
for ($i = $i_start; $i < $i_to; $i++)
{
$muid = new Horde_Imap_Client_Ids($uids->ids[$i]);
$list = $client->fetch($mailbox, $query, array(
'ids' => $muid
));
$flags = $list->first()->getFlags();
$part = $list->first()->getStructure();
$map = $part->ContentTypeMap();
$envelope = $list->first()->getEnvelope();
}
I am doing a update on my framework. Previously i am using zf1 zend db select for my data access object class. Now, i would like to make a shift and upgrade to zf2. I have problems translating for the insert, update, select, and delete queries and wonder if someone can shed some light to assist me.
What are the new classes that i should use?
Does it involve alot of re-coding?
Any references will helps alot ( Been looking through stackoverflow, but haven found a comprehensive guide)
Below is my code for insert/update/delete/select for zf1
Insert
$userdata = array('email' => $email,
'name' => $name,
'gender' => $gender,
'location' => $location,
'fbid' => $fbid,
'ipaddress' => $ipaddress,
'jointimestamp'=>new Zend_Db_Expr('NOW()'));
$this->dbo->insert('users', $userdata);
return $this->dbo->lastInsertId();
Select
if($this->dbo->fetchOne('SELECT id FROM users WHERE username = ?',$username)){
return true;
}else{
return false;
}
Update
$userdata = array($field => $value);
$this->dbo->update('user', $userdata, $this->dbo->quoteInto('useremail = ?', $this->user));
Also, does zf2 has fetchall, fetchone, fetchrow methods etc?
Appreciate any advices.
After reading the documentation, i have come out with the insert/select/update queries for zf2. Below is the code snippet for benefit of those who may need it in future. I am using Zend\Db\Select as a standalone classes for my custom mvc framework.
Adapter
$adapter = new Zend\Db\Adapter\Adapter(array(
'driver' => 'pdo_mysql',
'host' => DB_HOST,
'database' => DB_PREFIX.DB_NAME,
'username' => DB_USER,
'password' => DB_PW
));
Select
$select = $this->sql->select()
->from('table')
->join('users', 'users.id = table.userid')
->order("table.createdtimestamp DESC");
$statement = $this->sql->prepareStatementForSqlObject($select);
$result = $statement->execute();
$resultSet = new ResultSet();
$resultSet->initialize($result);
return $resultSet->toArray();
Insert
$insert = $this->sql->insert()
->into("messages");
$userdata = array(
'message' => $message,
'createdtimestamp'=>new Zend\Db\Sql\Expression('NOW()'),
'userid' => $userid);
$insert->values($userdata );
$statement = $this->sql->prepareStatementForSqlObject($insert);
$result = $statement->execute();
//return last insert id
return $this->dbo->getDriver()->getLastGeneratedValue();
Update
$update = $this->sql->update()
->table('posts')
->where(array('pid'=>$pid));
$numbercountarr = array('numbercount' => new Zend\Db\Sql\Expression('numbercount+ 1'));
$update->set($numbercountarr );
$statement = $this->sql->prepareStatementForSqlObject($update);
result = $statement->execute();
To count rows
$statement = $this->sql->prepareStatementForSqlObject($query);
$result = $statement->execute();
return $result->count();
Hope this can help those who need it save some time.
As anyone any idea on how to update a table in google fusion using Zend framework?
I can get the data:
$url = "https://www.google.com/fusiontables/api/query?sql=SELECT%20name%20FROM%201695591";
$data = $gdata->get($url);
$postcodes = $data->getRawBody();
But have no idea how to update a row ...
I know I have to 'call' this url, but no idea how :
UPDATE table_id
SET column_name = value {, column_name = value }*
WHERE ROWID = row_id
Thank you
Try this class http://barahlo.semero.com/description/Zend_Gdata_Fusion.zip
Example of usage:
$client = Zend_Gdata_ClientLogin::getHttpClient('your_login_here#gmail.com', 'your_pass_here', 'fusiontables');
$base = new Zend_Gdata_Fusion($client);
$sql = "SELECT ROWID FROM 596524 WHERE id = 1;";
$rowdata = $base->query($sql)->get_array();
print_r($rowdata);
$newRowId = $base->insertRow('596524',array(
'id' => time(),
'name' => 'trird row',
'added' => date('n/j/y'),
) );
$base->updateRow(
'596524',
array('name' => 'new first row'),
$rowdata[1][0] //ROWID from insert query
);
Oauth login for Zend_Gdata:
$oauthOptions = array(
'requestScheme' => Zend_Oauth::REQUEST_SCHEME_HEADER,
'version' => '1.0',
'signatureMethod' => 'HMAC-SHA1',
'consumerKey' => $CONSUMER_KEY,
'consumerSecret' => $CONSUMER_SECRET
);
$consumer = new Zend_Oauth_Consumer($oauthOptions);
$token = new Zend_Oauth_Token_Access();
$client = $token->getHttpClient($oauthOptions,null);
$base = new Zend_Gdata_Fusion($client);
// ...
Also, there is official php client library http://code.google.com/p/fusion-tables-client-php/