php pdo displaying rowCount in mvc - php

I am working with a new mvc framework (view here) and I have ran into a slight problem.
I have a table named 'favourite' which looks like below;
---------------------------
id user_id book_id
1 2 1777
2 3 1887
3 2 1023
4 7 8776
5 2 8811
---------------------------
I am trying to display the number of favourites for a specific on their profile page (Hello. You have x favourites). I feel I am misunderstanding something regarding the mvc structure or have a syntax issue somewhere?
On my showprofile I don't have any errors, it's simply blank where the count should be. When I run the query in phpmyadmin I get a result of 3 which is correct.
I have read that rowCount() can be unreliable so I have also tried fetchColumn() amongst other variations. Do I need to use a second query?
New to php/sql/mvc so any advice is appreciated.
My code is as follows;
login_model.php (model)
class LoginModel
{
public function favouriteTotal()
{
$query = $this->db->prepare("SELECT COUNT(book_id) FROM favourite WHERE user_id = 2");
$query->execute();
$count = $query->rowCount()
}
}
showprofile.php (view)
<div>
Hello. Your have this number of favourites:
<?php echo $this->count ?>
</div>
login.php (controller)
class Login extends Controller
{
function showProfile()
{
$login_model = $this->loadModel('Login');
$this->view->count = $login_model->favouriteTotal();
$this->view->render('login/showprofile');
}
}

Your issue is that you're executing a COUNT query, when you should be using a SELECT query if you want to use the rowCount function.
This query would let your rowCount function work:
SELECT `book_id` FROM favourite WHERE user_id = 2
Alternatively, you could continue to use the COUNT statement, but you would then need to get the first result from your query instead of a row count.

Related

Running two queries with Datamapper in Codeigniter

I want do perform two queries, one to get the count of all results and one to get the actual results 9 by 9. My problem is when I try to get the count of the results: The second query gets all the 9 rows from database without the WHERE clause.
$courses = $this->load->model("course")->where("deleted",0);
$courses->where("country",strtolower($country));
$courses->count(); // returns 15
$courses->offset(($per_page)*9)->limit(9);
$courses->get(); // returns 9 rows from all database (like select * from courses limit 9) without where country=france
My problem is I want to count all the results but I want to get just 9 results for pagination purposes
Help needed for newbie codeigniter user
class Course extends DataMapper {
var $table = 'course';
var $error_prefix = '<li>';
var $error_suffix = '</li>';
function __construct($id = NULL) {
parent::__construct($id);
}
}
As far as I know, you must perform two queries agaisnt the database:
One for counting.
One for retrieving the results you want.
Your problem is you think the active records is keeping your results. When you perform a count, Datamapper will return you the results of the query and will be ready for a new query, so, it's not keeping the where clause.
Try doing it in two steps. For counting:
$courses = $this->load->model("course")->where("deleted",0);
$courses->where("country",strtolower($country));
$counting = $courses->count(); // returns 15
For retrieving results:
$courses = $this->load->model("course")->where("deleted",0);
$courses->where("country",strtolower($country));
$courses->offset(($per_page)*9)->limit(9);
$results = $courses->get(); // returns 9 rows from all database (like select * from courses limit 9) without where country=france

Get row values as column names using Codeigniter and mysql

im using codeigniter and mysql as db. i know might can be solved with mysql query, but if anyone can solve with codeigniter query it will be awesome, otherwise normal PHP mysql query can work also.
I have Table with 3 columns, Well it have many feilds but i have shown here 4 enteries, i didnt wanted to make a table with many columns but only 1 row of data. so instead i went for this style of table as someone suggested me on this website.
Problem is i never worked with this kind of table.
SettingsID SettingsKey SettingsValue
----------------------------------------------------------------------
1 | facebookLink | facebook.com
2 | twitterLink | twitter.com
3 | youtubeLink | youtube.com
4 | googlePlusLink | googleplus.com
Now i want to run a query that should return me rows in to columns. i searched over net and found some solutions but i am not good with this new queries.
I suppose this guy had same kind of problem like i have but in his case he has same value repeated in column, where my SettingsKey has all the values unique.
Here is the link to similar kind of question :
mysql select dynamic row values as column names, another column as value
i cant understand his query and that query i am not sure if is any use of me.
Please can anyone help me build a query to return row values of SettingsKey as columns.
This should work:
<?php
$db = new PDO('mysql:host=localhost;dbname=DBNAME;charset=utf8', USERNAME, PASSWORD);
$stmt = $db->query("SELECT SettingsKey, SettingsValue FROM Settings");
$links = array();
while($row = $stmt->fetch()) {
$links[$row['SettingsKey']] = $row['SettingsValue'];
}
$db = null;
This code queries this table and for each row the SettingsKey and the SettingsValue will be shown.
Now you can get the facebookLink like this:
echo $links['facebookLink'];
Hope this helps.
$sql = "
SELECT SettingsKey, SettingsValue
FROM Settings
";
$q = $this->db->query($sql);
return $q->result_array();
Go to your controller
$data['settings'] = $this->model_selection->your_function();
$this->load->view('example', $data);
And lasty on your view
<?php if(!empty($settings)): ?>
<?php foreach($settings as $k => $v): ?>
//print your staff in here mix with html and go crazy
<?php endforeach; ?>
<?php endif ?>

Codeigniter-returns only one row from my model class

I have written a model code where i am joining two tables, and returning my results.
I have 26 results in my table ,but the code below i mention is returning only one rows! What could be the reason?Why its returning only one rows?
Please help me regarding this problem
Update
Table structure
question
-----------
question_id PK Auto_Incr
question varchar...
votes int
answer
------------
answer_id PK Auto_icre
question_id FK refrences question
content longtext
From the below table structure my model code is showing only 2 question count, skipping the last question, After little research i found the reason why it is not counting my third question, it is because it does not have any answer in my answer table.
I want, if no answer then it should show count=0 for the particular question, How can to solve this issue?
Table Data structure data:
question
-----------
question_id question votes
1 what's name? 0
2 where you? 3
3 blah blah 9
answer
----------
answer_id question_id content
4 2 India
5 2 Nepal
6 2 Pakistan
7 1 Mr Osama Binladan
Model
public function fetch_allquestions($limit, $start)
{
$this->load->database();
$this->db->limit($limit, $start);
$this->db->from('question');
$select =array(
'question.*',
'userdetails.*',
'COUNT(answer.answer_id) AS `Answers`'
);
$this->db->select($select);
$this->db->join('answer','answer.question_id = question.question_id');
$this->db->join('userdetails','userdetails.user_id = question.user_id');
$query = $this->db->get();
print_r("Number of rows=".$query->num_rows());//showing only One, out of 26 rows
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$data[] = $row;
}
return $data;
}else{
return false;
}
}
You have a COUNT() sql aggregation in the select. Since you don't have any GROUP BY, the database will use the whole result set as one implicit group thus reducing your resultset to one row when counting it all up. This is how sql should work.
You can check out the generated sql query with print $this->db->last_query() right after the $this->db->get(); line, and run it in your sql console to see what's happening.
You probably wanted to add a $this->db->group_by('question.question_id'); or something similar.

How to create a proper recursive function for mlm project

I've got various solution from SO to create my first MLM project, but now I got stuck in total down-line count (via recursive function), as I've no prior Idea on this, please anyone help me.
My Database Table structure is as below (table name member):
`member_id | member_name | node_left | node_right
where member's relation is as:
member_id (Id 101)
/\
/ \
node_left(Id 102) node_right(Id 103)
/\ /\
/ \ blank / \blank
(again) blank node_right (104)
...... and so on. The above is just an example
`
Now I need to count total downline of any member. eg: suppose of above example, I want to know total downline of member_id 101
How to create the recursive function to do this which ends in finite loop ?
please give me any Idea..
I'm not sure if you've tried to implement the nested set model here, but the implementation doesn't look right..
With a nested set, the left/right values representing your tree structure would look like this:
member 101 (root): left=1, right=8
member 102: left=2, right=5
member 103: left=3, right=4
member 104: left=6, right=7
Then, counting the childs of member #101 would be as simple as:
SELECT COUNT(*) FROM member WHERE node_left > 1 AND node_right < 8
you can use/create your own customize function from the below code, Just check it out and try to implement for your case.
function Recursive_getsubcategory($parent_id,$cat_group,$intLevel)
{
global $intLevel;
$sql = "select *,".$intLevel." as level from tbl_name where parent_id = '".$parent_id."' ";
$result = mysql_query($sql);
$cat_name = $result->fetch_array_multiple();
if(count($cat_name) > 0)
{
for($k=0;$k<count($cat_name);$k++)
{
$cat_group[] = array('id'=>$cat_name[$k]['sub_id'],
'parent_id'=>$cat_name[$k]['parent_id'],
'level' => $cat_name[$k]['level']
);
$parent_id[] = $cat_name[$k]['parent_id'];
//Function For Recursive Get Sub Category...
Recursive_getsubcategory($cat_name[$k]['ebay_sub_id'],$cat_group,$intLevel++);
}
}
// count of total downline nodes
return count($cat_group);
}
This code may helpful for your task.

Random record from mysql database with CodeIgniter

I researched over the internet, but could not find anything...
I have a mysql db, and records at a table, and I need to get random record from this table at every page load. how can I do that? Is there any func for that?
Appreciate! thanks
SORTED:
link: http://www.derekallard.com/blog/post/ordering-database-results-by-random-in-codeigniter/
$this->db->select('name');
$query = $this->db->get('table');
$shuffled_query = $query->result_array();
shuffle ($shuffled_query);
foreach ($shuffled_query as $row) {
echo $row['name'] . '<br />';
}
Codeigniter provides the ability to order your results by 'RANDOM' when you run a query. For instance
function get_random_page()
{
$this->db->order_by('id', 'RANDOM');
or
$this->db->order_by('rand()');
$this->db->limit(1);
$query = $this->db->get('pages');
return $query->result_array();
}
I've used this before and found it to work fine.
I don't know about codeigniter, but getting a random dataset is
SELECT * FROM table ORDER BY RAND() LIMIT 1
The relevant part is "ORDER BY RAND()", obviously.
Do you know how many records there are in the table? You could do something like this:
$count=mysql_exec('select count(*)-1 from some_table');
$count=rand(1,$count);
then:
select * from
some_Table
limit $count,1
This code snippet worked well for me.
$this->db->select('name');
$this->db->order_by('rand()');
$this->db->limit(1);
$query = $this->db->get('<table>'); //<table> is the db table name
return $query->result_array();
Getting random record from large table is very expensive.
Don't use ORDER BY RAND().
This is a bad idea, but if you have a small table no problem.
In a huge databases this type of queries very slow.
I use codeigniter with datamapper. This is the code which I use to get a record randomly from table Advertiser:
$ad = new Advertiser();
$ad->limit(3);
$ad->order_by('id', 'RANDOM');
$ad->get();
SELECT product_id, title, description
FROM products
WHERE active = 1
AND stock > 0
ORDER BY RAND()
LIMIT 4
The ORDER BY RAND() clause returns random records! You can limit records also using LIMIT.
Lets think we have table where we deleted some rows. There is maybe ID not continues correctly. For sample id: 1,5,24,28,29,30,31,32,33 (9 rows)
mysql_num_rows returns 9
Another methods will return not existing rows:
$count=9; //because mysql_num_rows()==9
$count=rand(1,$count); // returns 4 for sample, but we havn't row with id=4
But with my method you always get existing rows. You can separate code and use first 2 code anywhere on site.
// Inside of Controller Class
function _getReal($id,$name_of_table)
{
$Q=$this->db->where('id',$id)->get($name_of_table);
if($Q->num_rows()>0){return $Q;}else{return FALSE;}
}
function _getLastRecord($name_of_table)
{
$Q=$this->db->select("id")->order_by('id DESC')->limit("1")->get($name_of_table)->row_array();
return $Q['id'];
}
function getrandom()
{
$name_of_table="news";
$id=rand(1,$this->_getLastRecord($name_of_table));
if($this->_getReal($id,$name_of_table)!==FALSE)
{
echo $id;
// Here goes your code
}
else
{
$this->getrandom();
}
// END
Getting random record from large table is very expensive. But bellow this code is very effective ..
$count=mysql_num_rows(mysql_query("select * from table_name WHERE SOME_OF_YOUR_CONDITION"));
$nums=rand(1,$count);
mysql_query(" select * from table_name WHERE SOME_OF_YOUR_CONDITION LIMIT $count,1");
This will be helpful ...
I think this is not best way. For sample, you've deleted record which is now==$count. You must iterate this for mysql_num_rows()
This function retrieve all rows in table in random order
public function get_questions(){
$this->db->select('*');
$this->db->order_by('rand()');
$this->db->from('multiple_choices');
$query = $this->db->get();
return $query->result_array();
}
Random row without ORDER BY RAND() query:
$all_rows = $this->db->get('table')->result_array();
$random_row = $all_rows[rand(0,count($all_rows)-1)];

Categories