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.
Related
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();
}
$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
I need to create a PHP OData producer supporting both GET and PUT. Up to now I've only found this library, unfortunately this not support PUT operation.
Any suggestions?
Thank's
Currently there's no PHP Library (public) available to support OData CUD (Change, Update and Delete) operations.
Just released. Documentation is coming.
https://packagist.org/packages/falseclock/dbd-php
$cache = DBD\Cache\MemCache::me()->create(array(['host' => '127.0.0.1', 'port' => 11211]),false,"15 min")->open();
$odata_options = array(
'RaiseError' => true,
'PrintError' => true,
'HTMLError' => true,
'CacheDriver' => $cache
);
$od = (new DBD\OData())->create('http://crm.beta.virtex.kz/odata/', "user", "password", $odata_options);
$sth = $od->prepare("
SELECT
Ref_Key, Number, Date
FROM
Document_Invoices
ORDER BY
Date аsc
LIMIT 10
");
$sth->cache('CacheKey','24h');
$sth->execute();
while ($row = $sth->fetchrow()) {
print_r($row);
}
$od->update(
'Document_Invoices',
array('Date' => $data['Date']),
"(guid?)",
$data['Ref_Key'] // for ?-placeholder
);
I've got a little PHP script that has the following code in it:
$m = new MongoClient(Settings::$db);
$db = $m->db;
// get the 'customers' collection
$customers = $db->customers;
// determine if this customer already exists
$c = $customers.findOne(array('email' => $email)); <--- throws
if (is_null($c)) {
$customers.insert(array(
'email' => $email,
'firstname' => $firstName,
'lastname' => $lastName
));
}
// get the 'payments' collection
$payments = $db->payments;
// add a record
$payments->insert(array(
'email' => $email,
'firstname' => $firstName,
'lastname' => $lastName,
'amount' => $price,
'token' => $token
));
but it's throwing the error:
PHP Fatal error: Call to undefined function findOne() in ...
Now, I've downloaded and copied into the ext directory the php_mongo.dll file. Further, I've added this line to the php.ini:
extension=php_mongo.dll
and I've since rebooted the server numerous times.
It really feels to me like this findOne method isn't available because the php_mongo extension isn't loaded. But on the other hand, it's not throwing when creating the MongoClient, nor is it throwing when grabbing the database and the collection.
What's going on here?
As per my comment, you likely used another language's method access syntax by mistake:
This
$c = $customers.findOne(array('email' => $email));
is alas PHP so you need the object operator not the dot:
$c = $customers->findOne(array('email' => $email));
I think dot is the mistake.try
$c = $customers->findOne(array('email' => $email));
Hi i am using a PDO wrap object
https://github.com/Xeoncross/DByte/blob/master/example.php
having some issue with Updates features.
This is their defined function for update
static function update($table, $data, $value, $column)
{
$keys = implode('`=?,`', array_keys($data));
if($statement = DB::query(
"UPDATE`$table`SET`$keys`=? WHERE`$column`=?",
array_values($data + array($value))
))
return $statement->rowCount();
}
My function to update
public function update_users($user_id, $user_name, $user_email, $user_role, $user_phone){
$user_data = array(
'user_name' => $user_name,
'user_email' => $user_email,
'user_pass' => $user_pass,
'user_role' => $user_role,
'user_phone' => $user_phone,
);
$result = DB::update('users', $user_data, $user_id);
}
This is not working Error i am getting is,
Warning: Missing argument 4 for DB::update(), called in \XXXClass.php on line 47 and defined in XXXX\Application\inc\DB.php on line 120
You need to pass in the column name (4th argument of the method):
$result = DB::update('users', $user_data, $user_id, 'user_id'); // I presume `user_id` is the name of that column
Also it doesnt hurt to place spaces between SQL keywords and column/table names:
"UPDATE `$table` SET `$keys`=? WHERE `$column`=?"