简体   繁体   English

如何根据user_id插入数据

[英]How do I insert data based on user_id

Here is my Code which I need help with 这是我的代码,我需要帮助

I need to link user_id to user_location in second table, which I wrote out in the bottom of this question 我需要将user_id链接到第二个表中的user_location,这是我在此问题底部写的

<?php


/**
 * Class UserInfo
 * handles the insert information about a paricular User
 */
class UserInfo {


    private $db_connection = null;



    public $errors = array();



    public $messages = array();




    public function __construct() {

        if(isset($_POST["info"])) {
            $this->Insert();
        }   

    }




    /**
     * Handles the Insertion of user Information into database
     **/
    private function Insert() {

        if (empty($_POST['user_location'])) {
            $this->errors[] = "Please fillout a location.";
        } elseif (!empty($_POST['user_location'])) {

            $this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);          

            if (!$this->db_connection->connect_errno) {

                $user_id = $_SESSION['user_name'];
                $user_location = $this->db_connection->real_escape_string($_POST['user_location']);


                $insert = "insert into users_info (user_location) values ('".$user_location."');";      
                $check_insert = $this->db_connection->query($insert);


                if ($check_insert) {
                    $this->messages[] = "Location inserted into database successfully!";
                } else {
                    $this->errors[] = "Location could not be inserted into database.";
                }

            }   

        }

    }







}


?>









And here is my Login script






<?php


    /**
     * Class Login
     * handles the user's login and logout process
     */  
    class Login {


        /**
         * @var object The database connection
         */

        private $db_connection = null;

        /**
         * @var object Collection of error messages.
         */

        public $errors = array();

        /**
         * @var Collection of success / neutral messages
         */

        public $messages = array();




        /**
         * The function "__construct()" automatically starts whenever an object of this class is created,
         * you know, when you do $login = new Login();"
         */      
         public function __construct() {

            // create/read session
            session_start();

            // check the possible login actions:
            // if the user tried to logout ( happens when user clicks logout button )
            if (isset($_GET["logout"])) {

                $this->doLogout();
            }

            // login via post data ( if the user just submitted a login form )
            elseif (isset($_POST["login"])) {

                $this->doLoginWithPostData();
            }

         }  // end function __construct();





         /**
          * log in with post data
          */
         private function doLoginWithPostData() {

            // check login form contents
            if (empty($_POST['user_name'])) {   
                $this->errors[] = "Username field is empty.";
            } elseif (empty($_POST['user_password'])) {
                $this->errors[] = "Password field was empty.";
            } elseif (!empty($_POST['user_name']) && !empty($_POST['user_password'])) {


                // create a database connection, using the constants from config/db.php
                // which we loaded in index.php
                $this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

                // change character set to utf8 and check it
                if(!$this->db_connection->set_charset("utf8")) {

                    $this->errors[] = $this->db_connection->error;
                }


                // if no connection errors (working database connection)
                if (!$this->db_connection->connect_errno) {


                    // escape the POST stuff
                    $user_name = $this->db_connection->real_escape_string($_POST['user_name']);

                    // database query, getting all the info of the selected user ( allows via email address 
                    // in the username field. )
                    $sql = "select user_name, user_email, user_password_hash
                            from users
                            where user_name = '".$user_name."' or user_email = '".$user_name."';";

                    $result_of_login_check = $this->db_connection->query($sql);


                    // if this user exists
                    if ($result_of_login_check->num_rows == 1) {

                        // get result row (as an object)
                        $result_row = $result_of_login_check->fetch_object();

                        // using PHP 5.5's password_verify() function to check if the provided password fits
                        // the hash of that user's password
                        if (password_verify($_POST['user_password'], $result_row->user_password_hash)) {

                            // write user data into PHP SESSION (a file on your server)
                            $_SESSION['user_name'] = $result_row->user_name;
                            $_SESSION['user_email'] = $result_row->user_email;
                            $_SESSION['user_login_status'] = 1;

                        } else {
                            $this->errors[] = "Wrong password. Try again.";
                        }   
                    } else {
                        $this->errors[] = "This user does not exist.";
                    }   
                } else {
                    $this->errors[] = "Database connection problem.";
                }

             }

        }





        /*
         * Preform the logout
         */
        public function doLogout() {

            // delete the session of the user
            $_SESSION = array();
            session_destroy();

            // return a little feeback message
            $this->messages[] = "You have been logged out.";

        }





        /**
         * simply return the current state of the user's login
         * @return boolean user's login status
         */
        public function isUserLoggedIn() {

            if (isset($_SESSION['user_login_status']) AND $_SESSION['user_login_status'] == 1) {

                return true;
            }

            // default return
            return false;   
        }



    }   // ------> Close class Login



?>


Here is my Database (mySQL)

CREATE TABLE IF NOT EXISTS users (
  user_id int(11) NOT NULL AUTO_INCREMENT,
  user_name varchar(64) NOT NULL,
  user_password_hash varchar(255) NOT NULL,
  user_email varchar(64) NOT NULL,
  PRIMARY KEY (user_id),
  UNIQUE KEY user_name (user_name),
  UNIQUE KEY user_email (user_email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


CREATE TABLE IF NOT EXISTS users_info (
  user_id int(11) NOT NULL,
  user_location varchar(255) NOT NULL,
  PRIMARY KEY (user_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Forign constrants = login2, users, user_id (sorry cant post image yet, need 10 reputation) 外来约束= login2,用户,user_id(对不起,尚无法发布图片,需要10个信誉)

Which kind of coding is this ? 这是哪种编码? You are breaking all the concepts of OOPS. 您正在打破OOPS的所有概念。

Problem with your existing code and must be resolved first - 现有代码存在问题,必须首先解决-

Class UserInfo 类UserInfo

  1. You are creating datamembers public. 您正在创建公共的数据成员。 It is breaking the concept of data hiding. 它打破了数据隐藏的概念。 Your datamember should be assigned values through the functions . 应该通过函数为数据成员分配值。 Instead of : public $errors = array(); 代替:public $ errors = array();
    public $messages = array(); 公共$ messages = array(); use: private $errors = []; 使用:私人$ errors = []; PHP >=5.4 PHP> = 5.4
    private $messages = []; 私人$ messages = []; PHP >=5.4 PHP> = 5.4

  2. Constructors should not be used for these kind of operation. 构造函数不应用于此类操作。

  3. Create a wrapper class for handling user Info. 创建用于处理用户信息的包装器类。
  4. Create a new Class that will handle all the database related queries. 创建一个新的Class,它将处理所有与数据库相关的查询。
  5. You can extend this class into UserInfo class. 您可以将此类扩展为UserInfo类。 This way, your code will not look beautiful but would be more scalable. 这样,您的代码看起来不会很漂亮,但可扩展性更高。
  6. So I remove your construct 所以我删除了你的构造
  7. If you are using autoincrement field,it will automatically increase the id so do not use NULL for this. 如果您使用的是自动递增字段,它将自动增加ID,因此请勿为此使用NULL。 Insert statement should have proper mapping. 插入语句应具有正确的映射。
  8. Please use exception handling instead using condition for errors. 请使用异常处理,而不要使用条件错误。

Class Login 班级登录

  1. Again data hiding concept missing 再次缺少数据隐藏概念

  2. Don't use session start in the constructor instead of this use session start in the very first line of your entry script. 不要在构造函数中使用会话启动,而要在输入脚本的第一行中使用会话启动。

  3. remove constructor from this class because of no use. 因为没有用,所以从此类中删除构造函数。
  4. change your access specifier to public for login and logout 将您的访问说明更改为公开以进行登录和注销
  5. Since, you have already created a class for database query handling (please create if you still not created.) 从那以后,您已经创建了一个用于数据库查询处理的类(如果尚未创建,请创建。)
  6. Session destory will kill all the sessions of your website at one go. 会话破坏将一次性杀死您网站的所有会话。 Please be specific to the session you want to destroy. 请具体说明您要取消的会话。

Number of table column and values in insert query are equal. 表列数和插入查询中的值相等。

For Example 例如

INSERT INTO table_name (column1, column2, column3)
VALUES (value1, value2, value3)

So your insert query would be 所以您的插入查询将是

 $insert = "insert into users_info (user_location) values ( '".$user_location."')";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM