I am trying to implement basic transaction based queries using Jadell's Neo4jPHP.
Here is my code:
$transaction = $client->beginTransaction();
$query = new Query($client, "CREATE UNIQUE (u:users {email})-[r:visited {'time':'1425283200'}]->(e:halls {hallId}) RETURN r", array('email' => array('email' => 'test#test.com'), 'hallId' => array('hallId' => 1234)));
$result = $transaction->addStatements($query);
$transaction->commit();
I am getting an error:
[message] => Invalid input ''': expected whitespace, a property key
name, '}', an identifier or UnsignedDecimalInteger (line 1, column
52)\n
Any clues as to what is going wrong here?
UPDATE
I tried the following (removed parameters) and still getting an error:
$transaction = $client->beginTransaction();
$query = new Query($client, "CREATE UNIQUE (u:users {'email':'" . $email . "'})-[r:visited]->(e:halls {'hallId':'" . $hallId . "'}) RETURN r");
$result = $transaction->addStatements($query);
$transaction->commit();
Getting an error:
[message] => Unable to deserialize request: Can not deserialize
instance of java.util.LinkedHashMap out of START_ARRAY token\n
This should work.
Use query parameters instead of string concatenation
$transaction = $client->beginTransaction();
$cypher="CREATE UNIQUE (u:users {email:{email}})-[r:visited]->(e:halls {hallId:{hallId}}) RETURN r";
$query = new Query($client,$cypher,array('email'=>$email,'hallId'=>$hallId));
$result = $transaction->addStatements($query);
$transaction->commit();
Related
I am doing a "IN" query using prepared statements on rails. I am getting PG::InvalidTextRepresentation error.
code :
def mark_ineligible(match_ids)
ids = match_ids.join(", ")
result = epr("mark_matches_as_ineligible",
"UPDATE matches SET is_eligibile=false WHERE id IN ( $1 )",
[ids])
end
def epr(statementname, statement, params)
connection = ActiveRecord::Base.connection.raw_connection
begin
result = connection.exec_prepared(statementname, params)
return result
rescue PG::InvalidSqlStatementName => e
begin
connection.prepare(statementname, statement)
rescue PG::DuplicatePstatement => e
# ignore since the prepared statement already exists
end
result = connection.exec_prepared(statementname, params)
return result
end
end
trying to invoke this using :
match_ids = [42, 43]
mark_ineligible match_ids
PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer: "42, 43"
from (irb):24:in `exec_prepared'
from (irb):24:in `rescue in epr'
from (irb):15:in `epr'
from (irb):8:in `mark_ineligible'
from (irb):35
Please help here. I want to know why I am getting this errors and how to fix it.
Thanks,
mark_ineligible should look as follows:
def mark_ineligible(match_ids)
result = epr("mark_matches_as_ineligible",
"UPDATE matches SET is_eligibile=false WHERE id IN ( $1 )", match_ids)
end
And when you call mark_ineligible, pass an array as argument:
mark_ineligible(match_ids) #=>match_ids = [42,43]
Hi Friends i am trying to run twitter apis to get tweets for a hashtag using below code. When i tried get the user timeline it's not giving any error for authentication but when it tried to search for tweets which contains hahstag it's giving authentication error.
$token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$token_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$consumer_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$consumer_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$host = 'api.twitter.com';
$method = 'GET';
$path = '/1.1/statuses/user_timeline.json'; // api call path
$query = array( // query parameters
'screen_name' => 'twitterapi'
);
$oauth = array(
'oauth_consumer_key' => $consumer_key,
'oauth_token' => $token,
'oauth_nonce' => (string)mt_rand(), // a stronger nonce is recommended
'oauth_timestamp' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_version' => '1.0'
);
$oauth = array_map("rawurlencode", $oauth); // must be encoded before sorting
$query = array_map("rawurlencode", $query);
$arr = array_merge($oauth, $query); // combine the values THEN sort
asort($arr); // secondary sort (value)
ksort($arr); // primary sort (key)
// http_build_query automatically encodes, but our parameters
// are already encoded, and must be by this point, so we undo
// the encoding step
$querystring = urldecode(http_build_query($arr, '', '&'));
$url = "https://$host$path";
// mash everything together for the text to hash
$base_string = $method."&".rawurlencode($url)."&".rawurlencode($querystring);
// same with the key
$key = rawurlencode($consumer_secret)."&".rawurlencode($token_secret);
// generate the hash
$signature = rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));
// this time we're using a normal GET query, and we're only encoding the query params
// (without the oauth params)
$url .= "?".http_build_query($query);
$url=str_replace("&","&",$url); //Patch by #Frewuill
$oauth['oauth_signature'] = $signature; // don't want to abandon all that work!
ksort($oauth); // probably not necessary, but twitter's demo does it
// also not necessary, but twitter's demo does this too
function add_quotes($str) { return '"'.$str.'"'; }
$oauth = array_map("add_quotes", $oauth);
// this is the full value of the Authorization line
$auth = "OAuth " . urldecode(http_build_query($oauth, '', ', '));
echo $auth;exit;
// if you're doing post, you need to skip the GET building above
// and instead supply query parameters to CURLOPT_POSTFIELDS
$options = array( CURLOPT_HTTPHEADER => array("Authorization: $auth"),
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
// do our business
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json);
echo "<pre>";print_r($twitter_data);
When i run this code i am successfully able to get the user time line so i wnt for next step to get tweets for a particular hashtag by chnaging code like below
$host = 'api.twitter.com';
$method = 'GET';
$path = '/1.1/search/tweets.json'; // api call path
$query = array( // query parameters
'q' => '#Polls2013'
);
But now it's giving a weird error like below.
stdClass Object
(
[errors] => Array
(
[0] => stdClass Object
(
[message] => Could not authenticate you
[code] => 32
)
)
)
The query you are posting for search should be url encoded in the manner specified by twitter,
See this documentation (https://dev.twitter.com/docs/auth/percent-encoding-parameters)
I am doing like this sql into zend framework sql pattern.
SELECT
jobs . *,
c.id AS cid,
c.name AS name,
c.companyImage AS companyImage,
c.logo AS logo,
count(app.userId) AS t_app,
app.applyStatus AS applyStatus,
app.userId AS appUserId
FROM
jobs
LEFT JOIN
companies AS c ON jobs.companyName = c.id
LEFT JOIN
applicants AS app ON jobs.id = app.jobId AND app.applyStatus = 1
WHERE
jobs.ownerId = 16 AND jobs.draftId != 0
GROUP BY jobs.id
ORDER BY jobs.id DESC
LIMIT 3
For this sql I already write this code for zend framework 2
$adapter = $this->tableGateway->getAdapter();
$sql = new Sql($adapter);
$select = $sql->select();
$select->from('jobs')
->join(array('c' => 'companies'), 'jobs.companyName = c.id', array('cid' => 'id', 'name', 'companyImage', 'logo'), 'left')
->join(array('app' => 'applicants'), ' jobs.id = app.jobId AND app.applyStatus = 1', array('t_app' => new Expression('count(app.userId)'), 'applyStatus', 'appUserId' => 'userId'), 'left')
->where("jobs.ownerId ={$userId} AND jobs.draftId != 0")
->group('jobs.id')
->order('jobs.id DESC')
->limit(3);
$statement = $sql->getSqlStringForSqlObject($select);
$results = $adapter->query($statement, $adapter::QUERY_MODE_EXECUTE);
but does not work properly and its give a message like below.
SQLSTATE[42S22]: Column not found: 1054 Unknown column '1' in 'on clause'
The issue is this part:
app.applyStatus = 1
The framework is escaping 1 as if it were a column name, 1.
You need to enclose this part in an Expression too
new Expression('jobs.id = app.jobId AND app.applyStatus = 1')
I think the use of Expressions in the 'ON' parameter of the join method may depend on the version of ZF2 you are using, I think it was added 2.1+
Building on this answer. If you also want your table & column identifiers to be escaped, use this syntax:
use Zend\Db\Sql\Expression;
...
$onExpression = new Expression('? = ? AND ? = ?',
['jobs.id', 'app.jobId', 'app.applyStatus', 1],
[Expression::TYPE_IDENTIFIER, Expression::TYPE_IDENTIFIER,
Expression::TYPE_IDENTIFIER, Expression::TYPE_LITERAL]
);
$select->from('jobs')
->join(array('app' => 'applicants'), $onExpression, array('t_app' => new Expression('count(app.userId)'), 'applyStatus', 'appUserId' => 'userId'), 'left');
The Expression constructor accepts the string, then arguments, then argument types.
public function __construct($expression = '', $parameters = null, array $types = [])
This will create a security issue. Zf2 changes your query to this:
Select * from tableA inner join tableB
on `tableA`.`column` = `tableB`.`column`
AND `tableB`.`column` = `1`
It adds
`
to each part for security issues! By using new Expression you are bypassing it and if you get applyStatus from user entry, get sure about its filtering!
How to get Sql like this :
select * from foo where LOWER(foo_name) = 'test';
what i get is if Sql\Expression in right, not in left.
You can user code snippet like that.
$where = new Where();
$sql = new Sql($adapter);
$select = $sql->select();
$where->addPredicate(new Predicate\Expression('LOWER(foo_name) = ?', 'test' ));
$select->from('foo')->where($where);
However I dont think Sql\Expression on right side is possible on Zend Framework 2.
You can do it like this:
$sql = new SQL($adaptor);
$select = $sql->select()->from(array('f'=>'foo'));
$select = $select->where('foo_name' => new \Zend\Db\Sql\Expression("LOWER('test')"));
Above query would return as:
SELECT `f`.* FROM `foo` AS `f` WHERE `foo_name` = LOWER('test');
For others out looking for similar, there are actually quite a few different ways to achieve this as of ZF 2.2
Chaining (same as the accepted answer)
<?php
$sql = new Sql($adapter);
$select = $sql->select();
$select->from( array( 'f' => 'foo' ) )
->where
->addPredicate( new Predicate\Expression( 'LOWER(f.foo_name) = ?', 'test' ) );
//SELECT `f`.* FROM `foo` AS `f` WHERE LOWER(f.foo_name) = :where1
//:where1 = 'test'
?>
Note the absence of the execution command "()" of Select::$where allowing you to continue the method chaining.
Select::$where has a __get Magic method catch which returns the protected Select::$_where property within the Select object which is an instance of Sql\Where.
Predicate\Literal 1
<?php
$select->where( "LOWER(f.foo_name) = 'test'" );
//SELECT `f`.* FROM `foo` AS `f` WHERE LOWER(f.foo_name) = 'test'
?>
Predicate\Literal 2
<?php
$select->where( array( "LOWER(f.foo_name) = 'test'" ) );
//SELECT `f`.* FROM `foo` AS `f` WHERE LOWER(f.foo_name) = 'test'
?>
The two above automatically create a Predicate\Literal object for you if the indexed value (column identifier) of the array or argument supplied to the Select::where method is a string.
Predicate\Expression (manual)
<?php
$select->where( new Predicate\Expression( "LOWER(f.foo_name) = 'test'" ) );
//SELECT `f`.* FROM `foo` AS `f` WHERE LOWER(f.foo_name) = 'test'
?>
I started with the ZendSkeletonApplication and added a model extending Zend\Db\TableGateway\TableGateway.
I have the following method:
public function findByType($type) {
$rowset = $this->select('type' => $type);
return $rowset;
}
This works, but now if i do this:
$foo = $table->findBytype('foo');
$bar = $table->findBytype('bar');
the first one works, the query it executes is:
SELECT * FROM table WHERE 'type' = 'foo'
The second one however executes the following query:
SELECT * FROM table WHERE 'type' = 'foo' AND 'type' = 'bar'
is this expected behavior?
If so how can i have the second time i call the method execute the following query:
SELECT * FROM table WHERE 'type' = 'bar'
thanks in advance!
Should use select in tableGateway like this:
$select = $this->getSql()->select();
$select->where(array('type' => 'foo'))
->where(array('type' => 'bar'));
$rowset = $this->selectWith($select);
select() will be reset the where() paramters when you call it next time.
See more usage in my blog:
http://avnpc.com/pages/advanced-database-select-usage-in-zf2