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;
}
Related
When I run this query using CodeIgniter's active records:
$user_name = 'mememe';
$test = $this->db->select('filename')
->where('user', $user_name)
->order_by('number','asc')
->limit(4)
->get('mytable')
->row('filename');
print_r($test); exit;
I get this result on my browser:
5f
But when I run the same query on my database manager:
SELECT `filename` FROM `mytable` WHERE `user` = 'mememe' ORDER BY `number` ASC LIMIT 4
I get this (which is actually correct and what I want):
5f
9f
10f
11f
Why is this happening?
From CI doc
row()
This function returns a single result row. If your query has more than
one row, it returns only the first row. The result is returned as an
object.
Jusr remove call to row method
$test = $this->db->select('filename')
->where('user', $user_name)
->order_by('number','asc')
->limit(4)
->get('mytable');
row() method return only first row from your table it is used when you want to get single record you can also get data other row by passing Row number row(ROW NUMBER) example row(4)
Another Method
$query = $this->db->query("SELECT filename FROM mytable WHERE `user` = '$user_name' ORDER BY `number` ASC LIMIT 4");
foreach ($query->result() as $row)
{
echo $row->filename;
}
I want to get the maximum id of row data. In my table first column is id then firstname and etc.
this is the sql command I used to get the max(id) of row data.
<?PHP $maxid=$this->db->query("SELECT MAX(id) FROM `emplyee_personal_details`");
print_r( $maxid) ;?>
but it prints bunch of data as it is a array. But I need only the maximam id of row data for validation before data inserting and updating.
How to get the maxid. I use codeigniter framework.
Try this:
$maxid = $this->db->query('SELECT MAX(id) AS `maxid` FROM `emplyee_personal_details`')->row()->maxid;
UPDATE
This will work even if your table is empty (unlike my example above):
$maxid = 0;
$row = $this->db->query('SELECT MAX(id) AS `maxid` FROM `emplyee_personal_details`')->row();
if ($row) {
$maxid = $row->maxid;
}
The problem with using a raw query like "SELECT MAX(id) ..." is it is not abstract and may not work for every SQL engine. I think the active record way to do it is like this:
$this->db->select_max('id');
$query = $this->db->get('emplyee_personal_details');
// Produces: SELECT MAX(id) as age FROM emplyee_personal_details
See: http://ellislab.com/codeigniter/user-guide/database/active_record.html
SELECT id FROM table ORDER BY id DESC LIMIT 1
That will get you the highest id value, and when I read this, "it prints bunch of data as it is a array" I get the sense that what you really want is a part of that array. DB queries always return complex structures like arrays or objects. So if you wanted just the scalar value (the number as an integer) you might use something like this:
$maxid = (int)$maxid['id'];
or like this (if you have an object):
$maxid = (int)$maxid->id;
HTH, ~Ray
Try this,hope it helps,
return $this->db->select_max('id')
->get('your_table_name')
->row()->id;
public function getMaxCategoryId() {
$query = $this->db->query("SELECT category_id+1 AS maxid FROM " . DB_PREFIX . "category ORDER BY category_id DESC LIMIT 1");
return $query->row['maxid'];
}
error undefined index maxid
<?php`$qry = "select max(ID)+1 As ID from records";`
$result = $con->query($qry);
$row = $result->fetch_assoc();`echo "New ID To Enter = ".$row["ID"];?>
After Connection Just Write This Code It Will Work
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];
}
}
I need to fetch a particular column value of a particular row using php in mysql.
For example if I want to fetch column2 value in row2, I tried using:
$qry = mysql_query("SELECT * from $table");
$data = mysql_fetch_row($qry);
$result = $data[1];
but this always returns only the first row value.
SELECT Column2
FROM $table
ORDER BY Something
LIMIT 1,1;
Or, if you know the key of the row
SELECT Column2
FROM $table
WHERE Key = Something
-- Optional: if you want 2nd after filtering
-- ORDER BY Something
-- LIMIT 1,1;
select COLUMNNAME from TABLENAME where ROWELEMENT="SOME_VALUE";
This should be your sql query..
You will need to access the value of that element using
$result['COLUMNNAME']
Complete code should look like this.
$query="select COLUMNNAME from TABLENAME where ROWELEMENT='SOME_VALUE'";
$result=mysql_query($query);
$result=mysql_fetch_array($result);
$columnvalue=$result['COLUMNNAME'];
Its bcoz mysql_query returns the result in an associative array form.
After the above code, You can access all elements like this.
$columnname[$index];
This will return the first value,
According to your question, You will need to first get the column values in a saperate array, and then access it using your index value..
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)];