P_R
P_R

Reputation: 488

Codeigniter select single row from table

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 got 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 no text

foreach($notizie as $notizia)
{
    echo $notizia["titoloit"];
}

Upvotes: 0

Views: 575

Answers (3)

Newbie
Newbie

Reputation: 23

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"];
  }
}

Upvotes: 1

Zester Quinn Albano
Zester Quinn Albano

Reputation: 81

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

Upvotes: 0

Newbie
Newbie

Reputation: 23

$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?

Upvotes: 0

Related Questions