So I made this registration form but it won't send the data to my database, it works sometimes and sometimes it doesn't, it is really weird. here is the code.
<?php
error_reporting(E_ALL);
define('DB_HOST', 'localhost');
define('DB_NAME', 'Users');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db = mysql_select_db('Users', $con) or die("Failed to connect to MySQL: " . mysql_error());
function NewUser()
{
$firstname = $_POST['firstname'];
$efternamn = $_POST['efternamn'];
$email = $_POST['email'];
$password = $_POST['password'];
$query = "INSERT INTO WebsiteUsers (firstname,efternamn,email,password) VALUES ('$firstname','$efternamn','$email','$password')";
$data = mysql_query($query) or die(mysql_error());
if ($data) {
echo "YOUR REGISTRATIOfafa";
}
}
function SignUp()
{
if (!empty($_POST['email'])) {
$query = mysql_query("SELECT * FROM Websiteusers WHERE email = '$_POST[email]' ") or die(mysql_error());
if (!$row = mysql_fetch_array($query) or die(mysql_error())) {
NewUser();
} else {
echo "SORRY...YOU ARE ALREADY REGISTERED USER...";
}
}
}
if (isset($_POST['submit'])) {
SignUp();
}
<!DOCTYPE HTML>
<html>
<head>
<title>Registrera Dig</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<table style=" position:absolute; left:550; top:200;">
<form method="POST" action="signup.php">
<tr> <p style=" position:absolute; left:555; top:163;" >Namn</p><td> <input type="text" name="firstname"></td>
</tr>
<tr> <td>Efternamn</td><td> <input type="text" name="efternamn"></td> </tr>
<tr> <td>Email</td><td> <input type="text" name="email"></td></tr>
<tr> <td>Lösenord</td><td> <input type="password" name="password"></td> </tr>
<tr> <td>Bekräfta lösenord </td>
<td><input type="password" name="cpass"></td> </tr>
<tr> <td><input id="button" type="submit" name="submit" value="Skapa konto"></td> </tr>
</form>
</table>
</body>
</html>
What am I doing wrong here?
Update
So everytime I empty my table I am able to register again. but I can only register 1 time
Your code has so many problems, I just re-created it for you using best practices. Where you went wrong was the following:
1.Using MySQL (A depreciated class)
2.Vulnerable to SQL injection
3.You don't need functions, it's just as clean if you don't have them. You're only calling the code once.
4.Inserting $_POST[email] is not a good idea and probably won't work.
5.Fixed multiple other problems such as tags
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'Users');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); //Use MySQLi as MySQL is depreciated.
if (isset($_POST['submit'])) {
//No need for functions, do it all here as otherwise you'll have to declare globals.
if (!empty($_POST['email'])) {
$query = mysqli_prepare($con, "SELECT * FROM Websiteusers WHERE email = ?"); //Preparing the SQL query (We don't insert values directly into the query)
mysqli_stmt_bind_param($query, "s", $_POST['email']); //Bind the email to the SQL query
mysqli_stmt_execute($query); //Execute the query
mysqli_stmt_store_result($query); //Store the results
if(mysqli_stmt_num_rows($query) != 0) //Is the number of rows 0?
{
//rows
echo "SORRY...YOU ARE ALREADY REGISTERED USER...";
}
else
{
//No Rows
$query = mysqli_prepare($con, "INSERT INTO WebsiteUsers (firstname,efternamn,email,password) VALUES (?, ?, ?, ?)"); //Preparing the SQL query (We don't insert values directly into the query)
mysqli_stmt_bind_param($query, "ssss", $_POST['firstname'], $_POST['efternamn'], $_POST['email'], $_POST['password']); //Bind the params to the SQL query
mysqli_stmt_execute($query); //Execute the query
echo "YOUR REGISTRATIOfafa";
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Registrera Dig</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<table style=" position:absolute; left:550; top:200;">
<form method="POST" action="signup.php">
<tr> <p style=" position:absolute; left:555; top:163;" >Namn</p><td> <input type="text" name="firstname"></td> </tr>
<tr> <td>Efternamn</td><td> <input type="text" name="efternamn"></td> </tr>
<tr> <td>Email</td><td> <input type="text" name="email"></td></tr>
<tr> <td>Lösenord</td><td> <input type="password" name="password"></td> </tr>
<tr> <td>Bekräfta lösenord </td>
<td><input type="password" name="cpass"></td> </tr>
<tr> <td><input id="button" type="submit" name="submit" value="Skapa konto"></td> </tr>
</form>
</table>
</body>
</html>
i would simplify your code and remove conditions. Shorter code will make it easier to debug and then check line by line what's happening.
A blank screen is weird unless it's something to do with the way you've set up error handling? Do u get any other warnings of something basic goes wrong? To test maybe you should try writing a line of code that definitely gets an error such as including a file that doesn't exist? Do you then get an error ? If not, it's something to do with the way you've configured your error reporting ... This doesn't solve the problem, but will bring you a step closer as when u actually get the error displayed you'll find out why the DB is not registering your form data.
Related
When I run this code it all goes fine. It gives me the message "New record inserted succesfully". The problem that I have is whenever I go to my databse to check it out. It's still empty, the information that I typed into the input boxes don't appear in my database. Just a blank database. I'm new to coding so please bear with me if I misused some words or don't quite understand my mistakes.
<!DOCTYPE HTML>
<html>
<head>
<title>Sign Up Form</title>
<meta charset="utf-8">
<link rel="stylesheet" href="SignUp.css" type="text/css">
</head>
<body>
<form action="insert.php" method="POST">
<table>
<tr>
<td style="color:white">Username :</td>
<td><input type="text" name="Username" required></td>
</tr>
<tr>
<td style="color:white">voornaam :</td>
<td><input type="text" name="Voornaam" required></td>
</tr>
<tr>
<td style="color:white">Achternaam :</td>
<td><input type="text" name="Achternaam" required></td>
</tr>
<tr>
<td style="color:white">Wachtwoord :</td>
<td><input type="password" name="Wachtwoord" required></td>
</tr>
<tr>
<td style="color:white">Adres :</td>
<td><input type="text" name="Adress" required></td>
</tr>
<tr>
<td style="color:white">Telefoon nummer :</td>
<td>
<select name="Telcode" required>
<option selected hidden value="">Select Code</option>
<option value="297">297</option>
</select>
<input type="phone" name="Telnummer" required>
</td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
<?php
$Voornaam = $_POST['Voornaam'];
$Username = $_POST['Username'];
$Achternaam = $_POST['Achternaam'];
$Wachtwoord = $_POST['Wachtwoord'];
$Adress = $_POST['Adress'];
$Telcode = $_POST['Telcode'];
$Telnummer = $_POST['Telnummer'];
if (!empty($Voornaam) || !empty($Achternaam) || !empty($Wachtwoord) || !empty($Adress) || !empty($Telcode) || !empty($Telnummer) || !empty($Username))
{
$host = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbname = "gevuldetomaat";
$conn = new mysqli($host, $dbUsername, $dbPassword, $dbname);
if ($conn->connect_error) {
die("Connection failed: ". $conn->connect_error);
} else {
$SELECT = "SELECT Username From klant Where Username = ? Limit 1";
$INSERT = "INSERT INTO klant (Wachtwoord, Achternaam, Voornaam, Telnummer, Telcode, Username, Adress) values(?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($SELECT);
$stmt->bind_param("s", $Username);
$stmt->execute();
$stmt->bind_result($Username);
$stmt->store_result();
$rnum = $stmt->num_rows;
if ($rnum==0)
{
$stmt->close();
$stmt = $conn->prepare($INSERT);
$stmt->bind_param("sssiiss", $Wachtwoord, $Achternaam, $Voornaam, $Telnummer, $Telcode, $Username, $Adress);
$stmt->execute();
echo "New record inserted sucessfully";
}
else {
echo "Someone already registered using this name";
}
$stmt->close();
$conn->close();
}
}
else {
echo "All fields are required";
die();
}
?>
It seems like you do run into that fork where the INSERT SQL runs, but you print the success message without checking whether it indeed was successfully inserted or not
After each mysqli_stmt::execute(), you should consider checking the mysqli_stmt::$errno variable to see if there was an error or not ($errno is short for "error number", if it's zero, there were no errors)
Something like this should tell you more about the error that happens:
if ($rnum == 0) {
$stmt->close();
$stmt = $conn->prepare($INSERT);
$stmt->bind_param("sssiiss", $Wachtwoord, $Achternaam, $Voornaam, $Telnummer, $Telcode, $Username, $Adress);
$stmt->execute(); // Run the INSERT statement
if ($stmt->errno) { // Check for errors
die("Error in inserting: " . $stmt->error); // Print last error
} else { // No errors
echo "New record inserted sucessfully"; // Success message
}
} else {
echo "Someone already registered using this name";
}
I did this only for the INSERT statement here, but you should consider doing something like this for the SELECT statement too
Currently, the echo "New record inserted sucessfully"; line will return even if the query failed, as there is no check to see if the query was actually successful, hence why it's returning that value.
In order to check if there was an error, you need to add $stmt->error. There is most likely an error occurring in the Database when trying to insert data. Most likely, from what I can tell,the error is in the Telnumber and Telcodeas they are being treated as integers instead of strings in your prepared statement. Telephone numbers should be treated as strings as you are not performing any kind of math on the numbers, and they can sometimes be formatted to allow things such as dashes, spaces, parentheses, etc.
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 5 years ago.
<?php
session_start();
$host="localhost";
$username="root";
$password="";
$db_name="registrering";
$tbl_name="users";
$conn = mysqli_connect($host, $username, $password, $db_name);
if(!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
<html>
<head>
<title>user registration system using php and PHP and Mysq</title>
<!---<link rel="stylesheet" type="text/css" href="style.css">-->
</head>
<body>
<div style="float:right; width:70%">
<table width="150px" border="0" cellpadding="3" cellspacing="1">
<h2>Registrer<h2/>
<form method="post" action=" ">
<br>
<tr>
<td>Brugernavn</td>
<td>:</td>
<td><input type="text" name="Brugernavn"> </td>
</tr>
<br>
<tr>
<td>Email</td>
<td>:</td>
<td><input type="text" name="Email"> </td>
</tr>
<br>
<tr>
<td>Password</td>
<td>:</td>
<td><input type="password" name="Password"></td>
</tr>
<input type="submit" name="registrer" value="Registrer">
<p>
Allerede medlem? Log ind
</p>
</form>
</div>
</table>
</body>
</html>
<?php
if (isset($_POST["registrer"]))
{
$my_username=$_POST["Brugernavn"];
$my_email=$_POST["Email"];
$my_password=$_POST["Password"];
$sql = "INSERT INTO 'users'(`username`, `email`, `password`) VALUES ('$my_username','$my_email','$my_password')";
$resultat = mysqli_query($conn, $sql);
}
?>
It needs to connect to a database, but it doesn't. It's on a localhost and we can't insert data into a database. The database consists of a username, email and password.
We are using varchar(65) and utf8_general_ci.
Assuming the connection is working - the insert should have back ticks around the user name, not normal quotes.
$sql = "INSERT INTO `users`(`username`, `email`, `password`) VALUES ('$my_username','$my_email','$my_password')";
I would also recommend looking into prepared statements and bind parameters, not forgetting to NOT store passwords as plane text.
Just a tip. Try using die() to print out the mysql error every time you run a mysql query. Hope it will save you a lot of effort and time in the debugging process. Also use back-ticks users near insert statement.
I want to add an email verification link that should be sent when a new user registers, he has to go in and press the link and then will his account be activated. How can I do that in the best and easiest way? Here is my code
<?php
error_reporting(E_ALL);
define('DB_HOST', 'localhost');
define('DB_NAME', 'Users');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); //Use MySQLi as MySQL is depreciated.
if (isset($_POST['submit'])) {
{
$error=false;
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format";
$error=true;
}
}
{
if ($_POST['password'] !== $_POST['cpass']) {
echo "Password and confirm password fields do not match!";
$error=true;
}
}
//No need for functions, do it all here as otherwise you'll have to declare globals.
if (!$error) {
$query = mysqli_prepare($con, "SELECT * FROM Websiteusers WHERE email = ?"); //Preparing the SQL query (We don't insert values directly into the query)
mysqli_stmt_bind_param($query, "s", $_POST['email']); //Bind the email to the SQL query
mysqli_stmt_execute($query); //Execute the query
mysqli_stmt_store_result($query); //Store the results
if(mysqli_stmt_num_rows($query)) //Is the number of rows 0?
{
//Yes
echo "Det verkar som att du redan är registrerad";
}
else
{
//No
$query = mysqli_prepare($con, "INSERT INTO WebsiteUsers (firstname,efternamn,email,password) VALUES (?, ?, ?, ?)"); //Preparing the SQL query (We don't insert values directly into the query)
mysqli_stmt_bind_param($query, "ssss", $_POST['firstname'], $_POST['efternamn'], $_POST['email'], $_POST['password']); //Bind the params to the SQL query
mysqli_stmt_execute($query); //Execute the query
echo "Din registrering är slutförd";
}
}
}
?>
<!DOCTYPE HTML>
<html lang="sv">
<head>
<title>Registrera Dig</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<table>
<form method="POST" action="test.php">
<img class="bild">
<tr> <td class="ett">Namn</td><tr><td> <input class="två" name="firstname"></td> </tr></tr>
<tr> <td class="tre">Efternamn</td><tr><td> <input class="fyra"type="text" name="efternamn"></td></tr> </tr>
<tr> <td class="fem">Email</td><tr><td> <input class="sex"type="email" name="email"></td></tr></tr>
<tr> <td class="sju">Lösenord</td><tr><td> <input class="åtta"type="password" name="password"></td> </tr></tr>
<tr> <td class="nio" >Bekräfta lösenord </td> <tr><td><input class="tio" type="password" name="cpass"></td></tr> </tr>
<tr> <td><input class="skapa" id="button" type="submit" name="submit" value="Skapa konto"></td> </tr>
</form>
</table>
</body>
</html>
I've done somthing like this...
$chk = md5(strtolower($_POST['email']));
Then I put that $chk value in the database, along with the the email address and other user info, and in the email I send, I have a link.. something like
<?php echo 'http://mysite/verify.php?chk='.$chk ; ?>
Now when verify.php is viewed it just needs to find a row for an un-activated user with the identical $chk value, and activate it when found.
$mysqlqry = 'UPDATE user.table set active = 1 WHERE active=0 AND chk='.$_REQUEST['chk'] ;
Hopefully that gets you started.
I have a issue with my login form. I'm trying to login with PHP and MySQLi but for some reason every time I press the login button. The fields within the form reset to blank fields. This is my code index.php
<html>
<head>
<title>User Login</title>
</head>
<body>
<form action="" method="post">
<table width="500" align="center" bgcolor="skyblue">
<tr align="center">
<td colspan="3"><h2>User Login</h2></td>
</tr>
<tr>
<td align="right"><b>Email</b></td>
<td><input type="text" name="email" required="required"/></td>
</tr>
<tr>
<td align="right"><b>Password:</b></td>
<td><input type="password" name="pass" required="required"></td>
</tr>
<tr align="center">
<td colspan="3">
<input type="submit" name="login" value="Login">
</td>
</tr>
</table>
</form>
</body>
</html>
<?php
session_start();
$con = mysqli_connect("localhost","root","usbw","login");
if (mysqli_connect_errno())
{
echo "MySQLi Connection was not established:" . mysqli_connect_error();
}
// checking the user
if(isset($_POST['login'])){
$email = mysqli_real_escape_string($con,$_POST['email']);
$pass = mysqli_real_escape_string($con,$_POST['pass']);
$sel_user = "SELECT * FROM users WHERE user_email='".$email."' AND user_pass='".$pass."'";
echo $sel_user;
$run_user = mysqli_query($con, $sel_user);
$check_user = mysqli_num_rows($run_user);
echo $check_user;
if($check_user == 1){
$_SESSION['user_email']=$email;
header('Location: loggedin.html'); }
else { header('Location: index.html'); }
}
?>
I hope someone can help me to fix this issue because I really need to build a login form for my website
There's a few things I'd like to point out about your code, but the primary issue you've been having all along is that you are sending headers before you are calling the session_start(); and header("Location: ..); functions. This causes "Headers already sent" warnings, and will not break your script, but it won't function properly. You should read How to fix "Headers already sent" error in PHP.
The code below has been altered some as well, I've made a few changes to it that you really should include
Using prepared statements, to protect your database against SQL injection (see How can I prevent SQL injection in PHP?) (never, never, never, never ever trust user-input!)
Using exit after calling a header("Location .."); function (see php - Should I call exit() after calling Location: header?)
The altered code is given below, and should be placed above ANY kind of HTML.
<?php
session_start();
$con = mysqli_connect("localhost","root","usbw","login");
if (mysqli_connect_errno()) {
echo "MySQLi Connection was not established:" . mysqli_connect_error();
}
if (isset($_POST['login'])) {
$email = mysqli_real_escape_string($con, $_POST['email']);
$pass = mysqli_real_escape_string($con, $_POST['pass']);
$sql = "SELECT user_email FROM users WHERE user_email=? AND user_pass=?";
if ($stmt = $mysqli_prepare($sql)) {
mysqli_stmt_bind_param($stmt, "ss", $email, $pass);
mysqli_stmt_store_result($stmt);
// Checking if the user was valid
if (mysqli_stmt_num_rows($stmt) > 0){
$_SESSION['user_email'] = $email;
header('Location: loggedin.html');
exit;
} else {
header('Location: index.html');
exit;
}
}
}
?>
<!-- HTML form goes here, nothing(!) before this PHP -->
What you really should do is to hash your passwords - from the looks of it, your passwords are stored in clean text in the database, this is a BIG no-no!
You should use password_hash() and password_verify() for that. It's really important to protect your user should your database be breached.
To troubleshoot further, you should enable error-reporting:
error_reporting(E_ALL);
mysqli_error
mysqli_stmt_error
When you have enabled this, PHP will tell you what's wrong if you just check your logs.
dude try this
<html>
<head>
<title>User Login</title>
</head>
<body>
<form action="" method="post">
<table width="500" align="center" bgcolor="skyblue">
<tr align="center">
<td colspan="3"><h2>User Login</h2></td>
</tr>
<tr>
<td align="right"><b>Email</b></td>
<td><input type="text" name="email" required="required"/></td>
</tr>
<tr>
<td align="right"><b>Password:</b></td>
<td><input type="password" name="pass" required="required"></td>
</tr>
<tr align="center">
<td colspan="3">
<input type="submit" name="login" value="Login">
</td>
</tr>
</table>
</form>
</body>
</html>
<?php
session_start();
$con = mysqli_connect("localhost","root","usbw","users");
if (mysqli_connect_errno())
{
echo "MySQLi Connection was not established:" . mysqli_connect_error();
}
// checking the user
if(isset($_POST['login'])){
$email = mysqli_real_escape_string($con,$_POST['email']);
$pass = mysqli_real_escape_string($con,$_POST['pass']);
$sel_user = "SELECT * FROM users WHERE user_email='".$email."' AND user_pass='".$pass."'";
$run_user = mysqli_query($con, $sel_user);
$check_user = mysqli_num_rows($run_user);
if($check_user == 1){
$_SESSION['user_email']=$email;
header('Location: loggedin.html');
}
else {
header('Location: index.html');
}
}
?>
I successfully added a column into a table in MySQL when I insert data via a PHP form, the email and the password are added successfully but not the username.
When I display the table the "Usernames" tables remains blank.
Here is the PHP form:
<html>
<head>
<title>Register</title>
</head>
<body>
<?php
if(isset($_POST['add']))
{
$dbhost = 'localhost:3036';
$dbuser = 'xxxx';
$dbpass = 'xxxxxxx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() )
{
$email = addslashes ($_POST['email']);
$password = addslashes ($_POST['password']);
$usernames = addslashes ($_POST['usernames']);
}
else
{
$email = $_POST['email'];
$password = $_POST['password'];
$usernames = $POST['usernames'];
}
$sql = "INSERT INTO users (email,usernames,password) VALUES ('$email', '$usernames', ENCRYPT('$password'))";
mysql_select_db('dbname');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">Your Email #foo.com</td>
<td><input name="email" type="text" id="email"></td>
</tr>
<tr>
<td width="100">Your Username</td>
<td><input name="usernames" type="text" id="usernames"></td>
</tr>
<tr>
<td width="100">Your Password</td>
<td><input name="password" type="password" id="password"></td>
</tr>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="add" type="submit" id="add" value="Register">
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>
I added the column for usernames using the command line:
ALTER TABLE tbname ADD usernames VARCHAR(55) NOT NULL;
It was added but when a user registers, his username is not showing. Only the email and the encrypted password are added.
Any help would be greatly appreciated.
Change this line
$usernames = $POST['usernames'];
Change it to
$usernames = $_POST['usernames'];
First of all don't use mysql, use mysqli/pdo. Turn off magic quotes and if you stick with mysql (don't) switch addslashes() to mysql_real_escape_string().
And you're having:
$usernames = $POST['usernames'];
Missing _:
$usernames = $_POST['usernames'];
But your database schema (namely NOT NULL) should take care of not having empty data, so also make sure that your select is correct.
Don't use the mysql_* functions and at least escape all user input....
change
$usernames = $POST['usernames'];
to
$usernames = $_POST['usernames'];
When developing enable display_errors so you can easily spot this error:
error_reporting(E_ALL);