Yii2-mongodb: How to catch mongodb insert returned mongo id - mongodb

I would like to get the mongodb insert returned id for further insert specific operation my code is this:
$collection1 = $collection->insert(['username' => $this->email,
'password' =>sha1($this->input_password), 'full_name' => $this->full_name
'time_created' => '', 'time_updated' => '', 'time_last_visited' => '']);
when i does var_dump($collection1) function it shows me output
object(MongoId)#92 (1) { ["$id"]=> string(24) "54ba2b2c64363d640f000031" }
but when i try to access the id it shows me errors
i tried following options:
$insert_id = $collection1->primaryKey();
$insert_id = $collection1->getLastInsertID();
$id = $collection1->id;
$id = (string)$collection1['id'];
$id = $collection1['_id'];
but no options work. What is the right way?

Well i got my answer i tried another one differently & that works.
$id = (string) $collection1;
This returns me the string formatted mongoId.

$id = $collection->insert($data);

Related

WordPress API passing email argument issue

Using a WordPress REST API custom endpoint, I am attempting to get user data (or at least the user id) with the following code in the functions.php file:
function getUser(WP_REST_Request $request) {
global $wpdb;
$email = $request->get_param( 'email' );
$query = "SELECT * FROM wp_users WHERE user_email = $email";
$result = $wpdb->get_results($query);
return $result;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'myapi/v1', '/getcustomer/(?P<email>[^/]+)', array(
'methods' => 'GET',
'callback' => 'getUser'
) );
} );
Testing the function with the endpoint /wp-json/myapi/v1/getcustomer/joe#anymail.com it returns with empty brackets [ ]. Am I missing something here? Any help would be greatly appreciated.
There are multiple issues with your code:
You should encode your user emails or send it via POST method.
Your current query is open to SQL Injection
Your value must be enclosed in quotes. Now it translates to .. WHERE user_email = joe#anymail.com and that is SQL syntax error.
So your code should look like this:
$query = "SELECT * FROM wp_users WHERE user_email = %s";
$result = $wpdb->get_results($wpdb->prepare($query, $email));

How to set custmer id for an quote in magento?

I am adding product into cart and tried to map customer id,email to that quote
using the below code
$product_id = 123;
$qty = 1;
$product = Mage::getModel('catalog/product')->load($product_id);
$cart = Mage::getModel('checkout/cart');
$cart->init();
$superAttributeArray = array('151' => '3');
$params = array(
'product' => $product_id,
'qty' => $qty,
'super_attribute' => $superAttributeArray
);
$cart->addProduct($product, $params);
$cart->save();
$currenQuoteId = Mage::getSingleton('checkout/session')->getQuoteId();
$store = Mage::getSingleton('core/store')->load(Mage::app()->getStore()->getId());
$quote = Mage::getModel('sales/quote')->setStore($store)->load($currenQuoteId);
$quote->setCustomerId('1')->setCustomerEmail('test#gmail.com')->setCustomerFirstname('firstname')->setCustomerLastname('lastname');
$quote->save();
When I try to set customerid,email,fname,lname am getting error as "Mage registry key "controller" already exists".
Can anyone help me in fixing this issue?
Something like this might work
$customerObj = Mage::getModel('customer/customer')->load($customerId);
$quoteObj = Mage::getModel('sales/quote')->assignCustomer($customerObj);
$storeId = Mage::app()->getStore()->getId();
$quoteObj->setStore(Mage::getSingleton('core/store')->load($storeId);
$productObj = Mage::getModel('catalog/product')->load($productId);
$quoteItem = Mage::getModel('sales/quote_item')->setProduct($productObj);
$quoteItem->setQuote($quoteObj);
$quoteItem->setQty('1');
$quoteItem->setStoreId($storeId);
$quoteObj->addItem($quoteItem);
$quoteObj->setStoreId($storeId);
$quoteObj->collectTotals();
$quoteObj->save();

Last insert id return error in Yii

I just executed some code in controller, and try to find the last inserted id.
But it display s error :
This is my code:
$sql = 'INSERT into "Tbl_Community" ("User_id","Community_name") VALUES (10,'new community')';
$connection = Yii::app() -> db;
$command = $connection -> createCommand($sql);
$command -> execute();
echo $connection->getLastInsertID();
The error:
[message:protected] => SQLSTATE[42602]: Invalid name: 7 ERROR: invalid name syntax
[string:Exception:private] =>
[code:protected] => 42602
[file:protected] => D:\wamp\www\Tiein\framework\db\CDbConnection.php
[line:protected] => 548
[trace:Exception:private] => Array
(
[0] => Array
(
[file] => D:\wamp\www\Tiein\framework\db\CDbConnection.php
[line] => 548
[function] => lastInsertId
[class] => PDO
[type] => ->
[args] => Array
(
[0] =>
)
)
with postgresql you can't get last by this way
$lastId= Yii::app()->db->getLastInsertID();
try this (tbl_user_group_id is your table id column and _seq is for postgresql)
$lastId = Yii::app()->db->getLastInsertID('tbl_user_group_id_seq');
OR
$lastId= Yii::app()->db->getCommandBuilder()->getLastInsertID('{{tablename}}') ;
Besides what user714965 pointed out, I usually put the parameters in execute just to make sure they are used properly by PDO. If you write SQL command like in your example and you read the parameters from a form it is problematic.
Yii::app()->db->createCommand('INSERT into "Tbl_Community" ("User_id","Community_name") VALUES (:User_id,:Community_name)')->execute(array(":User_id"=>10, ":Community_name"=>"new community"));
$id = Yii::app()->db->getLastInsertID();
Finally I got the solution :
$sql = 'INSERT into "Tbl_Community" ("User_id","Community_name") VALUES (10,\'new community\')';
$connection = Yii::app() -> db;
$command = $connection -> createCommand($sql);
$command -> execute();
$id = $connection->getCommandBuilder()->getLastInsertID('{{Tbl_Community}}');
echo $id;
PDO::lastInsertID() requires the name parameter when used with PDO_PGSQL so need to replace this code Yiii::app()->db->getLastInsertID(); by Yii::app()->db->getCommandBuilder()->getLastInsertID('{{tablename}}') ;
Refer this link
It may be too late to reply to this thread. But here is the case.
As Per the user 'Always Sunny' you can send the 'Sequence Name' by hardcoding, but that's not a good coding practice.
As per the user 'Kitchu' the use of 'getCommandBuilder' is good, because, provided the 'TableName', it will query the Schema and finds out the 'Sequence Name'. It will inturn query the CDBCommand's 'getLastInsertId' by passing the 'Sequence Name'
One thing to ensure that it, if you have not defined the 'Primary Key' on the table, then you will end up getting the value as 'NULL'

Facebook New PHP SDK For Graph API - Multi Query

I'm at my wits end in what the queries parameter value should look like. So to sumbit a multiquery accross the graph API library, the following would be the code method to perform it, as far as I can tell.
$param = array(
'method' => 'fql.multiquery',
'queries' => $multiQuery,
'callback' => '');
$queryresults = $facebook->api($param);
Using this method in the new PHP SDK library from Facebook, has any one made this work? If so can you drop an example on how you build the complete value of the $multiQuery variable?
I've been struggeling with this for a few days and I'm only finding exmaples with the old PHP library.
Why is it always after banging your head for days, you ask a question, and 5 minutes later, you come up with the answer your self.
So here was MY lovely experience.
Since in PHP you can use a "/' character to start a text string, I got my self stuck in the flip flopping of the double quote character and single quote character. It dawned on me that the queries defined in a multi query are, duh, wrapped by double quotes.
So lesson learned? If you have a where clause that uses a string value in a multi query, make sure for pete's sake you use SINGLE QUOTES around the string value your filtering on.
BAD BAD - This is what I did. note the double quotes around myvalue and myothervalue. NAUGHTY!
$multiQuery = {
"query1":"select something from something where somecolumn = "myvalue"",
"query2":"select something from something where somecolumn = "myothervalue""
};
GOOD Example - Now look at myvalue and myothervalue.
$multiQuery = {
"query1":"select something from something where somecolumn = 'myvalue'",
"query2":"select something from something where somecolumn = 'myothervalue'"
};
So now I can...
$multiQuery = {
"query1":"select something from something where somecolumn = 'myvalue'",
"query2":"select something from something where somecolumn = 'myothervalue'"
};
$param = array(
'method' => 'fql.multiquery',
'queries' => $multiQuery,
'callback' => '');
$queryresults = $facebook->api($param);
And if any of you are wondering what is the actual type of the $multiQuery variable is (for newbie like me), it's just a string data type. It's not an array, nothing more nifty than text.
Considering an array of node id's with their respective url's as values you'll have
/**
*A JSON-encoded dictionary of the queries to perform. The array contains a set of key/value pairs.
*Each key is a query name, which can contain only alphanumeric characters and optional underscores.
*Each key maps to a value containing a traditional FQL query.
*/
$fql = '{';
foreach ($path as $key1 => $value1) {
$fql .= '"' . $key1 . '":"SELECT share_count, like_count, comment_count, total_count FROM link_stat WHERE url=\'' . $value1 . '\'",';
}
$fql .= '}';
$param = array(
'method' => 'fql.multiquery',
'queries' => $fql,
'callback' => ''
);
try {
$fqlresult = $facebook->api($param);
} catch (FacebookApiException $e) {
watchdog('Facebook Query', 'Parsing error on node #node | #error', array('#node' => $key1, '#error' => $e), WATCHDOG_DEBUG); }
You can try this:
$multiQuery= array ("query1" => "query #1 goes here","query2" => "query #2 goes here");
$param = array(
'method' => 'fql.multiquery',
'queries' => $multiQuery,
'callback' => '');
$queryresults = $facebook->api($param);

Zend framework group by

I'm trying to do a group by using Zend framework. Here's my code:
$table = new TableClass();
$select = $table->select();
$select->from ("table", array("date", "column1" => "sum(column1)"));
$select->group ( array ("date") );
$results = $table->fetchAll ($select);
$result = $results[0];
$date = $result->date;
$column1 = $result->column1;
TableClass extends 'Zend_Db_Table_Abstract'.
I can see the query by looking at the mysql query log. The query is well formed - column1 is named in the query and the results look correct if I run the query in mysql workbench.
I cannot access the data in 'column1' - I always get this exception:
Uncaught exception 'Zend_Db_Table_Row_Exception' with message 'Specified column "column1" is not in the row'
I can however access the date column without issue.
I tried:
accessing the columns by array index:
$result[0]
but you get an exception (can't access the columns by index).
not using a column alias:
$select->from ("table", array("date", "sum(column1)"));
$column1 = $result["sum(column1)"];
but you get an exception (no such column "sum(column1)").
throwing in a Zend_Db_Expr:
"column1" => new Zend_Db_Expr ( "sum(column1)" )
but this doesn't help.
Some other examples I have seen suggest the use of the column names without aggregate functions, ie. "column1" instead of "sum(column1)" but that doesn't seem to me to be the answer - the query doesn't have any aggregate functions in it so mysql won't know what to do with it.
Any help appreciated.
Firstly, a quick tip for working with Zend_Db_Select (and by extension Zend_Db_Table_Select), you can view the generated SQL by invoking the toString method. It is vital to verify that your code generates the correct query before working with a result set:
$select = $table->select();
$select->from ("table", array("date", "column1" => "sum(column1)"));
$select->group ( array ("date") );
$sql = (string) $select; //Retrieve SQL as a string
Or simply
die($select); //print SQL
I wrote the following test script using your example and have no problems:
class Table extends Zend_Db_Table_Abstract
{
protected $_primary = 'id';
protected $_name = 'table';
}
$db = Zend_Db::factory('Pdo_Mysql', array(
'dbname' => 'test',
'username' => 'root',
'password' => '',
'host' => 'localhost'
));
$table = new Table($db);
$select = $table->select();
$select->from ($table, array("date", "column1" => new Zend_Db_Expr("sum(column1)")));
$select->group ( array ("date") );
$sql = (string) $select;
echo $sql;
$results = $table->fetchAll ($select);
$result = $results[0];
$date = $result->date;
$column1 = $result->column1;
echo '<br>' . $date . ': ' . $column1;
Use Zend_Debug::dump($result); to inspect data inside the Zend_Db_Table_Row if necessary.
In my case the SQL generated is as follows:
SELECT `table`.`date`, sum(column1) AS `column1` FROM `table` GROUP BY `date`