I am trying to insert data from a HTML form and PHP script to a MySQL Database.
I am able to connect to the MySQL server from the script but I cannot connect to the Database and table. So that I cannot insert data.
The error that triggers from the PHP script. The error is : Database is not selected !. But I have declared the name correctly.
Here I have uploaded the
full solution .
Below I have added the HTML form and the PHP Script.
Could you please try to solve the issue if possible.
What I have tried:
HTML Form
<html>
<head>
<title>Registration Form</title>
</head>
<body>
<br>
<h2 align="center">Register a new customer</h2>
<h3 align="center">Fill all fields</h3>
<form action="insertdata.php" method="post">
<table align="center">
<tbody><tr>
<td>First Name:</td>
<td><input type="text" id="fname" name="fname" /></td>
</tr>
<tr>
<td>Middle Name:</td>
<td><input type="text" id="mname" name="mname" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" id="lname" name="lname" /></td>
</tr>
<tr>
<td>NIC / Driving License No:</td>
<td><input type="text" id="NICNo" name="nicno" /></td>
</tr>
<tr>
<td>Permanent Address Name:</td>
<td><input type="text" id="paddress" name="paddress" /></td>
</tr>
<tr>
<td>E-Mail Address:</td>
<td><input type="text" id="email" name="email" /></td>
</tr>
<tr>
<td>Telephone:</td>
<td><input type="text" id="telno" name="telno" /></td>
</tr>
<tr>
<td>Mobile No:</td>
<td><input type="text" id="mobileno" name="mobileno" /></td>
</tr>
<tr>
<td>Date of Registration:</td>
<td><input type="text" id="regdate" name="regdate" /></td>
</tr>
<tr><td></td></tr>
<tr><td></td></tr>
<tr><td></td></tr>
<tr><td></td></tr>
<tr><td></td></tr>
<tr><td></td></tr>
<tr>
<td align="center"><input type="submit" /> <input type="reset" /></td>
</tr>
</tbody></table>
</form>
</body>
InsertData.php
<?php
$dbserver = 'localhost';
$username = 'root';
$password = '';
$dbname = 'car_rental';
$con = mysqli_connect($dbserver, $username, $password);
if(!$con)
{
echo "Not connected to server !";
}else{
echo "Server connected !";
}
if(!mysqli_select_db($con, $dbname));
{
echo "Database not selected !";
}
$fname = $_POST["fname"];
$mname = $_POST["mname"];
$lname = $_POST["lname"];
$nicno = $_POST["nicno"];
$paddress = $_POST["paddress"];
$email = $_POST["email"];
$telno = $_POST["telno"];
$mobileno = $_POST["mobileno"];
$regdate = $_POST["regdate"];
$sql = "INSERT INTO new_customers (FirstName, MiddleName, LastName, NICNo, PermanentAddress, EmailAddress, Telephone, Mobile, RegDate) VALUES ('$fname','$mname','$lname','$nicno','$paddress','$email','$telno','$mobileno','$regdate')";
if (!mysqli_query($con,$sql))
{
echo "Data not inserted !";
}
else
{
echo "Data inserted !";
}
header("refresh:300; url=form.php");
?>
Thanks!