i am getting a fetchAll when using PHQL.
is there anyway to set it to just a fetch?
$result = $this->modelsManager->executeQuery ( $phql , [ "id" => $id ] );
i have to set the results to: return $result[0];
cheers.
try with:
$phql = "SELECT * FROM \Models\News AS n WHERE n.id = :id:";
$singleResult = $this->modelsManager->executeQuery($phql, ['id' => 3])->getFirst();
Related
I have two tables: products and current_product_attribute_values
I have tried a join query to filter them as per attribute selected by the user but when I try this with an additional condition it gives me 2 results instead of one it is including the first one which is not matching as per query:
select * from `products` inner join `current_product_attribute_values` on `products`.`id` = `current_product_attribute_values`.`product_id` where `current_product_attribute_values`.`attribute_id` = ? or `current_product_attribute_values`.`attribute_value_id` = ? and `current_product_attribute_values`.`attribute_id` = ? or `current_product_attribute_values`.`attribute_value_id` = ? and `product_name` LIKE ?
here is my laravel Controller code :
$all = Input::all();
$q = Input::get('search_text');
$att_val = Input::get('attribute_value');
$subcat = Input::get('subcat_id');
$subcat_name = DB::table('subcategories')->where('id', $subcat)->value('subcategory_name');
$brandname = DB::table('brands')->where('subcat_id', $subcat)->value('brand_name');
$brand_id = DB::table('brands')->where('subcat_id', $subcat)->value('id');
$product_count = DB::table('products')->where('brand_id', $brand_id)->count();
if ($q != "") {
// getting multiple same name params
$query = DB::table('products');
$query->join('current_product_attribute_values', 'products.id', '=', 'current_product_attribute_values.product_id');
$j = 0;
foreach ($all as $key => $values) {
//echo 'my current get key is : ' . urldecode($key). '<br>';
if ($key == $name[$j]) {
$query->where('current_product_attribute_values.attribute_id', '=', $att_id_value[$j]);
echo'<br>';
print_r($query->toSql());
echo'<br>';
//echo '<br> key matched and have some value : <br>';
//echo count($values);
if (count($values) >= 1) {
//echo '<br> it has array inside <br>';
foreach ($values as $val) {
// or waali query in same attribute
echo'<br>';
$query->orwhere('current_product_attribute_values.attribute_value_id', '=', $val);
print_r($query->toSql());
echo'<br>';
}
}
$j++;
}
}
$records = $query->toSql();
$query->where('product_name', 'LIKE', '%' . $q . '%');
$records = $query->toSql();
print_r($records);
$products = $query->paginate(10)->setPath('');
$pagination = $products->appends(array(
'q' => Input::get('q')
));
if (count($products) > 0) {
$filters = DB::table('product_attributes')->where('subcategory_id', $subcat)->get(['attribute_title']);
} else {
$filters = array();
}
$categories = categories::where('add_to_menu', 1)->with('subcategories')->with('brands')->get();
$categoryhome = categories::where('add_to_menu', 1)->with('subcategories')->get();
return view('searchfilter')
->with('productsdata', $products)
->with('filtersdata', $filters)
->with('categories', $categories)
->with('categorieshome', $categoryhome)
->with('subcat_name', $subcat_name)
->with('subcat_id', $subcat)
->with('brandname', $brandname)
->with('product_count', $product_count)
->with('querytext', $q);
}
return 'No Details found. Try to search again !';
its easier if you use raw sql as calling db select function. ex:
$query=DB::select("select * from `products` inner join `current_product_attribute_values` on `products`.`id` = `current_product_attribute_values`.`product_id` where `current_product_attribute_values`.`attribute_id` = ? or `current_product_attribute_values`.`attribute_value_id` = ? and `current_product_attribute_values`.`attribute_id` = ? or `current_product_attribute_values`.`attribute_value_id` = ? and `product_name` LIKE ?
");
indeed you can concat vars in raw sql if you need to, ex:
$queryBrands = "select id from brands where subcat_id =".$subcat;
//echo $queryBrands
$queryBrands = DB::select($queryBrands);
By looking at your tables, product table with id value 17 has two records in table current_product_attribute_values in column product_id (I assume this column is used as foreign key to product table).
With select *, you select all of the columns from both tables. So it would most likely cause your query to return multiple records.
My suggestions:
Only select the columns you need. Avoid using select * in the long run, i.e. select product.id, product.description, current_product_attribute_values.attribute_values ......
Make use of GROUP BY
Hope these helps.
Hi everyone I've some problems with a PDO query in access.
$result1 = $database->prepare('SELECT * FROM tblDestinazioni INNER JOIN tblRagioneSociale ON tblDestinazioni.id_cliente = tblRagioneSociale.id_cliente');
//$result1->execute(array(':nrags' => $rag, ':ndrags' => $nuovadest));
$result1->execute();
in this way it works, but i have to insert two more conditions... so:
$result1 = $database->prepare('SELECT * FROM tblDestinazioni INNER JOIN tblRagioneSociale ON tblDestinazioni.id_cliente = tblRagioneSociale.id_cliente WHERE tblDestinazioni.nome_dest=ndrags AND tblRagioneSociale.nomer=nrags');
$result1->execute(array(':nrags' => $rag, ':ndrags' => $nuovadest));
But it doesn't work (It returns to me a wrong result).
Please help me,
Thanks a lot
tblDestinazioni:
id_destinazioni INT AUTO_INCREMENT(PK)
id_cliente INT(FK)
nome_dest VARCHAR(30)
tblRagioneSociale:
id_cliente INT(PK)
rags VARCHAR(30)
more code:
<?php
$db_username = ''; //username
$db_password = ''; //password
$database_path = "Z:\\2017datiW.mdb";
$database = new PDO("odbc:DRIVER={Microsoft AccessDriver(*.mdb)}; DBQ=$database_path; Uid=$db_username; Pwd=$db_password;");
$rag=$_POST["rag"];
$nuovadest=$_POST["nuovadest"];
$result1 = $database->prepare('SELECT * FROM tblDestinazioni INNER JOIN tblRagioneSociale ON tblDestinazioni.id_cliente = tblRagioneSociale.id_cliente');
$result1->execute(array(':nrags' => $rag, ':ndrags' => $nuovadest));
?>
I have several tables that have JSON arrays stored within fields.
Using PHP PDO I am able to retrieve this data without issue using:
$query1 = $database->prepare("SELECT * FROM module_settings
WHERE project_token = ? AND module_id = ? ORDER BY id DESC LIMIT 1");
$query1->execute(array($page["project_token"], 2));
$idx = $query1->fetch(PDO::FETCH_ASSOC);
$idx["settings"] = json_decode($idx["settings"]);
This returns a string like:
{"mid":"","module_id":"1","force_reg_enable":"1","force_reg_page_delay":"2"}
Attempting to gather the same data via PhalconPHP
$result = Modulesettings::findFirst( array(
'conditions' => 'project_token = "' . $token . '"' ,
'columns' => 'settings'
) );
var_dump($result);
Provides a result of
object(Phalcon\Mvc\Model\Row)#61 (1) { ["settings"]=> string(167) "{"text":"<\/a>
<\/a>
","class":""}" }
What do I need to do different in Phalcon to return the string as it is stored in the table?
Thank you.
You have 2 approach
First :
Get the settings with this structure :
$settings = $result->settings;
var_dump($settings);
Second :
First get array from resultset, then using the array element :
$res = $result->toArray();
var_dump($res['settings']);
Try it.
You can decode json right in your Modulesettings model declaration:
// handling result
function afterFetch() {
$this->settings = json_decode($this->settings);
}
// saving. Can use beforeCreate+beforeSave+beforeUpdate
// or write a Json filter.
function beforeValidation() {
$this->settings = json_encode($this->settings);
}
In Symfony2 and Doctrine I would like to execute a query that returns a count and a group by.
Here's what I've tried. This is the SQL I want to run:
SELECT `terrain_id` , COUNT( * )
FROM `Partie`
WHERE 1 =1
GROUP BY `terrain_id`
With my entity:
class Partie
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Gp\UserBundle\Entity\User",
inversedBy="parties", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* #ORM\ManyToOne(targetEntity="Gp\JeuxBundle\Entity\Terrain")
*/
private $terrain;
This is my PartieRepository
public function getTest(\Gp\UserBundle\Entity\User $user){
return $this->createQueryBuilder('p')
->select('count(p), p.terrain')
->where('p.user = :user')
->setParameter('user', $user)
->groupBy('r.terrain')
->getQuery()
->getResult();
}
This is the error I get:
[Semantical Error] line 0, col 19 near 'terrain FROM': Error:
Invalid PathExpression. Must be a StateFieldPathExpression.
You'll probably want to go with a Native Query
$sql = "SELECT terrain_id as terrain,
count(*) AS count "
."FROM Partie "
."GROUP BY terrain_id;";
$rsm = new ResultSetMapping;
$rsm->addScalarResult('terrain', 'terrain');
$rsm->addScalarResult('count', 'count');
$query = $this->_em->createNativeQuery($sql, $rsm);
return $query->getResult();
Just add in any having / where clauses as needed.
The following is my result:
Array
(
[0] => Array
(
[terrain] =>
[count] => 7
)
[1] => Array
(
[terrain] => 1
[count] => 5
)
[2] => Array
(
[terrain] => 2
[count] => 1
)
)
The lack of terrain in the first array is due to null terrain_id.
EDIT
OP has unexpected results, so here are some troubleshooting steps:
1) Try a var_dump($query->getSQL()); right before the return statement, and run the SQL directly against your DB. If this produces incorrect results, examine the query and alter the $sql as appropriate.
2) If #1 produces correct results, try a var_dump($query->getResult()); right before the return statement. If this produces correct results, something is going on deeper in your code. It's time to look at why terrain is being filtered. It may be as simple as removing or changing the alias in SQL and addScalarResult.
3) Try an even simpler function:
$sql = "SELECT distinct(terrain_id) FROM Partie;";
$rsm = new ResultSetMapping;
$rsm->addScalarResult('terrain_id', 'terrain_id');
$query = $this->_em->createNativeQuery($sql, $rsm);
var_dump($query->getSQL());
var_dump($query->getResult());
return $query->getResult();
This error occurs on this line : select('count(p), p.terrain') where you are trying to use p alias that doesn't exist anymore. The select method override the default alias of the createQueryBuilder(). To avoid this, use addSelect instead or specify clearly the from method.
Try this :
public function getTest(\Gp\UserBundle\Entity\User $user){
return $this->createQueryBuilder('p')
->addSelect('count(p), p.terrain')
->where('p.user = :user')
->setParameter('user', $user)
->groupBy('r.terrain')
->getQuery()
->getResult();
}
or this :
public function getTest(\Gp\UserBundle\Entity\User $user){
return $this->createQueryBuilder('p')
->select('count(p), p.terrain')
->from('YourBundle:YourEntity', 'p')
->where('p.user = :user')
->setParameter('user', $user)
->groupBy('r.terrain')
->getQuery()
->getResult();
}
How to execute a raw Query with count and group by:
Hook onto your manager and make a new connection:
$manager = $this->getDoctrine()->getManager();
$conn = $manager->getConnection();
Create your query and fetchAll:
$result= $conn->query(
'select count(p.id) foobar, p.myid from foobartable p group by p.myid'
)->fetchAll();
Get the data out of result like this:
$this->appendStringToFile("first row foobar is: " . $result[0]['foobar']);
I have a basic MySQL database table People with 3 columns (ID, Name, Distance)
I am trying to output this with PHP as a JSON so my web app can pick it up. I tried using the solution from another answer:
$sth = mysql_query($con,"SELECT * FROM People");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
However I am just returning a blank array of [].
Update: Changed to mysqli and added dumps:
$sth = mysqli_query("SELECT * FROM Events",$con);
$rows = array();
var_dump($sth);
while($r = mysqli_fetch_assoc($sth)) {
var_dump($rows);
$rows[] = $r;
}
print json_encode($rows);
Returns:
NULL []
Swap your query and connection in the mysql_query-statement:
$sth = mysql_query("SELECT * FROM People", $con);
Besides that, the mysql-library is deprecated. If you're writing new code consider using mysqli_ or PDO.
Why no mysql_connect ?
var_dump($sth); // check the return of mysql_query()
var_dump($rows); // check the array of mysql_fetch_assoc result
I would check if your query is returning any rows first.
<?php
$rows = array();
array_push($rows, array("name" => "John"));
array_push($rows, array("name" => "Jack"));
array_push($rows, array("name" => "Peter"));
print json_encode($rows);
?>
Produces this output.
[{"name":"John"},{"name":"Jack"},{"name":"Peter"}]
Solved using a combination of answer to get:
$sth = mysqli_query($con,"SELECT * FROM Events");
$datarray = array();
while($row = mysqli_fetch_assoc($sth)) {
$datarray[] = $row;
}
print_r(json_encode($datarray));