0

I am trying to send a first name and last name to my database using a form, but when I try it does not actually send any values to FirstName and LastName, however it does add a new record as an ID is created.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Student Form</title>
</head>
<body>
<form action="insert.php" method="post">
    <p>
        <label for="FirstName">First Name:</label>
        <input type="text" name="FirstName" id="FirstName">
    </p>
    <p>
        <label for="lastName">Last Name:</label>
        <input type="text" name="LastName" id="LastName">
    </p>
    <input type="submit" value="Submit">
</form>
</body>
</html>

PHP (as a separate file called 'insert.php'):

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "INSERT INTO Students (FirstName, LastName) 
VALUES ('$FirstName', '$LastName')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

Any help would be greatly appreciated.

  • 1
    Your values haven't been set in the insert.php file. – Tony Hensler Oct 10 '16 at 21:57
  • Also a warning: your code is valuable to sql injection attacks. You want to start learning about the benefits of using "prepared statements" and "parameter binding". – arkascha Oct 10 '16 at 21:58

2 Answers2

0

u have to post values here e-g $FirstName=$_POST['FirstName']; $LastName=$_POST['LastName'];then run the insert query

Hassan Tahir
  • 134
  • 9
0

Change your PHP script to this:-

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "INSERT INTO Students (FirstName, LastName) 
VALUES ('$FirstName', '$LastName')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
Tony Hensler
  • 1,482
  • 5
  • 15
  • 30