Codeigniter select single row from talbe - php

Hi I have a table named news in my database and, using querybuilder, I want to obtain only the news with a specific id. I wrote this code but in the view I obtain no result.
$this->db->from("news");
$q=$this->db->get_where('news', array('id' => $idNotizia));
$data['notizie'] =$q->result_array();
If i print the numrow() method of the query I can see that there is a row but if I run this for there is now text
foreach($notizie as $notizia)
{
echo $notizia["titoloit"];
}

Oh this question has lasted so long.
From the comment I can see the error is actually
Error Number: 1066 Not unique table/alias: 'news' SELECT * FROM news, news WHERE id = '1' Filename: controllers/News.php
The error was from the database. Look at the generated query SELECT * FROM news, news: there are two "news", which makes the database confused. Try remove the first line.
// $this->db->from("news"); No you dont need this with get_where
$q=$this->db->get_where('news', array('id' => $idNotizia));
$data['notize'] =$q->result_array();
$notizie = $q->result_array();
if($q->num_rows()>0){
foreach($notizie as $notizia)
{
echo $notizie["titoloit"];
}
}

$this->db->from("news");
$q=$this->db->get_where('news', array('id' => $idNotizia));
$data['notize'] =$q->result_array();
$notizie = $q->result_array();
if($q->num_rows()>0){
foreach($notizie as $notizia)
{
echo $notizie["titoloit"];
}
}
this should work. In your pasted code the variable inside foreach is $notizia, which I guess you mean $notizie right?

Model
$this->db->from("news");
$q=$this->db->get_where('news', array('id' => $idNotizia));
$data['notize'] =$q->result_array();
$this->load->view('your_viewFIleName' , $data);
you should pass your data to the view controller

Related

Returning Data from database in laravel

I am new to laravel. I have an array. It looks like this.
$state=[
1 => "Utah"
2 => "California"
3 => "Nevada"
6 => "Arizona"
]
I am trying to query the table in a database called a county. I want to display all the county that falls in those states which are in the array.
I write a code like this
foreach($state as $st) {
$data= DB::table('state')->Select(County)->where('name','=', $st)->get();
dd($data);
}
This is the code that I wrote. It does only return for the first state then after that, it gets stopped can someone help me. Any kind of help is appreciated.
It stops because dd() is dump and DIE. So it is like you would call:
dump($data);
die();
Try something like:
$query= DB::table('state');
foreach($state as $st) {
$query->orWhere('name','=', $st);
}
$data = $query->get();
It will make one DB call instead of X calls and returns a collection of records with which you can work.
You can try:
DB::table('country')->whereIn('name', array_values($state))->get();
You have to give categories to filter and next join eachother
App\YourModel::select('what you want')->join('category','your_models.id','=','category.your_model_id')->get();

Update a row using idiorm and php

I have this function to update a record, but i cannot it fails and send me a "Primary key ID missing from row or is null" message, how can I fix it?
public static function update_child($data)
{
try
{
$update= ORM::for_table("dm_child",DM_TAG)
->where_equal($data["id_child"]);
$update -> set(array(
"gender" => $data["gender"]
"age_year" =>$data["year"]
"age_month" => $data["month"]
));
$update -> save();
}
catch(PDOException $ex)
{
ORM::get_db()->rollBack();
throw $ex;
}
}
Idiorm assumes that the name of the primary key is 'id', which is not that, in your case.
Therefore you have to explicitly specify it to Idiorm:
<?php
ORM::configure('id_column_overrides', array(
'dm_child' => 'id_child',
'other_table' => 'id_table',
));
See Docs>Configuration.
The answer is indeed the one provided by #iNpwd for changing the default 'id' column name for queries on a per table basis:
ORM::configure('id_column_overrides', array(
'table_name' => 'column_name_used_as_id',
'other_table' => array('pk_1', 'pk_2') // a compound primary key
));
The thing that was biting me on getting it to recognize my query was WHERE I was changing the ORM::configure values. I was not in the correct file.
A deeper link to specifically the ID Column configuration: http://idiorm.readthedocs.org/en/latest/configuration.html#id-column
I just met this problem 2 minutes ago. The real reason is, you forgot select id field in querying.
demo:
$demo = ORM::for_table('demo')->select('field_test')->find_one($id);
$demo->field_test = 'do';
$demo->save();
You will get the error.
change to :
$demo = ORM::for_table('demo')->select('field_test')->select('id')->find_one($id);
It will fix the problem.
Some tips in documents:
https://github.com/j4mie/idiorm/blob/master/test/ORMTest.php
/**
* These next two tests are needed because if you have select()ed some fields,
* but not the primary key, then the primary key is not available for the
* update/delete query - see issue #203.
* We need to change the primary key here to something other than id
* becuase MockPDOStatement->fetch() always returns an id.
*/
I've never used idiorm, so cannot guarantee that my answer will work for you, but from this page and under "Updating records", we have an example which is similar but slightly different to yours.
// The 5 means the value of 5 in the primary-key column
$person = ORM::for_table('person')->find_one(5);
// The following two forms are equivalent
$person->set('name', 'Bob Smith');
$person->age = 20;
// This is equivalent to the above two assignments
$person->set(array(
'name' => 'Bob Smith',
'age' => 20
));
// Syncronise the object with the database
$person->save();
I'm sure I'll learn the reason behind this, but let me tell you all I understand at the moment, and how I "fixed" it.
Here is the beginning of idiorm's save function:
public function save() {
$query = array();
// remove any expression fields as they are already baked into the query
$values = array_values(array_diff_key($this->_dirty_fields, $this->_expr_fields));
if (!$this->_is_new) { // UPDATE
// If there are no dirty values, do nothing
if (empty($values) && empty($this->_expr_fields)) {
return true;
}
$query = $this->_build_update();
$id = $this->id(true);
Right there, on that last line, when trying to access the $this->id, you are getting an exception thrown:
throw new Exception('Primary key ID missing from row or is null');
$this does not contain an id property. I'm not really sure how it could. The example given both on their homepage and in the docs doesn't do anything special to address this. In fact I am copying them 1:1 and still yielding the same error as you.
So, all that said, I fixed this error by just adding in my own id:
$crop = ORM::for_table('SCS_Crop')->find_one($id);
$crop->id = $id;
$crop->Name = "Foo";
$crop->save();
This also happens when the id field name is ambiguous, e.g. when joining two tables both having an id column. This is the case with referenced tables
Model::factory('tableOne')
->left_outer_join('tableTwo', array('tableOne.tableTwo_id', '=', 'tableTwo.id'))
->find_one($id);
In these cases set an alias to the ID column of the parent tableOne to later access it while saving. Make sure that you also select other columns you need - e.g. by ->select('*'):
Model::factory('tableOne')
->select('*')
->select('tableOne.id', 'id')
->left_outer_join('tableTwo', array('tableOne.tableTwo_id', '=', 'tableTwo.id'))
->find_one($id);
if in table primary key/ field name not id then following id column overrides required
default id (primary_key) to replace with other id name (primary_key)
ORM::configure('id_column_overrides', array(
'user' => 'user_id',
));
$update = ORM::for_table('user')->find_one(1);
$update->name = "dev";
try{
$update->save();
}catch(Exception $e){
echo $e;
}
print_r($update);

why not insert query is working in codeigniter when ever we use right syn.?

why not insert query is working whenever i am using right syn.,i have used this type syntax in my other function of same controller.
code
$reviewData = $this->input->post('reviewData');
$id=1;
$rdaraaa = array(
'id' => $id,
'content' => $reviewData
);
$this->db->insert('reviews', $rdataaa);
please help me
Your variable name is wrong.It should be
$this->db->insert('reviews', $rdaraaa);
You have given wrong array $rdataaa instead of $rdaraaa.And makesure that id,content are the column names in your table reviews.
remove this code print_r($rdaraaa); die; and it should be
$this->db->insert('reviews',$rdaraaa)

What does the $this->db->select portion of the CI Active Record API do?

I have code like this:
$this->db->select('title')->from('entries')->where('id', 1);
$query = $this->db->get();
echo $query->row('title');
Which echoes the title from the entries table where the id is equal to 1.
Why doesn't it work without the 'title in row function?
echo $query->row();
As it returns the first row?
Why do I have to have 'title' in both places ($query->row and $this->db->select), in order for this to work? It doesn't make sense to me.
Can anybody explain how this works, supposedly provide with alternative ways to get the value from the database?
$this->db->select('title')->from('entries')->where('id', 1);
Generates
SELECT title FROM entries WHERE id = 1
$query retrieves the result in an array:
array( [0] => array( [title] => 'your title' ))
row('title') returns the title column from the first row of your result array.
The reason you need to tell it which column to get is because row and get can be used with many columns.

Generating Links Within a HTML Table Using Query Results. (Codeigniter)

I’m trying to display two columns in my table view, one being a title of the document, the next being a description of the document. I have a column in the particular table which I am selecting named “filename” that stores the name of the uploaded document which is associated with it’s title and description.
I’m curious as to how I would manage to display only the title and description, while setting the data contained in the “filename” column as the hyperlink value of the title? (Basically, I’m wanting them to be able to download a document once they click on it’s name)
I’m fairly certain that I can pull this off by manually by skipping the table generator and doing a “foreach” in the view to print out all the data from the resultset, but I’m open to suggestions, as this would make for sloppy code. Here’s a snippet of my controller below.
<?php
class blah extends CI_Controller {
public function troubleshooting() {
$this->load->library('pagination');
$this->load->library('table');
$config['base_url'] = 'http://somewebsite.com/troubleshooting';
$config['total_rows'] = $this->db->get('document')->num_rows();
$config['per_page'] = 10;
$config['num_links'] = 10;
$this->pagination->initialize($config);
$data['records'] = $this->db->get('document', $config['per_page'],$this->uri->segment(3));
$this->db->select('doc_title, filename, description, category_id, product_id');
$this->db->where('category_id = 1');
$this->db->where('product_id = 1');
$this->db->order_by('doc_title', 'asc');
$this->load->view('blah/troubleshooting.php', $data);
}
}
You can create the link in your query with a select->(CONCAT(...), FALSE) query.
http://codeigniter.com/forums/viewthread/105687/#531878
** UPDATE **
Well, your table helper is going to receive an array - and your db query is going to return an array. So, you have to create your query in a way that will create your array the way you need it for the table helper.
You need something like this:
$records = [
'doc_title' => 'My Title',
'filename' => 'filename.php',
'description' => 'My description text here.',
'category_id' => 5,
'product_id' => 56
]
Your query might look like this:
$this->db->select('doc_title');
$this->db->select('CONCAT("<a href=path/to/'.filename.'>".'filename'."</a>")', FALSE);
$this->db->select('description, category_id, product_id');
$this->db->where('category_id = 1');
$this->db->where('product_id = 1');
$this->db->order_by('doc_title', 'asc');
$records = $this->db->get('document', $config['per_page'],$this->uri->segment(3));
The trick is your CONCAT function will have some 'quote' issues. Without actually testing this myself, I'm not sure I've got the quotes right. Take a look at some docs there and that should help: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat

Categories