How to get all rows data in single row in codeigniter - php

I am having MYSQL table "users" with two fields
1. id
2. name
I am fetching records in Codeigniter something like,
id name
1. jhon
2. martina
3. Rob
But I want results in single row like,
"john,martina,Rob"

Try this:
$this->db->select('GROUP_CONCAT("name") as all_names', false)->from('table')->get()->row_array();

You can use MYSQL query here,
SELECT GROUP_CONCAT(users.name) AS name
FROM users
This will return something like,
userA,Userb,UserC
Here is the way for a raw query in Codeigniter,
function get_names () {
$query = " SELECT GROUP_CONCAT(users.name) AS name FROM users";
return $this->db->query($query)->row();
}

function getName(){
$this->db->select('GROUP_CONCAT(users.name) AS name');
$q =$this->db->get('users');
if($q->num_rows() > 0)
{
foreach($q->result() as $row)
{
$output =$row->name;
}
return $output;
}
}

Related

How to create auto increment series number using mysql query?

code:
<?php
$this->db->select('*');
$this->db->from('bugs');
$where = "project_name = '".$project."'";
$this->db->where($where);
$sql = $this->db->get();
$res = $sql->num_rows();
if($res === 0)
{
$i = 1;
foreach ($bug as $row)
{
echo $i;
}
}
else
{
$i = 1;
foreach ($bug as $row)
{
echo ++$i;
}
}
?>
$data = array(
'project_name'=>$this->input->post('project'),
'bug_id'=>$this->input->post('bug_id'),
);
$query = $this->db->insert('bugs',$data);
In this code I have a table name bugs where I have a column i.e. bug_id. Now, I want to insert data into my table if table row having no value it insert bug_id = 1 and after that insert 2 and then 3 and so on. But now when I click on submit button it insert bug_id = 1 and then 2 but when I click on third it insert again bug_id 2 . So, How can I fix this problem?Please help me.
Thank You
MySQL has integrated AUTO_INCREMENT. Either you log into phpMyAdmin and change the properties of your bug_id field by clicking on edit, then selecting the "A_I" field.
Or you can do it with a SQL query:
ALTER TABLE YOUR_TABLE MODIFY bug_id INTEGER NOT NULL AUTO_INCREMENT;
If #Twinfriends answer doesn't fit your needs (but that should be the correct way to do that, you shouldn't reinvent the wheel) then maybe the problem is with your:
$data = array(
'project_name'=>$this->input->post('project'),
'bug_id'=>$this->input->post('bug_id'),
);
$query = $this->db->insert('bugs',$data);
Since you are actually using $this->input->post('bug_id') as your new id, maybe you want to use something else?
Where does your $bug var come from? To be sure of not getting duplicated ids or wrong one you could add to your MySql query something like "ORDER BY bug_id DESC LIMIT 1" (so that you take 1 row as result with the highest bug_id) and then just use that result + 1 as the new id

Can I repeat fetchColumn in a function?

I'm trying to show 3 different values in 3 different column in a table. My first $results is okay, it's shows what it has to shows in my database but the second and the third doesn't show up. So tell me guys, how can I fix that problem? How can I show my 3e column and the other one?
public function Show($name) {
$st = $this->db->prepare("SELECT * FROM form WHERE username='$name'");
$st->execute();
$results = $st->fetchColumn(2);
print("Votre adresse: $results <br>");
$results = $st->fetchColumn(3);
print("Votre met: $results <br>");
$results = $st->fetchColumn(4);
print("Votre age: $results <br>");
}
we cannot use fetchColumn and fetchAll multiple times..so that's why we store it in a variable and then fetch data with the help of foreach loop statement for echo all data..but try this one code may be it will be helpful for you
function fetch_det()
{
$query=self::$db->prepare("select * from clas_products");
$query->execute();
$dta=$query->fetchAll(PDO::FETCH_COLUMN,0); //you can enter column num 2,3,4 instead of 0
print_r($dta);
}

add two different query in codeigniter

I want to add two query but its not working. Here's my
Model page:
public function updateTable(){
$first= $this->db->query("select column1 from table where table_id='data1' AND
field_id=6"); // Data type is numeric. When I query this, result is 0.0
$second= $this->db->query("select column1 from table where table_id='data2' AND
field_id=6"); // Data type is numeric also. When I query this, result is 0.0 also
$total=$first+$second;
}
When I try to run this I got an error message
Message: Object of class CI_DB_postgre_result could not be converted to int
How can I make this happen or is this possible?
EDIT: NEW INFO
I want to use this $total to an if statement .
if ($total==0){
//code here
}
What should I do?
let's see the first example in CI userguide: http://ellislab.com/codeigniter/user-guide/database/results.html
$query = $this->db->query("YOUR QUERY");
foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->body;
}
we learn two things:
$this->db->query("YOUR QUERY") does not return a result, $query->result() does.
the result is an array of object. object names is the column name.
if you're sure every query only return one result. you can change your code like this:
$first= $this->db->query("select column1 from table where table_id='data1' AND
field_id=6")->result()[0]->column1;
$second= $this->db->query("select column1 from table where table_id='data2' AND
field_id=6")->result()[0]->column1;
===== answer been revised below =====
The analysis is correct but code above throws error, because php regard result()[0] as a whole.
you can either separate them
$row = $this->db->query("select column1 from table where table_id='data1' AND
field_id=6")->result();
$first = $row[0]->column1;
or use current function
$first= current($this->db->query("select column1 from table where table_id='data1' AND
field_id=6")->result())->column1;
try this,
$total=$first->column1 + $second->column1;
If you just want the total result num, it will be
$first->num_rows() + $second->num_rows()
If to get all the result, then
array_merge ( $first->result (), $second->result );
http://ellislab.com/codeigniter/user-guide/database/results.html
This process incorrect, the query return MYSql Result Object that wont add.
Do you want to sum (column1) values,
you can add column value in sql query, try this way
public function updateTable(){
$first= $this->db->query("select column1 from table where table_id='data1' AND
field_id=6"); // Data type is numeric. When I query this, result is 0.0
$second= $this->db->query("select column1 from table where table_id='data2' AND
field_id=6"); // Data type is numeric also. When I query this, result is 0.0 also
$total=$first->row()->column1 + $second->row()->column1;
}
OR
public function updateTable(){
$total_result= $this->db->query("select SUM(column1) as sum_column1 from table where table_id IN('data1', 'data2') AND
field_id=6"); // Data type is numeric. When I query this, result is 0.0
echo $total_result->row()->sum_column1;
}
Try this code i think this will work
public function updateTable(){
$first= $this->db->query("select column1 from table where table_id='data1' AND
field_id=6")->row(); // Data type is numeric. When I query this, result is 0.0
$second= $this->db->query("select column1 from table where table_id='data2' AND
field_id=6")->row(); // Data type is numeric also. When I query this, result is 0.0 also
$total=$first+$second;
}

How to get all the rows when executing query in codeigniter?

I have question in codeigniter.
Get All the rows when Executing the Query
In CI I want to get all the rows when I am executing the query like
Select * from tablename
But when I am using the
return $query->row();
I am getting only one row.How can I get all the rows.I dont get any idea in this article
instead of this
$query->row();
use this
foreach ($query->result() as $row)
{
echo $row->field_name;
//use the database table fields name in the place of field_name property
}

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