I have 3 tables: product, product_parameter, product_parameter_item.
Product and product parameter have no foreign references, product_parameter_item has product_id and product_parameter_id.
For example i have 4 products:
1
2
3
4
Product_parametetrs:
1 - Model
2 - Color
Product_parameter_item:
id - product_id - product_paramter_id - value:
1 - 1 - 1 - Toyota
2 - 1 - 2 - white
3 - 2 - 1 - Toyota
4 - 2 - 2 - black
5 - 3 - 1 - Citroen
6 - 3 - 2 - white
7 - 4 - 1 - Citroen
8 - 4 - 1 - black
How can I get all products with Model = Toyota, Color = Black ?
$c->addJoin(ProductPeer::ID, ProductParameterItemPeer::PRODUCT_ID);
$c->addJoin(ProductParameterItemPeer::PRODUCT_PARAMETER_ID, ProductParameterPeer::ID);
foreach ($product_params as $i => $param){
$c1 = $c->getNewCriterion(ProductParameterPeer::ID, $param->getId());
$c2 = $c->getNewCriterion(ProductParameterItemPeer::VALUE, $value);
$c1->addAnd($c2);
$c->addAnd($c1);
}
Doesnt work
$c->addJoin(ProductPeer::ID, ProductParameterItemPeer::PRODUCT_ID);
foreach ($product_params as $i => $param){
$c1 = $c->getNewCriterion(ProductParameterItemPeer::ID, $param->getId());
$c2 = $c->getNewCriterion(ProductParameterItemPeer::VALUE, $value);
$c1->addAnd($c2);
$c->addAnd($c1);
}
Doesnt work either
$c->addJoin(ProductParameterItemPeer::PRODUCT_PARAMETER_ID, ProductParameterPeer::ID);
foreach ($product_params as $i => $param){
$c->add(ProductParameterPeer::ID, $param->getId());
$c->add(ProductParameterItemPeer::VALUE, $value);
}
I have made this function to get ids of products and add them to Criteria. Didnt find another way :(
$product_params = ProductParameterPeer::getParamsForFilter();
$ids = false;
if (count($product_params)){
$sql = '';
$clause = '';
$clauses = array();
$make_query = false;
foreach ($product_params as $i => $param){
if ($values[$param->getAlias()]){
$is_last = end($product_params) == $param;
$sql .= '(SELECT product_id FROM `product_parameter_item` WHERE `value` = "'.$values[$param->getAlias()].'" AND `product_parameter_id` = '.$param->getId().' ) t'.$i.($is_last?' ':', ');
$clauses[] = 't'.$i.'.product_id';
$make_query = 'SELECT t'.$i.'.product_id FROM ';
}
}
if (count($clauses) == 1) $clause = 'WHERE '.$clauses[0];
else if (count($clauses) == 2) $clause = 'WHERE '.$clauses[0].'='.$clauses[1];
else if (count($clauses) > 2){
$clause = 'WHERE ';
for ($i = 1; $i < count($clauses); $i++){
$clause .= '('.$clauses[0].'='.$clauses[$i].')'.($i == count($clauses)-1 ? '' : ' AND ');
}
}
if ($make_query){
$query = $make_query.$sql.$clause;
$con = Propel::getConnection();
$statement = $con->prepare($query);
$statement->execute();
$ids = array();
while($stmt = $statement->fetch(PDO::FETCH_ASSOC)) {
$ids[] = (int)$stmt['product_id'];
}
}
}
return $ids;
Related
i need add subcategory after category in this code:
Help pls
Controller:
public function find_diagnoz() {
$key = $this->input->get('key');
$result = $this->Diagnoz_model->find_diagnoz($key);
foreach ($result as $key => $res) {
/* Категория */
$this_cat = $this->Diagnoz_model->get_categories($res['id']);
if (!$this_cat) {
$rec->cat = false;
continue;
}
$result[$key]['cat'] = $this_cat['names'];
}
$html = '';
foreach ($result as $res) {
$html .= '<li>';
$html .= '<a href="javascript:void(0);" data-id="'.$res['id'].'" data-code="'.md5($res['id'].$res['texts']).'" data-title="'.$res['texts'].'" class="select_td">';
$html .= '<p>'.$res['texts'].'</p>';
$html .= '<p>Из категории: '.$res['cat'].'</p>';
$html .= '</a>';
$html .= '</li>';
}
die(json_encode(array('html' => $html)));
}
Model
For get category name:
public function get_category($id) {
$this_category = $this->db->select('*')
->from('zaloby')
->where('id = '.$id)
->get()->result_array();
if (!isset($this_category[0])) {
return false;
}
return $this_category[0];
}
For get result by key:
public function find_diagnoz($key) {
$res = $this->db->select('*')
->from('zaloby')
->like('names', $key)
->get()->result_array();
return $res;
}
Mysql table have structure:
id parid names text
1 0 name1 desc1
2 1 name2 desc2
3 2 name3 desc3
4 2 name4 desc4
When I search result now, my result:
Name2
In category: Name2
I need result with subcategory:
Name2
In category: Name1 / Name2
Thx, sorry for my bad english.
I need to update month_no fields of the records resulting from a select query using some variables passed from controller but every field is written with the same value.
These are the variables:
$id_calc = 27
$from_y = "2013-05-01"
$to_y = "2015-11-31"
The table result:
id id_paid year_ref month_no
1 26 2012 12
2 26 2013 12
4 27 2013 12 (should be 8)
5 27 2014 12
6 27 2015 12 (should be 11)
This is model:
public function CorrectTable($id_calc, $from_y, $to_y)
{
$connection = Yii::$app->db;
$query = "SELECT * FROM my_table where id_paid='$id_calc'";
$data = $connection->createCommand($query)->queryAll();
// calculate no. of month first and last year
$month_no_begin = (13 - date("m",strtotime($from_y)));
$month_no_end = (date("m",strtotime($to_y)));
//
foreach($data as $row)
{
$id = $row['id'];
// calculate number of month per year
if ($row['year_ref'] = date("Y",strtotime($from_y)))
{
$month_no = $month_no_begin;
} elseif ($row['year_ref'] = date("Y",strtotime($to_y)))
{
$month_no = $month_no_end;
} else
{
$month_no = 12;
}
Yii::$app->db->createCommand()
->update('my_table', ['month_no' => $month_no], ['id' => $id])
->execute();
}
I tried to put the above code in controller with the same result.
A careless mistake once I had made before. You should use == or === in the if statement to test equal condition, instead of =
public function CorrectTable($id_calc, $from_y, $to_y)
{
$connection = Yii::$app->db;
$query = "SELECT * FROM my_table where id_paid='$id_calc'";
$data = $connection->createCommand($query)->queryAll();
// calculate no. of month first and last year
$month_no_begin = (13 - date("m",strtotime($from_y)));
$month_no_end = (date("m",strtotime($to_y)));
//
foreach($data as $row)
{
$id = $row['id'];
// use `==` instead of `=`
if ($row['year_ref'] == date("Y",strtotime($from_y)))
{
$month_no = $month_no_begin;
}
// use `==` instead of `=`
elseif ($row['year_ref'] == date("Y",strtotime($to_y)))
{
$month_no = $month_no_end;
}
else
{
$month_no = 12;
}
Yii::$app->db->createCommand()
->update('my_table', ['month_no' => $month_no], ['id' => $id])
->execute();
}
}
our if ... esleif ... else sequence seems not logig
as you done the else if is never executed
so you should change the condition this way the e
foreach($data as $row)
{
$id = $row['id'];
// assigne default value
$month_no = 12;
// check for month_begin
if ($row['year_ref'] == date("Y",strtotime($from_y)))
{
$month_no = $month_no_begin;
}
//check for month_end
if ($row['year_ref'] == date("Y",strtotime($to_y)))
{
$month_no = $month_no_end;
}
Yii::$app->db->createCommand()
->update('my_table', ['month_no' => $month_no], ['id' => $id])
->execute();
}
I have this table that I use (but not only) for storing friends in a database :
user_1 | user_2 | status
where 'status' can be -1,0 or 1. Here, we will consider only cases where status are '0' (pending for user_1) or '1' (approved by user_2). I have the following query to look for pending/approved friends for a given $user :
SELECT user_1,user_2,status
FROM Friends
WHERE (user_2 = '$user' OR user_1 = '$user') AND status >= 0;
The goal here is to modify the query to also tell if a given $user2 is a common (approved) friend of $user1 and each (approved) friend of $user1.
After some researches, I figured out that the left join would do the trick, by setting another field to either NULL (if no mutual) or $user2. I would want to do it efficiently. I tried several shots, but no success around it.
Thanks by advance for your help
EDIT : For example, let's say we have the following entries :
a | b | 1
c | a | 1
c | b | 1
a | d | 1
I want to list the friends of 'a' and for each friend f of 'a', verify if 'b' is a common friend of f and 'a'. Also, f =/= b for the mutual test. The result of such a query would be :
a | b | 1 | NULL
c | a | 1 | b
a | d | 1 | NULL
Let me know if you need more clarification
As in MySQL query would be so complicated and slow, that I wouldn't use it myself, here's a solution in PHP, with only one query:
<?php
// $db = mysqli_connect(...);
function findMutualFriends($of,$mutual_with){
global $db;
$user_friends = array();
$mutual_friends = array();
$results = array();
$res = mysqli_query($db,"SELECT user_1,user_2,status FROM Friends WHERE ((user_2 = '$of' OR user_1 = '$of') OR (user_2 = '$mutual_with' OR user_1 = '$mutual_with')) AND status >= 0;";
while($row = mysqli_fetch_assoc($res)){
if($row['user_1'] == $of || $row['user_2'] == $of){
$user_friends[] = (($row['user_1'] == $of) ? $row['user_2'] : $row['user_1']);
}
if($row['user_1'] == $mutual_with || $row['user_2'] == $mutual_with){
$mutual_friends[(($row['user_1'] == $mutual_with) ? $row['user_2'] : $row['user_1'])] = 1;
}
}
foreach($user_friends as $friend){
if($mutual_firends[$friend]){
$results[] = $friend;
}
}
return $results;
}
?>
Please notice that it haven't been tested. May contain some minor syntax error, but should return an array of mutual friends.
I modified a bit the Flash Thunder's function post. Just tested with some modifications and it works ! Thanks again.
function findMutualFriends($pdo, $of,$mutual_with){
$user_friends = array();
$mutual_friends = array();
$results = array();
$query = "SELECT user_1,user_2,status FROM Friends WHERE ((user_2 = '$of' OR user_1 = '$of') OR (user_2 = '$mutual_with' OR user_1 = '$mutual_with')) AND status = 1;";
$prep = $pdo->prepare($query);
$res = $prep->execute();
$rows = $prep->fetchAll();
foreach ($rows as $row) {
if($row['user_1'] == $of || $row['user_2'] == $of) {
$user_friends[] = ($row['user_1'] == $of ? $row['user_2'] :$row['user_1']);
}
if($row['user_1'] == $mutual_with || $row['user_2'] == $mutual_with) {
$mutual_friends[($row['user_1'] == $mutual_with ? $row['user_2'] :$row['user_1'])] = true;
}
}
foreach($user_friends as $friend) {
$results[$friend] = $mutual_friends[$friend] == true ? true : false;
}
return $results;
}
Based on : Getting a modified preorder tree traversal model (nested set) into a <ul>
I have following table :
id name lft rgt level
1 company 1 22 0
75 Developer 26 31 1
76 Tester 24 27 1
77 Analyst 22 23 1
78 under developer 27 30 2
79 under tster 25 26 2
And following query/code for fetching nested records:
function getstructureInformation() {
$treeArr = array();
$tree = array();
$sql = "SELECT node.name, node.id, node.unit_id,
node.description,node.lft,node.rgt,node.level,
(COUNT(parent.name) - 1) AS depth
FROM tablename AS node
CROSS JOIN tablename AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
GROUP BY node.name
ORDER BY node.lft";
$query = $this->db->query($sql);
$data = $query->result();
foreach ($data as $datap) {
$treeArr['id'] = $datap->id;
$treeArr['unit_id'] = $datap->unit_id;
$treeArr['lft'] = $datap->lft;
$treeArr['rgt'] = $datap->rgt;
$treeArr['level'] = $datap->level;
$treeArr['name'] = $datap->name;
$treeArr['depth'] = $datap->depth;
$treeArr['description'] = $datap->description;
$tree[] = $treeArr;
}
return $tree;
}
Here the PHP code for displaying it into the view page:
$result = '';
$currDepth = -1; // -1 to get the outer <ul>
while (!empty($tree)) {
$currNode = array_shift($tree);
if ($currNode['depth'] > $currDepth) {
echo '<ul>';
}
if ($currNode['depth'] < $currDepth) {
$result .= str_repeat('</ul>', $currDepth - $currNode['depth']);
}
echo '<li>' . $currNode['name'] . '</li>';
$currDepth = $currNode['depth'];
if (empty($tree)) {
echo str_repeat('</ul>', $currDepth + 1);
}
}
But its not displaying properly like:
It displaying output as:
001 : Company Name
3 : Analyst
2 : Tester
33 : under tster
1 : Developer
44 : under developer
The desired output is like:
001 : Company Name
3 : Analyst
2 : Tester
33 : under tster
1 : Developer
44 : under developer
Is there any solution?
This should work :
function printTree ($tree) {
$last_level = -1;
foreach ($tree as $v) {
$diff = $v['level'] - $last_level;
if ($diff == 0) {
echo '<li>' .$v['name']. '</li>';
}
elseif ($diff > 0) {
for ($i = 0; $i < $diff; $i++)
echo '<ul>';
echo '<li>' .$v['name']. '</li>' ;
}
else {
for ($i = 0; $i > $diff; $i--)
echo '</ul>';
echo '<li>' .$v['name']. '</li>' ;
}
$last_level = $v['level'];
}
}
But with this function, you won't have the depth printed.
Tested and working with
$tree = array (
array (
'name' => 'Line',
'level' => 0
),
array (
'name' => 'Line',
'level' => 1
),
array (
'name' => 'Line',
'level' => 2
),
array (
'name' => 'Line',
'level' => 1
)
);
printTree ($tree);
i have a mysql table
||==========||==========||==========||
|| id || name || age ||
||==========||==========||==========||
|| 1 || joe || 10 ||
|| 2 || harry || 20 ||
|| 3 || jane || 45 ||
|| 4 || john || 56 ||
|| 5 || larry || 89 ||
|| 6 || henry || 23 ||
|| 7 || steve || 25 ||
|| 8 || eric || 56 ||
|| 9 || dave || 98 ||
|| 10 || mat || 56 ||
||==========||==========||==========||
i need the sql query that would make an associative array from this table and give me values like this
id=>age
1=>10
4=>56
i also need to make all the id's as a variable where there value would be the age like
$1 = 10
$4 = 56
or if i could add a prefix to the variables
$id_1 = 10
$id_4 = 56
thanks in advance
In PHP, mysql_fetch_assoc() takes the result of a query, and returns one row as an associative array. Call it repeatedly to get all rows.
if your using php for fetching your data you may use the function mysql_fetch_array example:
while($row = mysql_fetch_assoc($resource))
{
echo $row['name'].'<br>';
}
you may know more about mysql functions for php on this site: http://www.php.net/manual/en/book.mysql.php
$ids = '1, 4';
$sql = "select age from __TABLE__ where id in ( {$ids} )";
$link = mysql_connect('__SERVER__', '__DBUSER__', '__DB_PWD__') or die('connect error');
$db = mysql_select_db('__DBNAME__', $link) or die('db error');
$rs = mysql_query($sql, $link);
$result = array();
while($row = mysql_fetch_assoc($rs))
{
$result[] = $row;
}
extract(my_result($result));
var_dump($id_1);
var_dump($id_4);
function my_result($result, $prefix = 'id_')
{
$data = array();
foreach($result as $k => $v)
{
$data[$prefix . $v['id']] = $v['order_no'];
}
return $data;
}