I am relatively experienced PHP developer.
I have chosen the CodeIgniter framework. So far I have understood how it is used. Until now, I want to be able to do a while loop.
Within my controller I have:
$this->load->model('Test');
$data['result'] = $this->Test->getInfo();
$this->load->view('index1', $data);
In my Model I have:
$result = mysql_query("SELECT * FROM users WHERE last_name='Hart'")or die(mysql_error());
$row = mysql_fetch_array( $result );
return $row;
And in my View:
echo $result[0];
However, this only outputs the first field within the first row found.
Please could you help me with retrieving the information from a database - while loop.
Does the while loop happen in the Model? Am I just echoing out the result correctly?
There's actually a much easier way to do what you want to do using the ActiveRecord class that CodeIgniter includes which will allow you to just return an array of results. Here's the documentation.
Your model would become:
$this->db->where('last_name','Hart');
$result = $this->db->get('users');
return $result->result_array();
You may also have to setup your database in application/config/database.php, and also load the database class in application/config/autoload.php:
$autoload['libraries'] = array('database');
To display this information, using the MVC pattern properly your controller should pass the information it gets from the model to a view. To do this generally you do this:
$data['myinfo'] = $this->test->getInfo();
$this->load->view('test_view',$data);
Then you have to create a view like so in applications/views/test_view.php:
<h1>Some HTML goes here</h1>
<?php
foreach($myinfo as $row) {
echo $row['field'];
}
?>
<p>Some more HTML goes here</p>
I suggest you read the CodeIgniter User Guide before diving into creating an application as CodeIgniter includes libraries that greatly simplify and speed up the whole process.
Well mysql_fetch_array will only bring back one row at a time, so you would need to put the while loop around the mysql_fetch_array call
Something like
while($row = mysql_fetch_array($result)) {
//save/process data
}
I would however just use codeigniters libraries to load the db and then use it:
$this->load->database();
$result = $this->db->query("SELECT * FROM users WHERE last_name='Hart'");
$result = $result->result_array();
//check for data and handle errors
return $result[0]
Related
I am trying to pass a users comment that they have posted into the thread to be displayed when they click the submit button on the create comment form. But the comment doesn't show up without refreshing the page (which also duplicates the comment). This is why I am trying to achieve this using redirect which I am finding difficult.
Currently in my controller i have the following code..
...
$query = 'SELECT * FROM thread where id='.$id;
$data['thread'] = $this->db->query($query)->result_array();
$query2 = 'SELECT username FROM newUsers where id='.$userid;
$data ['username'] = $this->db->query($query2)->result_array();
$query3 = 'SELECT id FROM newUsers where id='.$userid;
$data ['userid'] = $this->db->query($query3)->result_array();
$query4 = 'SELECT * FROM comments where thread_id='.$id;
$data['comment'] = $this->db->query($query4)->result_array();
I displayed this data in my view and all works fine with the following method....
$this->load->view('header', $data);
$this->load->view('discussion/create');
$this->load->view('footer');
The problem I faced was the comment not appearing when the page loaded.. I know i have to use the following
redirect('postComment/post','refresh');
In my controller/method, i have the following method
$this->load->view('header');
$this->load->view('discussion/create');
$this->load->view('footer2');
Im currently trying to pass this data with flash data which i'm not sure if its the best way.. i'm using the following code for this..
$this->session->set_flashdata('thread', $data['thread']);
$this->session->set_flashdata('username', $data['username']);
$this->session->set_flashdata('userid', $data['userid']);
$this->session->set_flashdata('comment', $data['comment']);
In the view I am trying to set the data the following way..
$data['thread'] = $this->session->flashdata('thread');
$data['comment'] = $this->session->flashdata('comment');
$data['username'] = $this->session->flashdata('username');
$data['userid'] = $this->session->flashdata('userid');
To display the data i am using the following..
foreach($thread as $t):
$t['id'];
$t['thread_title'];
$t['subject'];
$t['content'];
$t['created'];
$t['votes'];
endforeach;
I get multiple undefined variables and Invalid argument supplied for foreach().. Any help for my problem would be greatly appreciated
Flashdata is only for temporary things and will only work on page refresh once. You could use set_userdata() and just set the variables as a regular session variable, then when you are done with them you can unset them.
However I think it would be prudent to look into why you are doing this with session variables rather than getting the database rows on-the-fly. As you database tables get larger this will eventually be problematic.
My view customer folder contains 2 files
For best practice your code in showUtility view page should be in controllr customer in showUtility function which you already created. Loading view is not necessary.
Any ways just to work your logic you need to add some more after query and getting result.
$query = $this->db->query("YOUR QUERY");
foreach ($query->result() as $row)
{
echo $row->utility_name;
break;
}
exit ();
I am terrible at PHP and I need to retrieve data from a database and give it to an index.php view. The view is pre-made and has this code:
//This is simplified - it has error handling that is not shown
$results = getAll($tableName);
//This is the line where it is failing
//Undefined Offset
$columns = empty($results) ? array() : array_keys($results[0]);
$idColumn = $columns[0];
There is all the rest of it but I just need to know what on earth it is that this bit of code is expecting. I have not even got the first clue what is supposed to be sent to this thing. I just need to get it to work.
This is what I have tried so far:
function getAll($tablename)
{
$mysqlConnection = getDbConnection();//Just the normal PDO db connection
$sql = "SELECT * FROM ".$tablename;
$sth = $mysqlConnection->prepare($sql);
$sth->execute();
$resultSet = $sth->fetch(PDO::FETCH_ASSOC);
return $resultSet;
}
I have tried various different PDO::FETCH_... types but nothing is working. There is no information about what it is that I am supposed to send that part of the view.
If you want all the rows from fetch(), you will need to loop through the result set because it will return a single row. In the loop you can place them in an array.
You can use fetchAll() instead. It will return all the results as an array.
I'm checking an PHP project which is build using PHP Codeigniter. I'm new to PHP, I like to get your valuable feedback
To retrieve name and item number in php library/controller, call is made to Item Model as below
'name'=>$this->CI->Item->get_info($item_id)->name
'item_number'=>$this->CI->Item->get_info($item_id)->item_number
I suspect above two line of code will make two independent database sql call instead of one call to retrive the two column of same table. Ie., there will be performance degrade. But somebody can please let me know whether it fires two sql statements please?
I think we need to handle like object
$row = $this->CI->Item->get_info($item_id);
echo $row->name;
echo $row->item_number;
Please suggest. Thanks in advance.
Model Function:
function get_info($item_id)
{
$this->db->from('items');
$this->db->where('item_id',$item_id);
$query = $this->db->get();
if($query->num_rows()==1)
{
return $query->row();
}
else
{
//Get empty base parent object, as $item_id is NOT an item
$item_obj=new stdClass();
//Get all the fields from items table
$fields = $this->db->list_fields('items');
foreach ($fields as $field)
{
$item_obj->$field='';
}
return $item_obj;
}
}
I am looking to export to a csv file using doctrine. However the data is likely to be quite large. Therefore I dont want to ouput to the results to a complete array. I want to traverse the results iteratively.
I have tried looking here
doctrine docs
The PHP looks something like this
$result = mysql_query("SELECT * FROM bigtable");
while($row = mysql_fetch_assoc($result)) {
// do code iteratively here
}
Not sure how you do the same thing in doctrine for symfony2
This is from the doctrine documentation about batch processing:
$q = $this->_em->createQuery('select u from MyProject\Model\User u');
$iterableResult = $q->iterate();
foreach ($iterableResult AS $row) {
// do stuff with the data in the row, $row[0] is always the object
// detach from Doctrine, so that it can be Garbage-Collected immediately
$this->_em->detach($row[0]);
}
'select u ....is the equivalent to your SELECT * ...
$result = mysql_query("SELECT * FROM bigtable");
while($row = mysql_fetch_assoc($result)) {
// do code iteratively here
}
is Flat PHP and symfony2/doctrine is designed to avoid it. http://symfony.com/doc/2.0/book/from_flat_php_to_symfony2.html
kudos to Dirk his answer is correct. If you want to iterat eover entity models then thats the way to go. Sometimes you may not have a model mapped setup for the sql results you are returning. If you want to do it over a raw sql file then this is how I did it. I would be interested to hear more thoughts.
You pass the doctrine connection into the class via your controller
Controller
function indexAction(){
$className = new ClassName($this->getDoctrine()->getEntityManager());
}
You can then create raw sql lookup
Entity
function __construct($entity){
$this->connection = $entity->getConnection();
}
function saveToCSV
{
$stmt = $this->connection->prepare("SELECT * FROM bitTableExample ");
$stmt->execute();
while($row = $stmt->fetch()){
// append to csv file
}
}