需要帮助一些无效的代码[关闭]

if ($_SERVER['REQUEST_METHOD'] == 'POST'){
    $follow = strip_tags($_POST["follow"]);
    $follow = addslashes($follow);
    $follow = mysqli_real_escape_string($conn, $follow);
    $sesid = $_SESSION["id"];
    $rowid = $row['id'];
    $followers = $conn->query("INSERT INTO followers (forid, fromid) VALUES ('$rowid', '$sesid'");
    echo "<h3><center>Sucessfully followed!</center></h3>";
}

It doesn't seem to work. It doesn't throw any errors. I'm a new(er) PHP developer. Thank you!

STOP this madness... Do not insert values into a query, that's how bad things happen.

Also, add some error checking here and there, it's impossible to know what's wrong with the piece of code (or is it?):

Try something more like this:

$conn = new mysqli('localhost', 'root', 'password', 'db_name');
if ($conn->connect_errno) {
  throw new Exception('Connection Error' . $conn->connect_err);
}

Now let's deal with the post data:

if(isset($_POST)) {
  $follow = $_POST["follow"];
  $sesid = $_SESSION["id"];
  $rowid = $row['id']; // don't know where this is coming from

  if($stmt = $conn->prepare("INSERT INTO followers (forid, fromid) VALUES (?, ?)") {
    $stmt->bind_param('si', $follow, $sesid);
    if(!$stmt->execute()) {
      throw new Exception('Error! Could not execute query.');
    }

    $stmt->close();
  } else {
    throw new Exception('Could not prepare query!');
  }
} else {
  // Add a error checking here
  throw new Exception('No post data');
}

Prepared statements will help you avoid anyone trying to insert undesired content into your query (SQL injection).

The way it works,

  1. Prepare the query ($conn->prepare())
    • Note here that there are simple ? where the values would otherwise be. That's for our next step.
  2. Bind the parameters of your query with $stmt->bind_param(). This will tell PHP where each value should go, starting at the second parameter position.
    • The documentation for the bind_param function: bool mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] )
    • A little explanation for the first param:
      • s - stands for string (the $follow, I assume is a string)
      • i - stands for integer. The session ID
  3. Then, finally, execute the query ($stmt->execute()). That will do the hard work of adding the values to your database.
  4. Explicitly close the connection to your database ($conn->close());

Read more on PHP's official documentation.