Jump to content

Problem inserting data from form to Database.


Arcadia

Recommended Posts

Hello everyone, I have a problem and really hope someone can help me out here ::)

 

I'm trying to insert data from a form in my MYSQL database and it connect to the database but when i try to submit the form i keep getting these two error messages:

 

Notice: Undefined index: Naam in /Applications/XAMPP/xamppfiles/htdocs/Oefentoets1/Vraag4_Invoer.php on line 18

Notice: Undefined index: Score in /Applications/XAMPP/xamppfiles/htdocs/Oefentoets1/Vraag4_Invoer.php on line 19

 

 

 

I have the form and php code in one page I hope this is not a problem.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Vraag4_Invoer</title>


<?php


// Connect to the database

$con = mysqli_connect("localhost","root","","Oefentoets1");

$naam = $_POST['Naam'];
$score = $_POST['Score'];

// Check connection
if (mysqli_connect_errno()) {

echo "Failed to connect to MySQL: " . mysqli_connect_error();

}



$sql = "INSERT INTO Scores (Naam, Score)
VALUES ('$naam', '$score')";


if ($con->query($sql) === TRUE) {
    echo "Thanks for signing up!";
} else {
    echo "Error: " . $sql . "<br>" . $con->error;
}



mysqli_close($con);


?>


</head>



<body>

<form action="Vraag4_Invoer.php" method="post"> 

<label>Naam:  </label><input name="Naam" type="text" />
<p>
<label>Score:  </label><input name="Score" type="text" />

<p>

<input name="Submit" type="submit" />

</form>



</body>
</html>

In your particular case with this code, it would be best to wrap the entire mysql connection (open to close) in an if() that checks if the form has been submitted yet.  At this time the page is trying to run the insert query as soon as the page loads, but the post vars don't exist yet cause you haven't submitted the form.

if(isset($_POST['Submit']))
{
// Connect to the database

$con = mysqli_connect("localhost","root","","Oefentoets1");

$naam = $_POST['Naam'];
$score = $_POST['Score'];

// Check connection
if (mysqli_connect_errno()) {

echo "Failed to connect to MySQL: " . mysqli_connect_error();

}



$sql = "INSERT INTO Scores (Naam, Score)
VALUES ('$naam', '$score')";


if ($con->query($sql) === TRUE) {
    echo "Thanks for signing up!";
} else {
    echo "Error: " . $sql . "<br>" . $con->error;
}



mysqli_close($con);
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.