I can't add data in my database using php [clo

2019-09-21 22:53发布

I have index.html to post data in send.php the send.php code is the form data is named correctly & no error on send page

<?php
$servername = "localhost";
$username = "Blah Blah";
$password = "Blah Blah";
$dbname = "Blah Blah";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$name = $_POST['name'];
$famil = $_POST['famil'];
$email = $_POST['email'];
$amount = $_POST['amount'];

$sql = "INSERT INTO users".
"(name, famil, email, amount)".
"VALUES ('$name','$famil','$email','$amount')";

mysqli_close($conn);

but query can't insert the data into db!

why the post method won't work here?

1条回答
唯我独甜
2楼-- · 2019-09-21 23:09

The problem is that you're not querying - mysqli_query() is missing which is the essential part.

Your current code is indeed valid, yet SQL failed silently because of the missing mysqli_query().

$sql = mysqli_query($conn,"INSERT INTO users".
"(name, famil, email, amount)".
"VALUES ('$name','$famil','$email','$amount')");

Make sure that your form elements are named also and that your form is a POST method. (An insight)

I.e.: name="name", name="famil" etc. and <form method="post" action="handler.php">


Add error reporting to the top of your file(s) which will help find errors.

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

Sidenote: Error reporting should only be done in staging, and never production.

You can also use or die(mysqli_error($conn)) to mysqli_query()


"no error on send page"

  • You should always check for possible errors.

For added protection with your existing code, use:

$name = stripslashes($_POST['name']);
$name = mysqli_real_escape_string($conn, $_POST['name']);
  • and do the same for the others.

Doing this would also work:

$sql = "INSERT INTO users".
"(name, famil, email, amount)".
"VALUES ('$name','$famil','$email','$amount')";

mysqli_query($conn,$sql);

or

if (mysqli_query($conn, $sql)) {
    echo "Data entered successfully.";
} else {
    echo "Error entering data: " . mysqli_error($conn);
}
  • So as you can see, you have a few ways of querying.
查看更多
登录 后发表回答