not fetching data from database - mysql

Here i have a list of same category names which comes under different parent category.when i fetch the data according to the id am getting result because id is different for all but when i fetch by category name am getting only the first results even though i have two same category names under different parent category..here is my category table
id category_name parent_id
8 men 0
9 kids 0
10 T-shirts 8
11 Shirts 8
12 Jeans 8
13 Pants 8
14 Shorts 8
15 Tees 9
16 Shirts 9
17 Jeans 9
18 Pants 9
Here am having shirts as the category name under different parent_id.when i select the id of 16-shirts am getting the value of of id 11-shirts because of the same category name.
Here is the controller am using
public function men_clothing_image($category=null)
{
$category_id =$this->roxmodel->get_category_id($category);
$data['active_mn']='men_clothing';
$data['men']=$this->roxmodel->get_category_by_parent($p_id=8);
$data['kids']=$this->roxmodel->get_category_by_parent($p_id=9);
$config['base_url'] = base_url().'men-'.$category;
$config['per_page'] = 2;
$config['uri_rsegment'] = 4;
$config['use_page_numbers'] = TRUE;
$config['total_rows'] = $this->roxmodel->count_category_images($category_id);
$data['galllery']=$this->roxmodel->get_gallery_men_images($category_id,$config['per_page'],$this->uri->rsegment(4));
$this->load->library('pagination',$config);
$data['page_links'] = $this->pagination->create_links();
$this->load->view('men_clothing_image',$data);
}
Here is the model am passing
public function get_category_id($category_name)
{
$this->db->select('category.id');
$this->db->where('category.category_name',$category_name);
$result = $this->db->get('category')->row();
if($result)
{
return $result->id;
}
}
i had done self join for connecting the id and category name but the output was null
public function get_category_id($category_name)
{
$this->db->select('c.id');
$this->db->join('category c1','c.id=c1.category_name');
$this->db->where('c1.category_name',$category_name);
$result = $this->db->get('category c')->row();
if($result)
{
return $result->id;
}
}
count image function as follows..
public function count_category_images($p_id)
{
$this->db->select('gallery.*','category.category_name');
$this->db->join('category', 'category.id = gallery.category_id');
$this->db->where('category.id',$p_id);
$this->db->order_by('gallery.id','desc');
return $this->db->count_all_results('gallery');
}

You have to use result() or result_array(). Because there are several rows in result.
row() - This function returns a single result row.
result() - This function returns the query result as an array of objects, or an empty array on failure.
So, try
public function get_category_id($category_name)
{
$this->db->select('category.id');
$this->db->join('category c1','c.id=c1.category_name');
$this->db->where('category.category_name',$category_name);
$result = $this->db->get('category')->result();
return $result;
}
Also you can use
if ($query->num_rows() > 0)
to check if there are rows.
If you use, search, and use part of category name, use LIKE interms of WHERE.

try to use like query
If you want to control where the wildcard (%) is placed, you can use an optional third argument. Your options are 'before', 'after' and 'both'
and try group by
public function get_category_id($category_name)
{
$this->db->select('category.id');
$this->db->like('category.category_name',$category_name,'both');
$this->db->group_by(array("category.id", "category.category_name","category.parent_id"));
$result = $this->db->get('category')->result_array();
if($result)
{
print_r($result);
exit;
// return $result;
}
}

Related

Mysql PDO (Getting total from all colums) [duplicate]

I'm new to php and I've searched for the past hour and read all the documentation I could find and nothing is helping. I have a table that has a bunch of rows of data. I'm trying to pick one column from the whole table and add them all together. Here is what I got. All this tells me is how many rows there are that match my query, not the total sum of column I want. Any help is appreciated.
$res1 = $db->prepare('SELECT sum(distance) FROM trip_logs WHERE user_id = '. $user_id .' AND status = "2"');
$res1->execute();
$sum_miles = 0;
while($row1 = $res1->fetch(PDO::FETCH_ASSOC)) {
$sum_miles += $row1['distance'];
}
echo $sum_miles;
You're only returning one row in this instance. Modify your summed column to have an alias:
SELECT SUM(distance) AS totDistance FROM trip_logs ....
Now you can can fetch the row -
$row = $res1->fetch(PDO::FETCH_ASSOC);
echo $row['totDistance'];
No need to loop.
You can use SUM() without explicitely grouping your rows because if you use a group function in a statement containing no GROUP BY clause, it is equivalent to grouping on all rows.
If however you want to use the SUM() function for something slightly more complicated you have to group your rows so that the sum can operate on what you want.
If you want to get multiple sums in a single statement, for example to get the distance for all users at once, you need to group the rows explicitely:
$res1 = $db->prepare("
SELECT
SUM(distance) AS distance,
user_id
FROM trip_logs WHERE status = '2'
GROUP BY user_id
");
$res1->execute();
while ($row = $res1->fetch(PDO::FETCH_ASSOC))
{
echo "user $row[user_id] has runned $row[distance] km.\n";
}
This will return the sum of distances by user, not for all users at once.
Try this if you are using a Class :
class Sample_class{
private $db;
public function __construct($database) {
$this->db = $database;
}
public function GetDistant($user_id,$status) {
$query = $this->db->prepare("SELECT sum(distance) FROM trip_logs WHERE user_id =? AND status =?");
$query->bindValue(1, $user_id);
$query->bindValue(2, $status);
try{ $query->execute();
$rows = $query->fetch();
return $rows[0];
} catch (PDOException $e){die($e->getMessage());}
}
}
$dist = new Sample_class($db);
$user_id = 10;
$status = 2;
echo $dist->GetDistant($user_id,$status);

order and limit on a select query zend framework 2

Earlier this day a asked a question about an update query. But now i want to select some things ( and it is working ) but I also want to order them and put a limit on it.
This is the code to select all the food :
public function getFood($id)
{
$id = (int)$id;
$rowset = $this->tableGateway->select(array('kindOfFood_id' => $id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
But how can i do this :
Select * from KindOfFood ==> order by kindOfFood_votes DESC ?
I saw on the documentation you can do something like this, but it doesn't work with me?
$rowset = $artistTable->select(function (Select $select) {
$select->where->like('name', 'Brit%');
$select->order('name ASC')->limit(2);
});
Are you looking to return only single row or multiple rows.
Try this for multiple rows -
use Zend\Db\Sql\Select; //at the top of the page among other use statements.
public function getFood($id)
{
$id = (int) $id;
$select = new Select(TABLE_NAME); //CHANGE TABLE_NAME as per needs
$select->where('kindOfFood_id = ' . $id);
$select->order('kindOfFood_votes DESC');
$resultSet = $this->tableGateway->selectWith($select); //Will get array of rows.
//$row = $rowset->current(); THIS IS FOR RETURNING ONLY SINGLE ROW NOT ALL ROWS
if (!$resultSet) {
throw new \Exception("Could not find rows with food id - $id");
}
return $resultSet;
}
Can access the returned resultSet via loop. Eg: foreach
foreach($resultSet as $row) {
echo $row->kindOfFood_id; //or something
}
Note:
If you need only
Select * from KindOfFood order by kindOfFood_votes DESC
then remove the $select->where('kindOfFood_id = ' . $id); line from above.

Yii Call beforeSave() in other model's to be Save

I have created two tables as, forum_post and gallery.
forum_post table:
id user_id ststus photo_id
1 1 hi...! NULL
2 1 hello! NULL
3 1 NULL 1
4 1 NULL 2
user_gallery table:
id user_id image video
1 1 1.jpg NULL
2 1 new.gif NULL
When, user upload the image file in the user_gallery table, i want to create one row in the forum_post table and store the gallery id into the forum_post-> image field. as well as the user id also stored in the forum_post table.
My model code in the ForumPost is:
public static function addForumImage($id, $user_id) {
$forumImage = ForumPost::model()->find('LOWER(photo_id) = ?', array( strtolower($image)));
if (!$forumImage) {
$forumImage = new ForumPost;
$forumImage->photo_id = $image;
$forumImage->save(false);
}
UserGallery beforeSave function is:
protected function beforeSave() {
if (parent::beforeSave()) {
ForumPost::addForumImage($this->id, $this->user_id);
// var_dump($forumPost->photo_id);
return true;
}
return false;
}
My table relationship is, user_gallery->image refers the forum_post->photo_id.
Now, the image is stored in the user_gallery folder and i dint get the id in the ForumPost model...
Please any one help me.. :(
try this
protected function beforeSave() {
if (parent::beforeSave()) {
ForumPost::addForumImage($this->id, $this->user_id, $this->forum_image);
// var_dump($forumPost->photo_id);
return true;
}
return false;
}
Model
public static function addForumImage($id, $user_id,$image) {
$forumImage = ForumPost::model()->find('photo_id = :image', array( ':image'=>strtolower($image)));
if (empty($forumImage)) {
$forumImage = new ForumPost;
$forumImage->user_id=$user_id;
$forumImage->content= NULL
$forumImage->photo_id = $image;
$forumImage->save(false);
}
}

MySQL - select missing dates from table?

Suppose you have the following table values:
date | value
2012-01-01 | 8
2012-01-02 | 3
2012-01-03 | 17
2012-01-09 | 100
2012-01-12 | 2
Now suppose you want to select all the dates between 2012-01-02 and 2012-01-12 and show their values if present. If you simply query the table for the appropriate date range, the dates that don't have values are going to be absent, for obvious reasons. Is there a way to fill in those dates in the query?
The obvious solution is to create a table dates that just stores a list of all dates that may come up, and then to select from the dates table and join values to it, but I'd like to have a solution that doesn't rely on creating a single-column table if I can.
Of note: there are existing questions on SO on this topic, but they are all from 2010 (at least the ones I found when searching were), and MySQL features have grown in that time; there may be a dynamic solution now. If that's not the case, and the dates table is still the best solution, then this question should be closed as a duplicate.
The lack of answers from others suggests to me that at the current time, it is not possible to traverse a range of dates in MySQL without a table that holds those dates. I have, however, written some code in PHP that I'm using to fill in the missing dates after the fact:
function formatResults($inbound, $from, $to) {
$results = array();
$count = 0;
// In order not to lose any results, we have to change how the results are referenced
$indexes = array();
$stats = array();
foreach ($inbound as $stat) {
// ['listindex'] is the date, renamed in the query
$stats[$stat['listindex']] = $stat;
}
// In a function in case you want to pop it out
function dateArray($from, $to) {
$begin = new DateTime($from);
$end = new DateTime($to);
$interval = DateInterval::createFromDateString('1 day');
$days = new DatePeriod($begin, $interval, $end);
$baseArray = array();
foreach ($days as $day) {
$dateKey = $day->format("Y-m-d");
$baseArray[] = $dateKey;
}
$baseArray[] = $to;
return $baseArray;
}
$indexes = dateArray($from, $to);
// Now all the rows we need to return are uniquely identified in $indexes
// So we traverse $indexes to create our results array, rather than relying on $inbound
foreach($indexes as $index) if ($index != '') {
$data = array();
// Make sure we do not run into any 'missing index' problems
if (!isset($stats[$index]))
$stats[$index] = array(
'listindex' => $index,
// ... populate full list of empty fields
);
foreach ($stats[$index] as $key => $value) {
$data[] = $value;
}
$results[$count] = $data;
$count++;
}
return $results;
}

Classic structure - self connected DB table, list

I have the following:
ID NAME PAREN_ID
1 a null
2 b null
3 c 2
4 d 3
I want to list the ID 4 item, and its all parent, so I would like to get:
4 d 3
3 c 2
2 b null
I tried something:
SELECT * FROM categories c1
JOIN categories c2 ON c2.ID = c1.PARENT_ID;
but thats not the good result, even if I try to filter to ID 4, it returns nothing.
Its MySQL!
I'm not really sure how you can do it with MySQL. I think your best bet would be fetching everything recursively.
function getCategories( $id ) {
$ret = array();
$cat = mysql_query( 'SELECT * FROM categories' );
$curid = $id;
do {
$ret[] = $cat[ $curid ];
$curid = $cat[ $curid ][ 'PARENT_ID' ];
} while ( $curid );
return $ret;
}
You should alter this so that it uses the PDO.
Only problem would be the query returning much data.