INSERT INTO sql table from variable HTML form - php

I am trying to create two different tables based upon a radio selection in the HTML file. This is the HTML form I have created so far:
<form action="connect.php" method=POST>
First Name: <input type="text" name="firstname"><br><br>
Last Name: <input type="text" name="lastname"><br><br>
Email: <input type="text" name="email"><br><br>
Desired Password: <input type="password" name="password"><br><br>
Re-type Password: <input type="password" name="password"><br><br>
I am a: <input type="radio" name="role" value="student">Student
<input type="radio" name="role" value="alumni">Alumni<br><br>
<div class="stud">
Major: <input type="text" name="studmajor"><br><br>
Emphasis: <input type="text" name="studemphasis"><br><br>
Expected Graduation Year: <input type="text" name="studgradyear"><br><br>
Hobbies: <input type="text" name="studhobbies">
</div>
<div class="alum">
Gradutation Year: <input type="text" name="alumgradyear"><br><br>
Major: <input type="text" name="alummajor"><br><br>
Emphasis: <input type="text" name="alumemphasis"><br><br>
Company: <input type="text" name="alumcompany"><br><br>
Hobbies: <input type="text" name="alumhobbies">
</div>
<br>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
$('input:radio[name=role]').change(function(){
var role = $(this).val();
if(role=='student'){
$('.stud').show();
$('.alum').hide();
}
else if(role=='alumni'){
$('.alum').show();
$('.stud').hide();
}
});
So in this HTML code, I am trying to create a database. One for Alumni and one for Students. Depending on the radio box checked, different options are shown. The following is my php code I wrote (and borrowed) to INSERT INTO the two different tables I have created. I am using c9.io as this is just a mock up to get my idea for the site up and running.
<?php
$servername = getenv('IP');
$username = getenv('C9_USER');
$password = "";
$database = "c9";
$dbport = 3306;
$db = mysqli_connect($servername, $username, $password, $database, $dbport);
if($db === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$first_name = mysqli_real_escape_string($db, $_POST['firstname']);
$last_name = mysqli_real_escape_string($db, $_POST['lastname']);
$email_address = mysqli_real_escape_string($db, $_POST['email']);
$password = mysqli_real_escape_string($db, $_POST['password']);
$studmajor = mysqli_real_escape_string($db, $_POST['studmajor']);
$studemphasis = mysqli_real_escape_string($db, $_POST['studemphasis']);
$studgradyear = mysqli_real_escape_string($db, $_POST['studgradyear']);
$studhobbies = mysqli_real_escape_string($db, $_POST['studhobbies']);
$alumgradyear = mysqli_real_escape_string($db, $_POST['alumgradyear']);
$alummajor = mysqli_real_escape_string($db, $_POST['alummajor']);
$alumemphasis = mysqli_real_escape_string($db, $_POST['alumemphasis']);
$alumcompany = mysqli_real_escape_string($db, $_POST['alumcompany']);
$alumhobbies = mysqli_real_escape_string($db, $_POST['alumhobbies']);
$role = mysqli_real_escape_string($db, $_POST['role']);
// Post to Student
if($role == "student"){
$sql = "INSERT INTO Student (FirstName, LastName, Email, Password, Major, Emphasis, GradYear, Hobbies)
VALUES ('$first_name', '$last_name', '$email_address', '$password', '$studmajor', '$studemphasis', '$studgradyear', '$studhobbies');";
}
// Post to Alumni
else if($role == "alumni"){
$sql = "INSERT INTO Alumni (FirstName, LastName, Email, Password, GradYear, Major, Emphasis, Company, Hobbies)
VALUES ('$firstname', '$lastname', '$email', '$password', '$alumgradyear', '$alummajor', '$alumemphasis', '$alumcompany', '$alumhobbies');";
}
mysqli_close($db);
?>
Any help would be greatly appreciated. I'm pretty new to SQL and PHP so this is a little confusing.
Sorry for not being very specific. Whenever I fill out the form and click submit, I'm redirected and it displays:
Cannot POST /username/project/connect.php
My guess is that the if/elseif statement in the php file is what's causing the issue but I can't accurately say for sure.

You should name your form, pull data from HTML in connect.php and then use php to insert.
Here is a quick demo to show you how it is done!
PHP MYSQL Database Manipulation
Hope this Helps!

Related

Register Form PHP not inserting values into DB, just reloading the page

I really can not find what am I doing wrong in my registration form, unfortunately the page is just reloading instead of inserting values from form to my DB table.
Register.php
<?php
require_once("./Connection.php");
if(isset($_POST['submit'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$options = array("cost"=>5);
$hashPassword = password_hash($password,PASSWORD_BCRYPT,$options);
$sql = "insert into agents (firstName, lastName, email, phone, password) value ('".$firstName."', '".$lastName."', '".$email."','".$phone."','".$hashPassword."')";
$result = mysqli_query($conn, $sql);
if($result)
{
echo "Registration successfully";
}
}
?>
Connection.php
<?php
$conn = mysqli_connect("localhost","root","","KBHestate");
if(!$conn){
die("Connection error: " . mysqli_connect_error());
}
Register Form
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<input type="text" name="firstName" value="" placeholder="First Name">
<input type="text" name="lastName" value="" placeholder="Surname">
<input type="text" name="email" value="" placeholder="Email">
<input type="text" name="phone" value="" placeholder="Phone">
<input type="password" name="password" value="" placeholder="Password">
<button type="submit" name="submit">Submit</button>
</form>
Please make sure the following line has no problem when it is interpreted by the PHP:
$options = array("cost"=>5);
$hashPassword = password_hash($password,PASSWORD_BCRYPT,$options);
On the other hand, please make sure that the password field is wide enough to store the $hasPassword data
Your code looks fine, it should work. I am hoping you are having Register form in the same file Register.php
But as you mentioned it's just reload the page that means there must be a exception/error from mysql query that is not handled in your code.
You have not shared your table structure. So, I am answering you based on the common mistake.
Like one of your table column width is varchar(10) and you are trying to pass data of length 20 char.
So, i suggest you to add below code in your Register.php as the else condition for if($result). So, it will display the error if any.
else {
echo("Error description: " . $conn->error);
}
Now your Register.php code will be look like below:
<?php
require_once("./Connection.php");
if(isset($_POST['submit'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$options = array("cost"=>5);
$hashPassword = password_hash($password,PASSWORD_BCRYPT,$options);
$sql = "insert into agents (firstName, lastName, email, phone, password) value ('".$firstName."', '".$lastName."', '".$email."','".$phone."','".$hashPassword."')";
$result = mysqli_query($conn, $sql);
if($result)
{
echo "Registration successfully";
}else {
echo("Error description: " . $conn->error);
}
}
?>

How to fix php code to transfer data from html form to a database

I am trying to get data from a form into a database, have searched all the answers and code on yours and other websites but none of them work.
It is connecting to the database OK, but keep getting an error message when submitting the form.
Thanks
My form is
<html><head>
<link rel="stylesheet" href="form.css" type="text/css">
<meta charset="utf-8">
</head>
<body>
<h1>A small example page to insert some data in to the MySQL database using
PHP</h1>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" /><br><br>
Lastname: <input type="text" name="lastname" /><br><br>
<input type="submit" />
</form>
</body>
</html>
My PHP code is
<?php
$servername = "server";
$username = "username";
$password = "xxxx";
$database = "xxx_com";
$conn = mysqli_connect($servername, $username, $password, $database);
{
$first_name = $_POST['firstname'];
$last_name = $_POST['lastname'];
$dbh->query = "INSERT INTO nametable (firstname, lastname)
VALUES ('$_POST[firstname]', '$_POST[lastname]')";
}
if (!mysqli_query($user_info, $connect)) {
die('Error: ' . mysqli_error());
}
echo “Your information was added to the database.”;
mysqli_close($connect);
?>
Your html form using
Firstname: <input type="text" name="fname" /><br><br>
Lastname: <input type="text" name="lname" /><br><br>
but your PHP get from
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
it should used the same name. Like
$first_name = $_POST['fname'];
$last_name = $_POST['lname'];
As mention by people comment, please learn how to avoid the SQL injection problem

PHP / MySQLi registration form just returns a blank white page with no echoes or errors

so I'm just making a very basic registration for for PHP, and well...everytime I try to run it, it just returns a blank page, there are no errors or echos, just a plain, blank white page. I was hoping you guys could explain why as there are no obvious errors in my code.
Here is my reg.php file:
<html>
<head>
<title>Registered!</title>
</head>
<body>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
if(isset($_POST['submit']))
{
$name = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$username = mysqli_real_escape_string($db, $name);
$email = mysqli_real_escape_string($db, $email);
$password = mysqli_real_escape_string($db, $password);
$query = mysqli_query($db, "INSERT INTO users (username, password,
email)VALUES ('$name', '$password', '$email')");
if($query)
{
echo "You are now registered!";
}
else
{
echo "failed";
}
}
?>
</body>
</html>
and here is my html For the form section
<div id="id01" class="modal">
<form class="modal-content animate" action="reg.php" method="post">
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" id="username"
name="username" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" id="password"
name="password" required>
<label><b>Email</b></label>
<input type="text" placeholder="Enter Email" id="email" name="email"
required>
<button class="btn waves-effect waves-light teal lighten-1" type="submit"
name="submit" id="submit" value="submit">Submit<i class="material-icons
right">send</i></button>
</div>
</form>
</div>
And yes, I know, the form is open to SQL injection, I'll take care of that as soon as I can actually get the basic form to work!
Sorry, I know this will probably end up being some stupid fix, but I can't figure it out for the life of me...
Thanks everyone!
There is a SQL error in your code, try changing:
$query = mysqli_query($db, "INSERT INTO users (username, password,
email)VALUES ('$name', '$password', '$email')");
to
$query = mysqli_query($db, "INSERT INTO users (username, password,
email) VALUES ('$name', '$password', '$email')");

PHP to have required text fields

I have created a simple form that currently submits to a database. I am now wanting to add validation so that each field is required to be filled in.
This is what i have so far:
<?php include("header.php"); ?>
</br>
<form method = "post" action = "post-poster.php">
<label>Address Line 1:</label> <input name="addline1" id="addline1"></br>
<label>Area:</label> <input name="area" id="area"></br>
<label>Description:</label> <input name="description" id="description"></br>
<label>Bedrooms: </label><input name="bedrooms" id="bedrooms"></br>
<label>Bathrooms:</label> <input name="bathrooms" id="bathrooms"></br>
<label>Landlords Name:</label> <input name="lname" id="lname"></br>
<label>Landlords Number:</label> <input name="lphone" id="lphone"></br>
<label>Landlords Email:</label> <input name="lemail" id="lemail"></br>
</br>
<input type="submit" value="Submit">
</form>
<?php include("footer.php"); ?>
and this is the file that submits to the DB, i have blanked my db details:
<?php
/*
Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password)
*/
$link = mysqli_connect("localhost", "inspire_****", "*****", "inspire_****");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$addline1 = mysqli_real_escape_string($link, $_POST['addline1']);
$area = mysqli_real_escape_string($link, $_POST['area']);
$description = mysqli_real_escape_string($link, $_POST['description']);
$bedrooms = mysqli_real_escape_string($link, $_POST['bedrooms']);
$bathrooms = mysqli_real_escape_string($link, $_POST['bathrooms']);
$lname = mysqli_real_escape_string($link, $_POST['lname']);
$lphone = mysqli_real_escape_string($link, $_POST['lphone']);
$lemail = mysqli_real_escape_string($link, $_POST['lemail']);
// attempt insert query execution
$sql = "INSERT INTO posts (addline1, area, description, bedrooms, bathrooms, lname, lphone, lemail) VALUES ('$addline1', '$area', '$description', '$bedrooms', '$bathrooms', '$lname', '$lphone', '$lemail')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
If anyone can help me i would be greatly appreciated
One way, perhaps the lazy way, is to add required to each input tag. For example
<input name="addline1" id="addline1" required>
You can add the key word required in this manner to all input tags that apply.

When the user presses sign up, it keeps adding values to the database (MYSQL + PHP)

I am starting to learn PHP. I just tried to make a signup.php page where the user (which is me) has a form and he fills the form and presses the sign up button, and then the values are saved in the database.
This code works perfectly fine in XAMPP. If an email already exists, it says clearly that the email already exists and the user is required to select a new username.
However, when I uploaded everything to cPanel on my website and tried to test it, I can keep pressing the sign up button and it will keep saying "successful" and when I check PhpMyAdmin, there are like 5 values of the same thing (because of the multiple clicks of the button).
So I don't really know what the problem is here. Any help is highly appreciated.
My current code:
<form method='POST' class="form-login">
<?php
if(isset($_POST['submit'])){
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$IP = $_SERVER['REMOTE_ADDR'];
$fields = array(
'Username' => $username,
'Email' => $email
);
$dup = false;
foreach ($fields as $field => $value) {
$value = mysql_real_escape_string($value);
$query = mysql_query("SELECT COUNT({$field}) AS n FROM Users WHERE {$field}='{$value}';");
$tuple = mysql_fetch_assoc($query);
if ($tuple['n'] > 0) {
$dup = true;
break;
}
}
if ($dup) {
echo "<p><b><center> <font color=\"red\">{$field} already exists.<br> </b>If you already have an account, please<a href = 'login.php'> click here </a> to login.</font></center></p>";
}
else {
$regdate=date("Y-m-d H:i:s");
mysql_query("INSERT INTO users VALUES ('', '$first_name', '$last_name', '$username', '$password', '$email', '1', '0', '2', '$IP', '$regdate', '', 'active')");
<label>First Name:</label>
<input type="text" name="first_name" id="first_name" value="<?=(isset($first_name) ? $first_name : "")?>"/>
<label>Last Name:</label>
<input type="text" name="last_name" id="last_name" value="<?=(isset($last_name) ? $last_name : "")?>"/>
<label>Username:</label>
<input type="text" name="username" id="username" value="<?=(isset($username) ? $username : "")?>"/>
<label for="email">
Email:</label>
<input type="email" id="email" name="email" value="<?=(isset($email) ? $email :"")?>"/>
<label>Password:</label>
<input type="password" name="password" id="password" value="<?=(isset($password) ? $password : "")?>"/>
<button type="submit" name="submit" value="Register">Register</button>
</form>

Categories