Я могу заставить этот код работать только с использованием php native, но я хочу точно знать, что он будет делать, если я в буквальном смысле использую Codeigniter, например, Controller, Model и View, не так ли? Можете ли вы посмотреть и помочь мне переместить код в Codeigniter
Таким образом, этот код показывает все имя сотрудника и рядом с ним есть кнопка с подробными сведениями, в которой будет отображаться подробная информация о самом сотруднике
index.php
<?php
$connect = mysqli_connect("localhost", "root", "", "testing_ci");
$query = "SELECT * FROM tbl_employee";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<br /><br />
<div class="container" style="width:700px;">
<h3 align="center"> </h3>
<br />
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="70%">Employee Name</th>
<th width="30%">View</th>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row["name"]; ?></td>
<td><input type="button" name="view" value="view" id="<?php echo $row["id"]; ?>" class="btn btn-info btn-xs view_dawta" /></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
</body>
</html>
<div id="dataModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Employee Details</h4>
</div>
<div class="modal-body" id="employee_detail">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$('.view_dawta').click(function(){
var employee_id = $(this).attr("id");
$.ajax({
url:"select.php",
method:"post",
data:{employee_id:employee_id},
success:function(data){
$('#employee_detail').html(data);
$('#dataModal').modal("show");
}
});
});
});
</script>
select.php
<?php
if(isset($_POST["employee_id"]))
{
$output = '';
$connect = mysqli_connect("localhost", "root", "", "testing_ci");
$query = "SELECT * FROM tbl_employee WHERE id = '".$_POST["employee_id"]."'";
$result = mysqli_query($connect, $query);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">';
while($row = mysqli_fetch_array($result))
{
$output .= '
<br>
<tr>
<td width="30%"><label>Name</label></td>
<td width="70%">'.$row["name"].'</td>
</tr>
<tr>
<td width="30%"><label>address</label></td>
<td width="70%">'.$row["address"].'</td>
</tr>
<tr>
<td width="30%"><label>gender</label></td>
<td width="70%">'.$row["gender"].'</td>
</tr>
<tr>
<td width="30%"><label>designation</label></td>
<td width="70%">'.$row["designation"].' Year</td>
</tr>
';
}
$output .= "</table></div>";
echo $output;
}
?>
ПРИМЕЧАНИЕ. Этот код не был полностью протестирован и является основным примером того, как делать то, что вы хотите.
Предполагается, что вы используете таблицу под названием "пользователи" с столбцами "id" и "name".
Вам необходимо настроить подключение к базе данных в /application/config/database.php.
Модель:
/application/models/Users_model.php
Именно здесь происходит ВСЕ ваши запросы к базе данных:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Users_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
// get a list of all users
public function get_all_users() {
return $this->db->query("
SELECT id, name
FROM users;
")->result();
}
// get the details for one specific user
public function get_user(int $id) {
return $this->db->query("
SELECT *
FROM users
WHERE id = ?;
", $id)->result();
}
}
контроллер:
/application/controllers/Users.php
Здесь все ваши запросы начинаются. Перейдите к "domain.com/users", чтобы получить к нему доступ (или "localhost/myapp/users" в зависимости от вашей настройки).
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Users extends CI_Controller
{
public function __construct() {
parent::__construct();
$this->load->model('Users_model');
}
// show a list of all users
public function index() {
// do this by loading a "view" that formats the data we gather here.
$this->load->view('display_users_view', [
'users' => $this->Users_model->get_all_users(),
'title' => 'Title for your HTML could go here.'
]);
}
// return the details for one user
// if $id is not specified, then look for it in a POST variable
public function get_user($id = null) {
// get the employee_id from the ajax request
// this means if $id is set (not null) then make $employee_id = $id. Otherwise, make $employee_id = posted input
$employee_id = ($id) ? $id : (int) $this->input->post('employee_id');
$user = $this->Users_model->get_user($employee_id);
// if the user made an ajax request, send json encoded data
if (! $this->input->is_ajax_request())
echo json_encode($user);
else
return $user;
}
}
Посмотреть:
/application/views/display_users_view.php
Я не очень тщательно очищал ваш HTML-код, но добавлял скрипты для загрузки jquery и модального.
<!DOCTYPE html>
<html>
<head>
<title><?= $title; ?></title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.css" />
</head>
<body>
<br><br>
<div class="container" style="width:700px;">
<h3 align="center"> </h3>
<br>
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="70%">Employee Name</th>
<th width="30%">View</th>
</tr>
<?php foreach($users as $user): ?>
<tr>
<td><?= $user->name; ?></td>
<td><input type="button" name="view" value="view" id="<?= $user->id; ?>" class="btn btn-info btn-xs view_dawta"></td>
</tr>
<?php endforeach; ?>
</table>
</div>
</div>
<div id="dataModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Employee Details</h4>
</div>
<div class="modal-body" id="employee_detail">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$('.view_dawta').click(function(){
var employee_id = $(this).attr("id");
$.ajax({
url:"/users/get_user",
method:"post",
data:{employee_id:employee_id},
success:function(data){
$('#employee_detail').html(data);
$('#dataModal').modal("show");
}
});
});
});
</script>
</body>
</html>
Имейте в виду, что это не проверяет, разрешено ли человеку иметь доступ к этой информации. Если вы хотите сделать это, добавьте что-то вроде этого в свой __construct()
в контроллере:
// if the user isn't logged in, get them out of here
if ($this->session->userdata('access_level') < 10) {
$this->output->set_status_header(403);
return;
}
CI
. И после установки вы найдете примерыController
,Model
иView
в проекте. Они помогут вам понять, как они связаны и как они работают. Удачи !