Hashey100
Hashey100

Reputation: 984

Creating onclick rows when displaying a database

I have a database which displays results of all employees that are stored in it.

It works and displays all the employees but I was wondering if its possible to make each row click-able referring to a specific id.

I thought I would have to create a for each function that loops through every row and make them onClick but i am still very very confused.

    Controller

$this->load->model('Employee_model');
$results = $this->Employee_model->search($offset,$sort_by,$sort_order);
$data['employees'] = $results['rows'];
$data['num_results'] = $results['num_rows'];

$this->load->view('employees', $data);


    Model
function search($sort_by, $sort_order)
{

//result query
$q = $this->db->select('*')
    ->from('employees')
    ->order_by($sort_by,$sort_order)


      // if onclick row then display additional information


}

 view
<?php foreach($employees as $row): ?>
<tr> 
    <td><?php echo $row->first_name; ?></td>
    <td><?php echo $row->last_name; ?></td>
    <td><?php echo $row->gender; ?> </td>

    </tr>
    <?php endforeach; ?>

Upvotes: 0

Views: 1553

Answers (2)

Rooneyl
Rooneyl

Reputation: 7902

How about something like;
in view;

<?php foreach($employees as $row): ?>
<tr data-id="<?php echo $employee->id; ?>"> 
    <td><?php echo $employee->first_name; ?></td>
    <td><?php echo $employee->last_name; ?></td>
    <td><?php echo $employee->gender; ?> </td>
    </tr>
<?php endforeach; ?>

<script type="text/javascript">
$("tr").click(function() {
    window.location = 'your-controller/the-id-view-function/'+$(this).data('id');
}
</script>

Upvotes: 2

Naryl
Naryl

Reputation: 1888

the onclick event is handled by Javascript in a HTML page. So basically what you need to do is:

In a php script retrieve the database info and, as you said, do a loop. Either store the HTML code into a variable or echo it, but keep in mind you have to output a whole correct HTML page (with html, head and body tags).

You can either insert the onclick event on the HTML you return from PHP or declare a click event from Jquery. The first is more simple so I'll give an example using this method

while(something){ //loop through all DB results
    $table_tr.="<tr onclick='do_something_when_tr_click(".$id_from_db.")'><td>$data_from_db</td></tr>";

}

echo "<html><head><script>(javascript functions go here)</script></head><body><table>$table_tr</table></body></html>";

Upvotes: 0

Related Questions