I can read from database, but when I insert data to database, It said "Successfully Registered!", then I check my database , it didn't insert any data.
Register.php
<!DOCTYPE HTML>
<html>
<head>
<title>Register page</title>
<br>
<font size="5" color="black"><b> Register Page<br><br></b></font>
</head>
<body background=" images/background.jpg">
<form action="index.php">
<input type="submit" value="Home">
</form>
<br>
<form action="Register.php" method="POST">
<fieldset>
<legend>Enter your information</legend>
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="username" required="required"/><br></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="text" name="password" required="required"/><br></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" name="email" required="required"/><br></td>
</tr>
<tr>
<td>First Name:</td>
<td><input type="text" name="firstname" required="required"/><br></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" name="lastname" required="required"/><br></td>
</tr>
<tr>
<td>Date of Birth:</td>
<td><input type="date" name="dateofbirth" required="required" ><br></td>
</tr>
<tr>
<td><input type="submit" value="Register"/></td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = mysql_real_escape_string($_POST['email']);
$dateofbirth= $_POST['dateofbirth'];
echo "user is :".$username;
$bool = true;
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("userdata") or die(mysql_error("Cannot Connect to Database"));
$query = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($query))
{
$table_users = $row['username'];
if($username == $table_users)
{
$bool = false;
Print '<script>alert("username is used!");</script>';
Print '<script>window.location.assign("Register.php");</script>';
}
}
if($bool)
{
mysql_query("INSERT INTO users ('username','password','email','firstname','lastname','dateofbirth') VALUES ('$username','$password','$email','$firstname','$lastname','$dateofbirth')");
Print '<script>alert("Successfully Registered!");</script>';
Print '<script>window.location.assign("Register.php");</script>';
}
}
?>
SOLVED: I used PDO instead of mysql_ and mysqli_ .
'username'(and you don't actually need to encapsulate column names, and should use backticks anyway) in the insertion query. You're not checking if the insertion was successful. You're using deprecated mysql_ functions instead of mysqli_mysql_queryis actually returning rather than just assuming it was successful. That isn't the cause of your failed insert, but would help with troubleshooting and give you an opportunity to trap the error and report on the problem rather than just silently discarding data.