0

I've started a To-do App. I've created a login and registration from and made the to-do application, but I need to have a unique to-do list for every user, right now all users get the same to-do list. I've created a database with two tables one for the to-do items(called 'todos') and one for the users. Is there any way I can link these two tables together so that each user has their own to-do items?

Here is my index.php code(registration)

    <?php
    // Include config file
    require 'config.php';

    // Define variables and initialize with empty values
    $username = $password = $confirm_password = "";
    $username_err = $password_err = $confirm_password_err = "";

    // Processing form data when form is submitted
    if($_SERVER["REQUEST_METHOD"] == "POST"){

      // Validate username
       if(empty(trim($_POST["username"]))){
            $username_err = "Please enter a username.";
        } else{
            // Prepare a select statement
            $sql = "SELECT id FROM users WHERE username = ?";
    
            if($stmt = mysqli_prepare($link, $sql)){
                // Bind variables to the prepared statement as parameters
                mysqli_stmt_bind_param($stmt, "s", $param_username);
        
                // Set parameters
                $param_username = trim($_POST["username"]);
        
                // Attempt to execute the prepared statement
                if(mysqli_stmt_execute($stmt)){
                    /* store result */
                    mysqli_stmt_store_result($stmt);
            
                    if(mysqli_stmt_num_rows($stmt) == 1){
                        $username_err = "This username is already taken.";
                    } else{
                        $username = trim($_POST["username"]);
                    }
                } else{
                    echo "Oops! Something went wrong. Please try again later.";
                }

                // Close statement
                mysqli_stmt_close($stmt);
            }
        }

        // Validate password
        if(empty(trim($_POST["password"]))){
            $password_err = "Please enter a password.";     
        } elseif(strlen(trim($_POST["password"])) < 6){
            $password_err = "Password must have atleast 6 characters.";
        } else{
            $password = trim($_POST["password"]);
        }

        // Validate confirm password
        if(empty(trim($_POST["confirm_password"]))){
            $confirm_password_err = "Please confirm password.";     
        } else{
           $confirm_password = trim($_POST["confirm_password"]);
            if(empty($password_err) && ($password != $confirm_password)){
                $confirm_password_err = "Password did not match.";
            }
        }

// Check input errors before inserting in database
if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){
    
    // Prepare an insert statement
    $sql = "INSERT INTO users (username, password) VALUES (?, ?)";
     
    if($stmt = mysqli_prepare($link, $sql)){
        // Bind variables to the prepared statement as parameters
        mysqli_stmt_bind_param($stmt, "ss", $param_username, $param_password);
        
        // Set parameters
        $param_username = $username;
        $param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash
        
        // Attempt to execute the prepared statement
        if(mysqli_stmt_execute($stmt)){
            // Redirect to login page
            header("location: login.php");
        } else{
            echo "Something went wrong. Please try again later.";
        }

        // Close statement
        mysqli_stmt_close($stmt);
    }
}

// Close connection
mysqli_close($link);
    }
    ?>

    <!DOCTYPE html>
    <html lang="en">
    <head>
       <meta charset="UTF-8">
        <title>Sign Up</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
        <style type="text/css">
            body{ font: 14px sans-serif; }
            .wrapper{ width: 350px; padding: 20px; }
       </style>
   </head>
   <body>
        <div class="wrapper">
            <h2>Sign Up</h2>
            <p>Please fill this form to create an account.</p>
            <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                <div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
                    <label>Username</label>
                    <input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
                    <span class="help-block"><?php echo $username_err; ?></span>
                </div>    
                <div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
            <label>Password</label>
            <input type="password" name="password" class="form-control" value="<?php echo $password; ?>">
            <span class="help-block"><?php echo $password_err; ?></span>
        </div>
        <div class="form-group <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>">
            <label>Confirm Password</label>
            <input type="password" name="confirm_password" class="form-control" value="<?php echo $confirm_password; ?>">
            <span class="help-block"><?php echo $confirm_password_err; ?></span>
        </div>
        <div class="form-group">
            <input type="submit" class="btn btn-primary" value="Submit">
            <input type="reset" class="btn btn-default" value="Reset">
        </div>
        <p>Already have an account? <a href="login.php">Login here</a>.</p>
    </form>
</div>    
   </body>
   </html>

This is my login.php code(login)

    <?php
    // Initialize the session
    session_start();

     // Check if the user is already logged in, if yes then redirect him to welcome page
    if(isset($_POST['loggedin']) && $_SESSION["loggedin"] === true){
        header("location: login.php");
        exit;
    }

    // Include config file
    require 'config.php';

    // Define variables and initialize with empty values
    $username = $password = "";
    $username_err = $password_err = "";

    // Processing form data when form is submitted
    if($_SERVER["REQUEST_METHOD"] == "POST"){

        // Check if username is empty
        if(empty(trim($_POST["username"]))){
            $username_err = "Please enter username.";
        } else{
            $username = trim($_POST["username"]);
        }

        // Check if password is empty
        if(empty(trim($_POST["password"]))){
            $password_err = "Please enter your password.";
        } else{
            $password = trim($_POST["password"]);
        }

        // Validate credentials
        if(empty($username_err) && empty($password_err)){
           // Prepare a select statement
           $sql = "SELECT id, username, password FROM users WHERE username = ?";
    
           if($stmt = mysqli_prepare($link, $sql)){
                // Bind variables to the prepared statement as parameters
                mysqli_stmt_bind_param($stmt, "s", $param_username);
        
                // Set parameters
                $param_username = $username;
        
               // Attempt to execute the prepared statement
                if(mysqli_stmt_execute($stmt)){
                    // Store result
                    mysqli_stmt_store_result($stmt);
            
                    // Check if username exists, if yes then verify password
                    if(mysqli_stmt_num_rows($stmt) == 1){                    
                       // Bind result variables
                        mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
                        if(mysqli_stmt_fetch($stmt)){
                           if(password_verify($password, $hashed_password)){
                                // Password is correct, so start a new session
                                session_start();
                        
                                // Store data in session variables
                               $_SESSION["loggedin"] = true;
                                $_SESSION["id"] = $id;
                                $_SESSION["username"] = $username;                            
                        
                                // Redirect user to welcome page
                                header("location: todomain.php");
                            } else{
                                // Display an error message if password is not valid
                                $password_err = "The password you entered was not valid.";
                            }
                }
            } else{
                // Display an error message if username doesn't exist
                $username_err = "No account found with that username.";
            }
        } else{
            echo "Oops! Something went wrong. Please try again later.";
        }

        // Close statement
        mysqli_stmt_close($stmt);
    }
}

// Close connection
mysqli_close($link);
    }
    ?>

    <!DOCTYPE html>
    <html lang="en">
   <head>
       <meta charset="UTF-8">
       <title>Login</title>
       <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
       <style type="text/css">
    body{ font: 14px sans-serif; }
    .wrapper{ width: 350px; padding: 20px; }
       </style>
   </head>
   <body>
        <div class="wrapper">
           <h2>Login</h2>
           <p>Please fill in your credentials to login.</p>
            <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
               <div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
                   <label>Username</label>
                   <input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
                    <span class="help-block"><?php echo $username_err; ?></span>
                </div>    
                <div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
                    <label>Password</label>
                    <input type="password" name="password" class="form-control">
                    <span class="help-block"><?php echo $password_err; ?></span>
        </div>
        <div class="form-group">
            <input type="submit" class="btn btn-primary" value="Login">
        </div>
        <p>Don't have an account? <a href="register.php">Sign up now</a>.</p>
    </form>
</div>    
  </body>
   </html>

This is my todomain.php code(this is the page that I'm redirected to when I successfully login, the main page)

    <?php 
    require 'db_conn.php';


   ?>
   <!DOCTYPE html>
    <html lang="en">
    <head>
     <meta charset= "UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
    <link rel="stylesheet" href="css/bootstrap-grid.min.css">
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="style.css">


     <title>TODO App</title>
      <script src="https://kit.fontawesome.com/d72928d9b9.js" crossorigin="anonymous"></script>
      </head>
     <body>
         <div class="container m-5 p-2 rounded mx-auto bg-light shadow">
         <!-- App title section -->
         <div class="row m-1 p-4">
            <div class="col">
                <div class="p-1 h1 text-primary text-center mx-auto display-inline-block">
                    <i class="fa fa-check bg-primary text-white rounded p-2"></i>
                     <u>My Todo-s</u>
               </div>
             </div>
         </div>
         <!-- Create todo section -->
        <form action="app/add.php" method="POST" autocomplete="off">
         <div class="row m-1 p-3">
             <div class="col col-11 mx-auto">
        
                 <div class="row bg-white rounded shadow-sm p-2 add-todo-wrapper align-items-center justify-content-center">
            
                    <div class="col">
                         <input class="form-control form-control-lg border-0 add-todo-input bg-transparent rounded" type="text" name="title" placeholder="Add new ..">
                     </div>
                     <div class="col-auto m-0 px-2 d-flex align-items-center">
                <label class="text-secondary my-2 p-0 px-1 view-opt-label due-date-label d-none">Due date not set</label>
                <i class="fa fa-calendar my-2 px-1 text-primary btn due-date-button" data-toggle="tooltip" data-placement="bottom" title="Set a Due date"></i>
                <i class="fa fa-calendar-times-o my-2 px-1 text-danger btn clear-due-date-button d-none" data-toggle="tooltip" data-placement="bottom" title="Clear Due date"></i>
            </div>
            
            <div class="col-auto px-0 mx-0 mr-2">
                
                <button type="submit" class="btn btn-primary">Add</button>
                
                
            </div>
         
        </div>

        
    </div>
</div>
</form>
            <?php
                $todos=$conn->query("SELECT * FROM  todos ORDER BY id ASC");
              ?>

       <div class="row mx-1 px-5 pb-3 w-80">
            <div class="col mx-auto">

               <?php
               while($todo=$todos->fetch(PDO::FETCH_ASSOC)){ ?>
                <!-- Todo Item 1 -->

        
        <div class="row px-3 align-items-center todo-item rounded">

            <?php if($todo['checked']){ ?>
            
            <input type="checkbox" class="check-box" data-todo-id="<?php echo $todo['id'];?>" checked />
        <h2 class="checked"><?php echo $todo['title'] ?> </h2>
        <div class="col-auto m-1 p-0 todo-actions">
                <div class="row d-flex align-items-center justify-content-end">
          
        </div>
      </div>
    
         

                  
        <?php } else{ ?>
            <input type="checkbox" class="check-box" data-todo-id="<?php echo $todo['id'];?>"/>
             <h2><?php echo $todo['title'] ?></h2>
               
                      

        <?php } ?>

            <div class="col-auto m-1 p-0 d-flex align-items-center">


                <h2 class="m-0 p-0">
                    <i class="fa fa-square-o text-primary btn m-0 p-0 d-none" data-toggle="tooltip" data-placement="bottom" title="Mark as complete"></i>
                    
                </h2>
            </div>
           
            
         
            <div class="col-auto m-1 p-0 todo-actions">
                <div class="row d-flex align-items-center justify-content-end">

                    <h5 class="m-0 p-0 px-2">
                        <i class="fa fa-pencil text-info btn m-0 p-0" data-toggle="tooltip" data-placement="bottom" title="Edit todo"></i>
                    </h5>
                    <h5 class="m-0 p-0 px-2">
                      
                         
                    <i class="remove-to-do fa fa-trash-o text-danger btn m-0 p-0" data-toggle="tooltip" data-placement="bottom" title="Delete todo" id="<?php echo $todo['id']; ?>"></i>
                  </h5> 
                </div>
                <div class="row todo-created-info">
                    <div class="col-auto d-flex align-items-center pr-2">
                        <i class="fa fa-info-circle my-2 px-2 text-black-50 btn" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="Created date"></i>
                        <label class="date-label my-2 text-black-50"><?php echo $todo['date_time'] ?></label>
                    </div>
                </div>
            </div>
        </div>
    
            <?php } ?>













    </div>

      <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
       <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
        <script src="js/bootstrap.bundle.min.js"></script>
        <script src="js/myjs.js" ></script>
        <script src="js/jquery-3.3.1.min.js"></script>

        <script>
    $(document).ready(function(){

      $(".remove-to-do").click(function(e){
            const id = $(this).attr('id');
             $.post('app/remove.php', 
                  {
                      id: id
                  },
                  (data) => {
                     if(data){
                        $(this).parent().parent().parent().parent().hide(300);
                     }
                  }

            );
            
           
        });
      




        $(".check-box").click(function(e){
            const id = $(this).attr('data-todo-id');
            
            $.post('app/checking.php', 
                  {
                      id: id
                  },
                  (data) => {
                     if(data!='error'){
                        const h2= $(this).next();
                        if(data === '1'){
                            h2.removeClass('checked');
                        }else{
                            h2.addclass('checked');
                        }
                     }
                  }

            );
        });
    });
</script>


    </body>
     </html>
2
  • 1
    Please do not vandalize your posts (rolled back). Commented Mar 21, 2021 at 14:17
  • 1
    Welcome to Stack Overflow! Please don't make more work for other people by vandalizing your posts. By posting on the Stack Exchange network, you've granted a non-revocable right, under the CC BY-SA 4.0 license, for Stack Exchange to distribute that content (i.e. regardless of your future choices). By Stack Exchange policy, the non-vandalized version of the post is the one which is distributed. Thus, any vandalism will be reverted. If you want to know more about deleting a post please see: How does deleting work? Commented Mar 21, 2021 at 15:54

1 Answer 1

2

You'll need to add a relationship between todo and user, the best option is a FOREIGN KEY but is optional.

| users    | | todo    |
|----------| |---------|
| id       | | id      |
| username | | user_id |
| password | | title   |
             | checked |

So, you keep your user id when they login inside a $_SESSION and every time you list or insert things on the todo you use this reference:

INSERT INTO todo (user_id, title) VALUES (10, 'My Todo') -- or any other id
SELECT * FROM todo WHERE user_id = 10 -- or any other id

On PHP with PDO:

$stmt = $conn->prepare("INSERT INTO todos (user_id, title) VALUES (:user_id, :title)");
$stmt->execute([':user_id' => $user_id, ':title' => $title]);

On PHP with mysqli bind parameters you can do in this way:

$stmt = $mysqli->prepare("INSERT INTO todos (user_id, title) VALUES (?, ?)");
$stmt->bind_param("is", $user_id, $title);
$res = $stmt->execute();
Sign up to request clarification or add additional context in comments.

2 Comments

Created a foreign key called user_id and tried doing what you said and now it will not let me add any items
The foreign key are a constraint to keep your data integrity, but if you're learning don't use if for now, get used with all your code first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.