За последние 24 часа нас посетили 16737 программистов и 1635 роботов. Сейчас ищут 836 программистов ...

Добавление в базу данных информацию с разных таблиц

Тема в разделе "PHP для новичков", создана пользователем Anthony Fink, 18 авг 2018.

  1. Anthony Fink

    Anthony Fink Новичок

    С нами с:
    30 май 2018
    Сообщения:
    44
    Симпатии:
    0
    как правильно написать query чтобы я мог юзать дополнительные таблицы
    PHP:
    1. <?php
    2.  
    3. class StudentModel {
    4.     private $db;
    5.     public function __construct(){
    6.         $this->db = new Database;
    7.     }
    8.     public function getStudents(){
    9.         $this->db->query('SELECT * FROM students');
    10.         $results = $this->db->resultSet();
    11.         return $results;
    12.     }
    13.     public function getStudentById( $student_id ){
    14.         $this->db->query('SELECT * FROM students WHERE student_id = :student_id');
    15.         $this->db->bind(':student_id', $student_id );
    16.         $row = $this->db->single();
    17.         return $row;
    18.     }
    19.     public function createStudent( $data ){
    20.         $this->db->query('INSERT INTO students (student_name,student_phone,student_email,student_image)
    21.                          VALUES(:student_name,:student_phone,:student_email,:student_image)');
    22.         // Bind values
    23.         $this->db->bind(':student_name', $data['student_name']);
    24.         $this->db->bind(':student_phone', $data['student_phone']);
    25.         $this->db->bind(':student_email', $data['student_email']);
    26.         $this->db->bind(':student_image', $data['student_image']);
    27.             // Execute
    28.             if($this->db->execute()){
    29.                 return true;
    30.             } else{
    31.                 return false;
    32.             }
    33.     }
    34.     public function updateStudent($data){
    35.         $this->db->query('UPDATE students SET student_name = :student_name, student_email = :student_email, student_phone = :student_phone, student_image = :student_image WHERE student_id = :student_id');
    36.         // Bind Values
    37.         $this->db->bind(':student_id', $data['student_id']);
    38.         $this->db->bind(':student_name', $data['student_name']);
    39.         $this->db->bind(':student_email', $data['student_email']);
    40.         $this->db->bind(':student_phone', $data['student_phone']);
    41.         $this->db->bind(':student_image', $data['student_image']);
    42.         // Execute
    43.         if($this->db->execute()){
    44.             return true;
    45.         } else{
    46.             return false;
    47.         }
    48.     }
    49.     public function delete($data){
    50.         $this->db->query('DELETE FROM students WHERE student_id = :student_id');
    51.         // Bind values
    52.         $this->db->bind(':student_id', $data['student_id']);
    53.         // Execute
    54.         if($this->db->execute()){
    55.             return true;
    56.         } else{
    57.             return false;
    58.         }
    59.     }
    60.     public function courses( $student_id ) {
    61.         $select = "SELECT courses.* FROM courses
    62.                                      LEFT JOIN courses_students
    63.                                      ON courses.course_id = courses_students.course_id
    64.                                      WHERE courses_students.student_id=:student_id";
    65.         $this->db->query( $select );
    66.         $this->db->bind(':student_id', $student_id );
    67.         $results = $this->db->resultSet();
    68.         return $results;
    69.     }
    70.  
    71. }
    --- Добавлено ---
    HTML:
    1. <div class="row">
    2.     <div class="sm-12 col">
    3.         <h2>New Student</h2>
    4.         <p>Add new student to school</p>
    5.         <form action="<?php echo URLROOT;?>/student/create" method="post" enctype="multipart/form-data">
    6.             <div class="form-group">
    7.                 <label for="student_name">Student Name: <sup>*</sup></label>
    8.                 <input type="text" class="form-control form-control-lg <?php echo (!empty($data['errors']['name_err'])) ? 'is-invalid':'';?>" name="student_name" value="<?php echo  $data['errors']['student_name'];?>">
    9.                 <span class="invalid-feedback"><?php echo $data['errors']['name_err']; ?></span>
    10.             </div>
    11.             <div class="form-group">
    12.                 <label for="student_email">Student Email: <sup>*</sup></label>
    13.                 <input type="email" class="form-control form-control-lg <?php echo (!empty( $data['errors']['email_err'])) ? 'is-invalid':'';?>" name="student_email" value="<?php echo  $data['errors']['student_email']; ?>">
    14.                 <span class="invalid-feedback"><?php echo  $data['errors']['email_err']; ?></span>
    15.             </div>
    16.             <div class="form-group">
    17.                 <label for="student_phone">Student Phone: <sup>*</sup></label>
    18.                 <input type="text" class="form-control form-control-lg <?php echo (!empty( $data['errors']['email_err'])) ? 'is-invalid':'';?>" name="student_phone" value="<?php echo  $data['errors']['student_phone']; ?>">
    19.                 <span class="invalid-feedback"><?php echo  $data['errors']['phone_err']; ?></span>
    20.             </div>
    21.             <div class="form-group">
    22.                 <label for="student_image">Student Photo: <sup>*</sup></label>
    23.                 <input type="file" class="form-control-file form-control-lg <?php echo (!empty( $data['errors']['img_err'] )) ? 'is-invalid':'';?>" name="student_image" value="<?php echo  $data['errors']['student_image'];?>">
    24.                 <span class="invalid-feedback"><?php echo $data['errors']['img_err']; ?></span>
    25.             </div>
    26.             <div class="form-group">
    27.                 <ul>
    28.                     <?php
    29.                    foreach ($data['courses'] as $course ) { ?>
    30.                         <li>
    31.                             <input type="checkbox" name="courses[]" class="form-check-input">
    32.                             <label for="courses[]" class="form-check-label"><?php echo $course->course_name; ?></label>
    33.                         </li>
    34.                     <?php };
    35.                    ?>
    36.                 </ul>
    37.             </div>
    38.             <div class="form-group">
    39.             <input type="submit" value="Add Student" class="btn btn-success btn-block">
    40.         </form>
    41.     </div>
    42. </div>
    оутпут
    --- Добавлено ---
    контролер
    PHP:
    1. <?php
    2. class Student extends Controller{
    3.     public function __construct(){
    4.         if(!isLoggedIn()){
    5.             redirect('pages/login');
    6.         }
    7.         $this->StudentModel = $this->model('StudentModel');
    8.         $this->CourseModel = $this->model('CourseModel');
    9.     }
    10.     public function index( $extra = null, $template = null ){
    11.         $students = $this->StudentModel->getStudents();
    12.         $courses = $this->CourseModel->getCourses();
    13.         $data = [
    14.             'title' => 'Welcome to School',
    15.             'courses' => $courses,
    16.             'students' => $students
    17.         ];
    18.         if (!empty($extra)) {
    19.             $keys = array_keys($extra);
    20.             $data[$keys[0]] = $extra[$keys[0]];
    21.         }
    22.         if (!empty($template)) {
    23.             $data[ 'student_template' ] = $template;
    24.         }
    25.         $this->view('school/index', $data );
    26.     }
    27.  
    28.     public function create(){
    29.  
    30.         if($_SERVER['REQUEST_METHOD'] == 'POST'){
    31.             $_POST = filter_input_array(INPUT_POST);
    32.             $data = [
    33.                 'student_name'               => trim($_POST['student_name']),
    34.                 'student_email'              => trim($_POST['student_email']),
    35.                 'student_phone'              => trim($_POST['student_phone']),
    36.                 'student_image'              => trim($_POST['student_image']),
    37.                 'name_err' => '',
    38.                 'email_err' => '',
    39.                 'image_err'  => ''
    40.             ];
    41.             // Validate Data
    42.             if(empty($data['student_name'])){
    43.                 $data['name_err'] = 'Please enter student name';
    44.             }
    45.             if(empty($data['student_email'])){
    46.                 $data['email_err'] = 'Please enter student email address';
    47.             }
    48.             if(empty($data['student_phone'])){
    49.                 $data['phone_err'] = 'Please enter phone number';
    50.             }
    51. //            if(empty($data['student_image'])){
    52. //                $data['img_err'] = 'Please enter student photo';
    53. //            }
    54.             // Make sure no errors
    55.             if(empty($data['name_err']) && empty($data['email_err']) && empty($data['img_err'])){
    56.                 // Validated
    57.                 if( $this->StudentModel->createStudent($data) ){
    58.                     flash('student_message', 'Student added');
    59.                     redirect('school');
    60.                 } else{
    61.  
    62.                     die('Something went wrong');
    63.                 }
    64.             } else {
    65.                 // Load view with errors
    66.                 $this->index( array( 'errors' => $data ), 'create' );
    67.             }
    68.         } else {
    69.             $data = [
    70.                 'student_name'        => '',
    71.                 'student_email'       => '',
    72.                 'student_phone'       => '',
    73.                 'student_image'       => ''
    74.             ];
    75.             $this->index( array( 'errors' => $data ), 'create' );
    76.         }
    77.     }
    78.     public function display( $id){
    79.         $student = $this->StudentModel->getStudentById( $id );
    80.         $courses = $this->StudentModel->courses( $id );
    81.         $info['student'] = $student;
    82.         $info['courses'] = $courses;
    83.         $this->index( array( 'info' => $info ), 'display' );
    84.     }
    85.  
    86.     public function delete ( $id )
    87.     {
    88.         if ( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' ) {
    89.             // Get existing student from model
    90.             $this->StudentModel->getStudentById ( $id );            // Check for owner
    91.             // Removing Post
    92.             if ( $this->StudentModel->delete ( $id ) ) {
    93.                 flash ( 'student_message' , 'Student Removed' );
    94.                 redirect ( 'school' );
    95.             } else {
    96.                 die( 'Something went wrong' );
    97.             }
    98.         } else {
    99.             redirect ( 'posts' );
    100.         }
    101.     }
    102. }
    --- Добавлено ---
    есть еще такое же на курс