I have a raw sql query code that I want to run using laravel query builder out of laravel :
$q = "SELECT * FROM wp_posts WHERE post_parent = ? ORDER BY ? ? LIMIT ?, ?";
$values = ['40','post_status', "ASC" ,'1','10'];
$q = $db->connection()->select($q,$values);
This query will throw an error saying that
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error
in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near '? LIMIT ?, ?' at line 1 (SQL:
SELECT * FROM wp_posts WHERE post_parent = `40` ORDER BY `post_status` ASC LIMIT 1, 10)
Now, when I copy the query from the error output and paste it in phpmyadmin sql runner it will run without any error .
Any Idea ??
could be post_parent is not a string and don't need backtics
$q = "SELECT * FROM wp_posts WHERE post_parent = ? ORDER BY ? ? LIMIT ?, ?";
$values = [ 40,'post_status', "ASC" ,'1','10'];
If you want to do it with query builder this should work.
$posts = DB::table('wp_posts')->where('post_parent', 40)->orderBy('post_status', 'ASC')->take(10)->get();
Laravel will automatically bind values with PDO.
It seems query builder does not allow to put SQL Commands in binding variables, when I removed 'ASC' out of binding variables it worked :
$q = "SELECT * FROM wp_posts WHERE post_parent = ? ORDER BY ? ASC LIMIT ?, ?";
$values = [40,'post_status', 1,10];
$q = $db->connection()->select($q,$values);
You Can write
$q = "SELECT * FROM wp_posts WHERE post_parent = ? ORDER BY ? ? LIMIT ?, ?";
$values = [ 40,'post_status', "ASC" , 1, 10];
hOPEFULLY THIS WILL SOLVE YOUR Problem
Related
I am very confused about this (returning false):
$sql = "SELECT * from tbl_user WHERE group = 'abc'";
$res = mysql_query($sql);
if(mysql_num_rows($res) > 0) {
$response = array('status' => '1');
} else {
$response = array('status' => '0'); // ---> what I get back
die("Query failed");
}
...despite the fact the field group is present in mySQL database. Even more strange is that the following return the value of group:
$SQL = "SELECT * FROM tbl_user";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['group']; // ---> returns 'abc'
When I execute a WHERE clause with every other fields of my table excepting group (for example WHERE name = 'ex1' AND ID=1 AND isAllowed=0 (and so on...), everything is fine. As soon as I insert group = 'abc', I get nothing...
This makes me mad. If anyone could help... (I am running a local server with MAMP).
Thanks a lot!
The issue is that group is a reserved word in SQL.
For MySql you need to escape it with backticks
`group`
So your query would be
$sql = "SELECT * from tbl_user WHERE `group` = 'abc'";
problem in Mashable Slider Clone plugin when uload it in server
WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 3] SELECT * FROM wp_mash_fields WHERE docid IN()
code for this is
$sql = "SELECT *
FROM $this->flds
WHERE docid IN(".implode(',' , array_keys($r)).")";
$r2 = $this->db->get_results($sql, ARRAY_A);
WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LIMIT 0,999' at line 3] SELECT SQL_CALC_FOUND_ROWS DISTINCT wp_mash_documents.* FROM wp_mash_documents WHERE wp_mash_documents.type='image' ORDER BY wp_mash_documents. LIMIT 0,999;
code for this is
function get($type, $page = 0, $limit = 10, $sort = 'modify_time', $ord = 'ASC', $rel = null, $dorder = false, $s = null)
{
$ll = $page * $limit;
$docs = $this->docs;
$flds = $this->flds;
$rels = $this->rels;
$inner = array();
$where = array();
$order = '';
// get ids
$sql = "SELECT SQL_CALC_FOUND_ROWS DISTINCT $docs.*".($dorder? ",$rels.dorder" : "")." FROM $docs";
switch ($sort) {
case "title":
$inner[$flds] = array("$docs.id", "$flds.docid");
$where["$flds.name"] = "='title'";
$order = "$flds.value_text $ord";
if (isset($s)) {
$where["MATCH ($flds.value_text)"] = " AGAINST ('$s')";
}
Given your error message:
ORDER BY wp_mash_documents. LIMIT 0,999;
^---missing field name
Is there a way to execute a SQL String as a query in Zend Framework 2?
I have a string like that:
$sql = "SELECT * FROM testTable WHERE myColumn = 5"
now I want to execute this string directly.
Just pass the sql string to your db adapter like this:
$resultSet = $adapter->query($sql, \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE);
And if you want to pass parameters:
$sql = "SELECT * FROM testTable WHERE myColumn = ?";
$resultSet = $adapter->query($sql, array(5));
EDIT: Please note that the query method does not always returns a resultset. When its a resultset producing query(SELECT) it returns a \Zend\Db\ResultSet\ResultSet otherwise(INSERT, UPDATE, DELETE, ...) it will return a \Zend\Db\Adapter\Driver\ResultInterface.
And when you leave the second Parameter empty you will get a \Zend\Db\Adapter\Driver\StatementInterface which you can execute.
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);
$select = $sql->select();
$select->from('testTable');
$select->where(array('myColumn' => 5));
$statement = $sql->prepareStatementForSqlObject($select);
$result = $statement->execute();
S. docu: Zend\Db → Zend\Db\Sql
If you are using tableGateway, you can run your raw SQL query using this statement,
$this->tableGateway->getAdapter()->driver->getConnection()->execute($sql);
where $sql pertains to your raw query. This can be useful for queries that do not have native ZF2 counterpart like TRUNCATE / INSERT SELECT statements.
If you have EntityManager $em on your hands, you can do something like this:
$select = $em->getConnection()->executeQuery("
SELECT a.id, a.title, a.announcement, asvc.service_id, COUNT(*) AS cnt,
GROUP_CONCAT(asvc.service_id SEPARATOR \", \") AS svc_ids
FROM article AS a
JOIN articles_services AS asvc ON asvc.article_id = a.id
WHERE
asvc.service_id IN (
SELECT tsvc.service_id
FROM tender AS t
JOIN tenders_services AS tsvc ON tsvc.tender_id = t.id
WHERE t.id = :tenderId
)
GROUP BY a.id
ORDER BY cnt DESC, a.id DESC
LIMIT :articlesCount
", [
'articlesCount' => 5,
'tenderId' => $tenderId,
], [
'articlesCount' => \PDO::PARAM_INT,
]);
$result = $select->fetchAll(); // <-- here are array of wanted rows
I think this way to execute complex queries is best for Zend. But may be I'm not very smart in Zend still. Will glad to see if it helps to someone.
I'm trying to construct a working MySql query with a correlated subquery in zend_db_select (ZF 1.12) to use that in Zend_Paginator_Adapter. The working query is as follows:
SELECT f.*, (SELECT (COUNT(p.post_id) - 1)
FROM `forum_topic_posts` AS p WHERE f.topic_id = p.topic_id) AS post_count
FROM `forum_topics` AS f WHERE f.forum_id = '2293'
ORDER BY post_count DESC, last_update DESC
So i worked out:
$subquery = $db->select()
->from(array('p' => 'forum_topic_posts'), 'COUNT(*)')
->where('p.topic_id = f.topic_id');
$this->sql = $db->select()
->from(array('f' => 'forum_topics'), array('*', $subquery . ' as post_count'))
->where('forum_id=?', $forumId, Zend_Db::PARAM_INT)
->order('post_count ' . $orderDirection);
But Zend stops with the following exception when executing the query:
Zend_Db_Statement_Mysqli_Exception: Mysqli prepare error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT COUNT(*) FROM forum_topic_posts AS p WHERE (p.topic_id = f.to' at line 1
How could i get the subquery to work?
Here is the query written using the Zend_Db OO interface.
The key was mostly using some Zend_Db_Expr objects for the subquery and COUNT function.
$ss = $db->select()
->from(array('p' => 'forum_topic_posts'),
new Zend_Db_Expr('COUNT(p.post_id) - 1'))
->where('f.topic_id = p.topic_id');
$s = $db->select()
->from(array('f' => 'forum_topics'),
array('f.*', 'post_count' => new Zend_Db_Expr('(' . $ss . ')')))
->where('f.forum_id = ?', 2293)
->order('post_count DESC, last_update DESC');
echo $s;
// SELECT `f`.*, SELECT COUNT(p.post_id) - 1 FROM `forum_topic_posts` AS `p` WHERE (f.topic_id = p.topic_id) AS `post_count` FROM `forum_topics` AS `f` WHERE (f.forum_id = 2293) ORDER BY `post_count DESC, last_update` DESC
I have the following DQL query:
$query = Doctrine_Query::create()
->select('p.genre')
->from('Profile p')
->where('sf_guard_user_id = ?', 11);
If I return the SQL syntax with $sql = $query->getSqlQuery(); I get:
SELECT p.id AS p__id, p.genre AS p__genre FROM profile p WHERE (p.sf_guard_user_id = ?)
This is not normal. It should be 11 not ?:
SELECT p.id AS p__id, p.genre AS p__genre FROM profile p WHERE (p.sf_guard_user_id = 11)
And if I write:
$query = Doctrine_Query::create()
->select('p.genre')
->from('Profile p')
->where('sf_guard_user_id = ' . 11);
The SQL syntax is correct.
Normally DQL should do this automatically. Why isn't happening ?
This is how prepared statement works. Values will be bound on database server Hence doctrine can not show the real values with the query.
Doctrine will show a question mark if you use prepared statement not the real value.
Checkout how it is describing here