如何从表1'中提取数据;s ID并将其放入表2';s外键通过PHP

如何从表1'中提取数据;s ID并将其放入表2';s外键通过PHP,php,mysql,Php,Mysql,因此,评论系统工作正常,我尝试放置不同的ArticleCID,并在特定的文章中添加评论。现在,我想在我添加评论时,比如说对它自己发布的“Microsoft”文章进行评论,而不在查询中添加ID。如果你不明白我想做什么,让我们假设我想隐式地,而不是显式地这样做: $query = "INSERT INTO comments (comment, name, articlecID) VALUES ('$comment', '$username', 1) 现在我需要一个“$articlecID”变量,而

因此,评论系统工作正常,我尝试放置不同的ArticleCID,并在特定的文章中添加评论。现在,我想在我添加评论时,比如说对它自己发布的“Microsoft”文章进行评论,而不在查询中添加ID。如果你不明白我想做什么,让我们假设我想隐式地,而不是显式地这样做:

$query = "INSERT INTO comments (comment, name, articlecID) VALUES ('$comment', '$username', 1)
现在我需要一个“$articlecID”变量,而不是查询中的数字“1”

我尝试从HTML中的隐藏字段获取数据,并将其放入PHP,如下所示:

$articlecID = e($_POST['articlecID']);
#e()表示实数转义函数# 我也试着把身份证放进去,但什么也没放。。谁能解决这个问题

<?php

  # Starting session. #
    session_start();
  # Starting session. #

  # Connection to database. #
    $db = mysqli_connect('127.0.0.1:3305', 'root', '', 'assignmentnews');
  # Connection to database. #

  # Let's declare some variables. #
    $username = "";
    $errors = array();
  # Let's declare some variables. #

  # Call the register() function if register_btn is clicked. #
    if(isset($_POST['register_btn']))
    {
      register();
    }
  # Call the register() function if register_btn is clicked. #

  # Register function. #
    function register()
    {
      # Let's use here 'global' keyword to make these declared variables available outside function. #
        global $db, $errors, $username;
      # Let's use here 'global' keyword to make these declared variables available outside function. #

      # Recieve all input values from the form. Let's call e() / escape string function. #
        $username = e($_POST['username']);
        $password_01 = e($_POST['pwd']);
        $password_02 = e($_POST['pwd-confirmation']);
      # Recieve all input values from the form. Let's call e() / escape string function. #

      # Form validation. Let's make sure that form is correctly filled. #
        if(empty($username)) { array_push($errors, "Username is required."); }
        if(!preg_match("/^[a-zA-Z0-9]*$/", $username)) { array_push($errors, "Invalid characters in username field."); }
        if(empty($password_01)) { array_push($errors, "Password field can't be empty."); }
        if(empty($password_02)) { array_push($errors, "Re-entering password field can't be empty, either."); }
      # Form validation. Let's make sure that form is correctly filled. #

      # Let's register user if there are no errors inside form. #
        if(count($errors) == 0)
        {
          # Encrypt password before storing it inside database. #
            $password = md5($password_01);
          # Encrypt password before storing it inside database. #

          if(isset($_POST['usertype']))
          {
            $usertype = e($_POST['usertype']);
            $query = "INSERT INTO users (username, pwd, usertype) VALUES ('$username', '$password', '$usertype')";
            mysqli_query($db, $query);
            $_SESSION['success'] = "New user successfully created.";
            header("Location: ../registration/login.php");
          }
          else
          {
            $query = "INSERT INTO users (username, pwd, usertype) VALUES ('$username', '$password', 'user')";
            mysqli_query($db, $query);

            # Let's get ID of the created user. #
              $logged_in_user_ID = mysqli_insert_id($db);
            # Let's get ID of the created user. #

              # Let's put logged in user in session. #
                $_SESSION['user'] = getUserById($logged_in_user_ID);
                $_SESSION['success'] = "You are now logged in.";
                header("Location: ../user.php?loggedIn");
              # Let's put logged in user in session. #
          }
        }
      # Let's register user if there are no errors inside form. #
    }

    # Function for getting users ID. #
      function getUserById($id)
      {
        global $db;
        $query = "SELECT * FROM users WHERE id=" . $id;
        $result = mysqli_query($db, $query);
        $user = mysqli_fetch_assoc($result);
        return $user;
      }
    # Function for getting users ID. #

    # Escape string function. #
      function e($val)
      {
        global $db;
        return mysqli_real_escape_string($db, trim($val));
      }
    # Escape string function. #
  # Register function. #

  # Display error function. #
    function display_error()
    {
      global $errors;
      if(count($errors) > 0)
      {
        echo '<div class="error">';
          foreach($errors as $error)
          {
            echo $error . '<br>';
          }
          echo '</div>';
      }
    }
  # Display error function. #

  # Let's make an algorithm when person types url like: user.php into browser they are unable to access page if not logged in. #
    function isLoggedIn()
    {
      if(isset($_SESSION['user']))
      {
        return true;
      }
      else
      {
        return false;
      }
    }
  # Let's make an algorithm when person types url like: user.php into browser they are unable to access page if not logged in. #

  # Let's make an function if user click logout button, logout action happens. #
    if(isset($_GET['logout']))
    {
      session_destroy();
      unset($_SESSION['user']);
      header("Location: login.php");
    }
  # Let's make an function if user click logout button, logout action happens. #

  # Let's call the login() function if the login button is clicked. #
    if(isset($_POST['login_user']))
    {
      login();
    }

    function login()
    {
      # Let's use here 'global' keyword to make these declared variables available outside function. #
        global $db, $username, $errors;
      # Let's use here 'global' keyword to make these declared variables available outside function. #

      # Recieve all input values from the form. Let's call e() / escape string function. #
        $username = e($_POST['username']);
        $password = e($_POST['pwd']);
      # Recieve all input values from the form. Let's call e() / escape string function. #

      # Form validation. Let's make sure that form is correctly filled. #
        if(empty($username)) { array_push($errors, "Username field is required. It can't be empty."); }
        if(!preg_match("/^[a-zA-Z0-9]*$/", $username)) { array_push($errors, "Invalid characters in username field."); }
        if(empty($password)) { array_push($errors, "Password field is required. It can't be empty."); }
      # Form validation. Let's make sure that form is correctly filled. #

      # Let's attempt login if there are no errors on form. #
        if(count($errors) == 0)
        {
          $password = md5($password);
          $query = "SELECT * FROM users WHERE username='$username' AND pwd='$password'";
          $results = mysqli_query($db, $query);

          # User found. #
            if(mysqli_num_rows($results) == 1)
          # User found. #
          {
            # Let's check if person is admin or user. #
              $logged_in_user = mysqli_fetch_assoc($results);
              if($logged_in_user['usertype'] == 'admin')
              {
                $_SESSION['user'] = $logged_in_user;
                $_SESSION['success'] = "You are logged in as admin.";
                header("Location: ../admin.php");
              }
              else
              {
                $_SESSION['user'] = $logged_in_user;
                $_SESSION['success'] = "You are now logged in as user.";
                header("Location: ../user.php");
              }
            # Let's check if person is admin or user. #
          }
          else
          {
            array_push($errors, "Wrong username/password combination.");
          }
        }
      # Let's attempt login if there are no errors on form. #
    }
  # Let's call the login() function if the login button is clicked. #

  # Let's add isAdmin function. #
    function isAdmin()
    {
      if(isset($_SESSION['user']) && $_SESSION['user']['usertype'] == 'admin')
      {
        return true;
      }
      else
      {
        return false;
      }
    }
  # Let's add isAdmin function. #

  # Algorithm for saveChanges button-submit. #
    if(isset($_POST['saveChanges']))
    {
      saveChangesArticle();
    }
  # Algorithm for saveChanges button-submit. #

  # Save changes function. #
    function saveChangesArticle()
    {
      global $db, $errors;
      $headline = e($_POST['headline']);
      $storyline = e($_POST['storyText']);
      $authorUsername = e($_POST['authorUser']);
      $timestampDate = e($_POST['date']);

      if(empty($headline)) { array_push($errors, "Headline / Title field is required."); }
      if(empty($storyline)) { array_push($errors, "Storyline / Text field is required."); }
      if(empty($authorUsername)) { array_push($errors, "Author / Username field is required."); }
      if(empty($timestampDate)) { array_push($errors, "Date field is required."); }

      if(count($errors) == 0)
      {
        $query = "INSERT INTO newsmodule (headline, storyline, username, timestamp)
                                  VALUES ('$headline', '$storyline', '$authorUsername', '$timestampDate')";
        mysqli_query($db, $query);
        header("Location: admin.php?ArticleAddedSuccessfully");
        exit();
      }
      else
      {
        echo("Error: Creating article failed.");
      }
    }
  # Save changes function. #

  # Function for viewing news. #
    function viewNews()
    {
      global $db;
      $query = "SELECT * FROM newsmodule ORDER BY timestamp";
      $result = mysqli_query($db, $query);
      if (!$result)
      {
        echo "Error selecting headline from database.";
        exit();
      }
      if (mysqli_num_rows($result) > 0)
      {
        echo "<div style='margin-left: 0; width: 100%;' class='jumbotron'>";
        while ($row = mysqli_fetch_object($result))
        {
          echo "<h1><br>" . $row->headline . "</h1>";
          echo "<hr>";
          echo "<p>" . $row->storyline . "</p>";
          echo "<hr>";
          echo "<h5 class='pull-right'>" . $row->username . "</h5>";
          echo "<p>" . $row->timestamp . "</p>";
          echo "<hr>";
          echo showCommentArea($row->id);
          echo "<a data-target='#postComment' class='text-white dropdown-toggle btn btn-danger' data-toggle='modal' type='button'>";
          echo  "Publish a Comment";
          echo "</a>";
        }
        echo "</div>";
      }
      else
      {
        echo "No headlines in database.";
      }
    }
  # Function for inserting comments. #

    function addComment()
    {
      global $db, $errors, $username;
      $comment = $_POST['comment-text'];
      $username = $_POST['commenter-username'];
      $articlecID = $_POST['articlecID']; # Getting value from input name attr #
      if(count($errors) == 0)
      {
        $query = "INSERT INTO comments (comment, name, articlecID)
                  VALUES ('$comment', '$username', '$articlecID')";
        mysqli_query($db, $query);
        header("Location: ./admin.php?successMessage");
      }
    }
  # Function for inserting comments. #

  # Function for joining tables. #

  # Function for joining tables. #

  if(isset($_POST['saveChanges02'])){
    addComment();
  }

  # Post comment function. #
    function showCommentArea($id)
    {
      global $db, $errors, $username;
      if(count($errors) == 0)
      {
        $query = "SELECT comment, name FROM comments
                  INNER JOIN newsmodule ON comments.articlecID=newsmodule.id WHERE $id = newsmodule.id";
        $result = mysqli_query($db, $query);
        if(!$result)
        {
          echo "SQL Query ERROR: !ERR_SQL_QUERY_01";
          exit();
        }
        if (mysqli_num_rows($result) > 0) {
          echo "<div>";
          echo "<h4>";
          echo "Comments:";
          echo "</h4>";
          echo "<br>";
          while ($row = mysqli_fetch_object($result)) {
            echo "<p class='text-danger' style='font-weight: bold;'>" . $row->name . "</p>";
            echo "<p>" . $row->comment . "</p>";
          }
          echo "</div>";
        }
      }
    }
  # Post comment function. #

在空字段中,我试图从另一个表中放入一列,但什么也没有。 像这样:

$query = "INSERT INTO comments (comment, name, articlecID) VALUES ('$comment', '$username', 'newsmodule.id')";

$articlecID=
-那么您是如何尝试将其插入查询的?请向我们展示实际的代码,而不仅仅是缺少上下文的代码片段。顺便说一句:使用准备好的语句进行变量查询,请参阅。另外,不要使用
global
,而是使用参数。请将您的问题包含在您的完整源代码中,以供他人测试。详细解释问题所在。@04FS这是一个完整的代码,我没有把它放在一个文件中,因为它将整个系统放在一个文件中,我知道,这有时是错误的,但因为我是初学者,从来没有工作过,这对我来说是一种练习,没关系。@Progman我想要一个外键ID,而不是在查询中硬编码一个数字。好了吗?@ravenousHydra你必须用表单来显示HTML代码,因为这些表单定义了哪些值被发送到你的PHP脚本。这个查询有严重的安全问题,不应该使用,不应该使用预先准备好的语句或占位符。显然,这将由OP来清理,我给出了建议-不是完成的代码,但感谢您指出另一个明显的选择是使用PDO,但这不是他最初的脚本。。。
$query = "INSERT INTO comments (comment, name, articlecID) VALUES ('$comment', '$username', '')";
$query = "INSERT INTO comments (comment, name, articlecID) VALUES ('$comment', '$username', 'newsmodule.id')";
$query = "INSERT INTO comments (comment, name, articlecID) VALUES ('$comment', '$username', (SELECT id from newsmodule where ....))";