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

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
}

Related

Codeigniter JOIN - not a unique table/alias issue

I have bookings tables from several countries (for example: book_uk) these tables contain information about our customers in different countries such as name, address, etc etc. Then in my results table I have the results of all tests this customer has had, the information is 'linked' by a PIN number, eg 336699, this number is referenced in both the book_uk table and the results table.
What I want to do is select all data from the book_uk table and then link each row to the results table (where the PIN matches) but I keep getting not a unique table/alias, here is my model code:
$database->select($new_country_columns)
->from($country_table);
$database->select($p_results_cols)
->from($table);
$database->join('p_results', $join, 'inner');
$database is defined earlier on in the model
Produces this error:
Error Number: 1066
Not unique table/alias: 'p_results'
SELECT `book_uk`.`pin`, `book_uk`.`clinic`, `book_uk`.`dob`, `book_uk`.`gender`, `book_uk`.`country`, `book_uk`.`order_date`, `p_results`.`pin`, `p_results`.`code`, `p_results`.`name`, `p_results`.`result` FROM (`book_uk`, `p_results`) INNER JOIN `p_results` ON 'book_uk.pin = p_results.pin'
Filename: C:/xampp/htdocs/projects/b2k-stat/system/database/DB_driver.php
Line Number: 691
what I really need to do is select data from book_uk and then run a foreach loop on the results table and add any data with matching PIN to the results array, I have no idea how to do this, I tried to loop through it with a foreach loop but it kept coming up blank, i've also tried:
$database->select($new_country_columns)
->from($country_table)
->join('p_results', $join, 'inner');
But this also gives me zero results, any help? Thanks in advance
Remove
'p_results'
from your
FROM
clause since your joining it right after that.
Not sure if this is the best way to do things, but I solved my issue by generating 2 queries and running an IF statement inside a foreach loop on both queries like so:
$database->select($new_country_columns)
->from($country_table);
$query1 = $database->get()->result_array();
$p_results->select($p_results_cols)
->from($table);
$query2 = $p_results->get()->result_array();
foreach($query1 as $row){
foreach($query2 as $rows) {
if($row['pin'] === $rows['pin']) {
$new_row = array_merge($row, $rows);
$query[] = $new_row;
}
}
}
return $query;
This code gave me an array of the combined data that was needed to display in my view

MySQL return rows where column contains categories defined by array (and add weight to the results)

In my app, the user can type in an indefinite amount of categories to search by. Once the user hits submit, I am using AJAX to call my PHP script to query my DB and return the results that match what the user defined for the categories.
My category column is separated as so for each row: "blue,red,yellow,green" etc.
I have two questions:
How can I pass an array to MySQL (like so: [blue,yellow,green]) and then search for each term in the categories column? If at-least one category is found, it should return that row.
Can MySQL add weight to a row that has more of the categories that the user typed in, therefor putting it further to the top of the returned results? If MySQL cannot do this, what would be the best way to do this with PHP?
Thanks for taking the time and looking at my issue.
For the part 1 you can use the function below:
<?php
function createquery($dataarray){
$query="select * from table where ";
$loop=1;
foreach($dataarray as $data)
{
$query.="col='$data'";
if(count($dataarray)<$loop-1){
$query.=' or ';
}
$loop++;
}
return $query;
}
?>
This will return the long query.
use this some like this:
mysql_query("select * from table where category in (".implode($yourarray,',').")");
1)
Arrays are not passed to a MySQL database. What's past is a query which is a string that tells the database what action you want to preform. An example would be: SELECT * FROM myTable WHERE id = 1.
Since you are trying to use the values inside your array to search in the database, you could preform a foreach loop to create a valid SQL command with all those columns in PHP, and then send that command / query to the database. For example:
$array = array('blue', 'red', 'yellow', 'green');
$sql = "SELECT ";
foreach ($array as $value)
{
$sql .= $value.", ";
}
$sql .= " FROM myTable WHERE id = 1";
IMPORTANT! It is highly recommended to used prepared statements and binding your parameters in order not to get hacked with sql injection!
2)
You are able to order the results you obtained in whichever way you like. An example of ordering your results would be as follows:
SELECT * FROM myTable WHERE SALARY > 2000 ORDER BY column1, column2 DESC

mysql query to laravel query

I've been trying for several hours to make this little query work, but I cant seem to make it work.
Basically I'm trying to do a foreach from the results of the query.
This is the query I want in raw MYSQL:
SELECT id FROM albums WHERE id IN (SELECT album_id FROM user_albums WHERE user_id =".Auth::user()->id
And I tried the following:
$myAlbums = Album::whereIn('id', DB::table('user_albums')->where('user_id', Auth::user()->id)->select('album_id')->get());
But it seems like the whereIn doesnt take the array from the select correctly and it gives nothing back.
The query builder doesn't support subquery.
Break it up into two queries. Something like this. (untested)
$albums = DB::table('user_albums')->where('user_id', Auth::user()->id)->get();
// collect the album ids
$albumIds = array();
foreach ($albums as $a) {
albumIds[] = $a->album_id;
}
$myAlbums = Album::whereIn('id', $albumIds)->get();

How to query all fields in a row

I know this is very simple, but I haven't used PHP/MySQL in a while and I have been reading other threads/php website and can't seem to get it.
How can I query a single row from a MySQL Table and print out all of the fields that have data in them? I need to exclude the NULL fields, and only add those that have data to an html list.
To clarify, I would like to display the field data without specifying the field names, just for the reason that I have a lot of fields and will not know which ones will be NULL or not.
What you've outlined requires 4 basic steps:
Connect to the database.
Query for a specific row.
Remove the null values from the result.
Create the html.
Step 1 is quite environment specific, so that we can safely skip here.
Step 2 - SQL
SELECT * from <tablename> WHERE <condition isolating single row>
Step 3 - PHP (assuming that $query represents the executed db query)
//convert the result to an array
$result_array = mysql_fetch_array($query);
//remove null values from the result array
$result_array = array_filter($result_array, 'strlen');
Step 4 - PHP
foreach ($result_array as $key => $value)
{
echo $value \n;
}
Just SELECT * FROM table_name WHERE.... will do the trick.
To grab data from specific fields, it would be SELECT field_1,field_2,field_3....
you have to make a string which represent mysql query. Then there is function in php named mysql_query(). Call this function with above string as parameter. It will return you all results. Here are some examples
You need to do it like this...
First connect to your sql... Reference
Now make a query and assign it to a variable...
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename");
If you want to retrieve a single row use LIMIT 1
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename LIMIT 1");
If you want to fetch all the columns just use * instead of column names and if you want to leave some rows where specific column data is blank you can do it like this
$query = mysqli_query($connect, "SELECT * FROM tablename WHERE column_name4 !=''");
Now fetch the array out of it and loop through the array like this..
while($show_rows = mysqli_fetch_array($query)) {
echo $show_rows['column_name1'];
echo $show_rows['column_name2'];
}
If you don't want to include the column names in the while loop, you could do this:
while($show_rows = mysqli_fetch_array($query)) {
foreach( $show_rows as $key => $val )
{
echo $show_rows[$key];
}
}

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