How would I be able to insert data to a database using a textbox in a form

Basically I have created a form with several text boxes First Name, Surname, Username and Password. The form also contains a Submit Button.

And a database the contains the fields user_id (Primary key) (Auto-Increment), firstname, surname, username, password.

Ok I what need to know is how I would be able to insert the data typed into the text boxes into my database using PHP, with the data going into the correct fields when the submit button is clicked. And the user_id being able to Auto-Increment itself.

Please any help would be greatly appreciated thankyou so much for you time :slight_smile:

UPDATED!!! I found an error in my send.php and I corrected it.

Ok, here is a sample form.


<!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=iso-8859-1" />
<title>Untitled Document</title>
</head>

<body>
<form action="send.php" method="post">
<p>First Name:<br /><input type="text" name="fname" /></p>
<p>Surname:<br /><input type="text" name="sname" /></p>
<p>Username:<br /><input type="text" name="uname" /></p>
<p>Password:<br /><input type="password" name="pword1" /></p>
<p>Verify Password:<br /><input type="password" name="pword2" /></p>
<p><input type="submit" name="submitForm" value=" Submit " /></p>
</form>
</body>
</html>

Here is the send.php which will handle input from the form.


<?php

if ($_POST['formSubmit']) {
	
	if ($_POST['pword1'] !== $POST['pword2'] || empty($_POST['pword1'])) {
		echo 'Your passwords do not match Or you did not enter a password. Please enter again';
	} elseif (!empty($_POST['fname']) && !empty($_POST['sname']) && !empty($_POST['uname'])) {
		$conn = mysql_connect("localhost","username","password");
		mysql_select_db("databaseName",$conn);
		$exists = mysql_query("SELECT username FROM userTable WHERE username='$_POST[uname]'",$conn);
		
		if ($exists !== 0) {
			echo 'That username already exists in the database. Please choose another one.';
		} else {
			$sql = "INSERT INTO userTable (user_id,firstname,surname,username,password) VALUES ('','$_POST[fname]','$_POST[sname]','$_POST[uname]','$_POST[pword1]')";
			$query = mysql_query($sql,$conn) or die(mysql_error("Could not write information to the database"));
			
			if (mysql_affected_rows($conn) == 0) {
				echo 'Your account was not created.';
			} else {
				echo 'Your account was created successfully';
			}
		}	
	}
}

?>

You will need to modify some things in the send.php. Replace localhost (if you are not using local database) with the correct name, username and password with your login information for the database. Replace the databaseName with the name of the datebase you are using. Also replace the userTable with the table that you created to store this info.

This script will do the following:

  1. Make sure a password was entered and make sure the passwords match.
  2. Make sure all items are entered in the form.
  3. Make sure the username does not already exist in the database

Thanx alot mate I will give it a try thank you mate appreciate it alot :slight_smile:

Ok, here it goes again. I have tested this to work. Only made changes to send.php


<?php

if ($_POST['submitForm']) {
	
	if (!$_POST['pword1'] !== $_POST['pword2'] || empty($_POST['pword1'])) {
		echo 'Your passwords do not match Or you did not enter a password. Please enter again';
	} elseif (!empty($_POST['fname']) && !empty($_POST['sname']) && !empty($_POST['uname'])) {
		$conn = mysql_connect("localhost","username","password") or die("Could not connect to database");
		mysql_select_db("databaseName",$conn) or die("Could not select the database");
		$res = mysql_query("SELECT username FROM userTable WHERE username='$_POST[uname]'",$conn) or die("Query Failed");
		$exists = mysql_num_rows($res);
				
		if ($exists !== 0) {
			echo 'That username already exists in the database. Please choose another one.';
		} else {
			$sql = "INSERT INTO userTable (user_id,firstname,surname,username,password) VALUES ('','$_POST[fname]','$_POST[sname]','$_POST[uname]','$_POST[pword1]')";
			$query = mysql_query($sql,$conn) or die(mysql_error("Could not write information to the database"));
			
			if (mysql_affected_rows($conn) == 0) {
				echo 'Your account was not created.';
			} else {
				echo 'Your account was created successfully';
			}
		}	
	}
}

?>

thanx alot mate appreciate it alot hey mate can I ask does this allow the table that I insert the data to allow the user_id field to Auto-Increment? and plus do I insert the PHP code directly under the Form with the text boxes I have created or do I create a new .php file and put the code there, because just need to know how they gonna link together I see the $_POST[‘submitForm’] coz that links to the Submit Button but how does it know which form it’s taking the data from? Just wanna know to understand it properly mate

Thank you so much mate

Yes, if that field is set for Primary Key and auto_increment it does. You can just put the HTML underneath this code in the .php file and this will do it. So for example it would be:


<?php

if ($_POST['submitForm']) {

    if (!$_POST['pword1'] !== $_POST['pword2'] || empty($_POST['pword1'])) {
        echo 'Your passwords do not match Or you did not enter a password. Please enter again';
    } elseif (!empty($_POST['fname']) && !empty($_POST['sname']) && !empty($_POST['uname'])) {
        $conn = mysql_connect("localhost","username","password") or die("Could not connect to database");
        mysql_select_db("databaseName",$conn) or die("Could not select the database");
        $res = mysql_query("SELECT username FROM userTable WHERE username='$_POST[uname]'",$conn) or die("Query Failed");
        $exists = mysql_num_rows($res);

        if ($exists !== 0) {
            echo 'That username already exists in the database. Please choose another one.';
        } else {
            $sql = "INSERT INTO userTable (user_id,firstname,surname,username,password) VALUES ('','$_POST[fname]','$_POST[sname]','$_POST[uname]','$_POST[pword1]')";
            $query = mysql_query($sql,$conn) or die(mysql_error("Could not write information to the database"));

            if (mysql_affected_rows($conn) == 0) {
                echo 'Your account was not created.';
            } else {
                echo 'Your account was created successfully';
            }
        }
    }
}

?>
<!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=iso-8859-1" />
<title>Untitled Document</title>
</head>

<body>
<form action="send.php" method="post">
<p>First Name:<br /><input type="text" name="fname" /></p>
<p>Surname:<br /><input type="text" name="sname" /></p>
<p>Username:<br /><input type="text" name="uname" /></p>
<p>Password:<br /><input type="password" name="pword1" /></p>
<p>Verify Password:<br /><input type="password" name="pword2" /></p>
<p><input type="submit" name="submitForm" value=" Submit " /></p>
</form>
</body>
</html>

Any information inside the <form> </form> is alltogether. So when you submit it will pass all the other fields in between this form. You can give your form a name but it is not necessary for the most part.

Ah ok that is great ya a star mate thank you so much mate really appreciate it mate :slight_smile:

I tried your code the thing is for some reason it it gets stuck at this point

if (!$_POST[‘password1’] !== $_POST[‘password2’] || empty($_POST[‘password1’])) {
echo ‘Your passwords do not match Or you did not enter a password. Please enter again’;

because I enter the password and made sure its the same password each time but when I click the submit button it keeps printing “'Your passwords do not match Or you did not enter a password. Please enter again” even though the two passwords are the same I made sure all the variables are the same and all the text box names re the same so I dunno what else the problem maybe

<?php

if ($_POST['submitForm']) {

    if (!$_POST['password1'] !== $_POST['password2'] || empty($_POST['password1'])) {
        echo 'Your passwords do not match Or you did not enter a password. Please enter again';
    } elseif (!empty($_POST['fname']) && !empty($_POST['sname']) && !empty($_POST['uname'])) {
        $conn = mysql_connect("localhost","root","") or die("Could Not Connect To The Database");
        mysql_select_db("database",$conn) or die("Could Not Select The Database");
        $res = mysql_query("SELECT username FROM passwordtable WHERE username='$_POST[uname]'",$conn) or die("Query Failed");
        $exists = mysql_num_rows($res);

        if ($exists !== 0) {
            echo 'That Username Already Exists In The Database. Please Choose Another User Name Thank You.';
        } else {
            $sql = "INSERT INTO passwordtable (user_id,firstname,surname,username,password) VALUES ('','$_POST[fname]','$_POST[sname]','$_POST[uname]','$_POST[password1]')";
            $query = mysql_query($sql,$conn) or die(mysql_error("Could Not Write Information To The Database"));

            if (mysql_affected_rows($conn) == 0) {
                echo 'Your Account Was Not Created.';
            } else {
                echo 'Your Account Was Created Successfully';
            }
        }
    }
}

?>

        <p align="center"><form action="register.php" method="post" >
		<p><STRONG>First Name:</STRONG><br>
		<input type="text" name="fname" maxlength="20"></p>
		<p><STRONG>Surname:</STRONG><br>
		<input type="text" name="sname" maxlength="20"></p>
		<p><STRONG>User Name:</STRONG><br>
		<input type="text" name="uname" maxlength="20"></p>
		<p><STRONG>Password:</STRONG><br>
		<input type="password" name="password1" maxlength="32"></p>
		<p><STRONG>Confirm Password:</STRONG><br>
		<input type="password" name="password2" maxlength="32"></p>
		<p><input type="submit" name="submitForm" value="Register User"></p>
		</form>
		</p>

This is what I done but it still doesn’t seem to work even though I enter the same password it still comes up with “'Your passwords do not match Or you did not enter a password. Please enter again” so I hope you can help me to find what the problem is it would be great

Thank you so much :slight_smile: