MYSQL database not showing inserted data from HTML form - php

I am fairly new to PHP and I was following a simple tutorial on youtube, I followed the youtube video, double and tripple checked to make sure everything I typed was correct and data was still not being inserted.
I searched the internet for hours and I came up with a fix, sort of but I don't think it's the correct way to do it
HTML
<html>
<head>
<title>Insert Form Data In MYSQL Database Using PHP</title>
</head>
<body>
<form action="insert.php" method="post">
Name : <input type="text" name="username">
<br/>
Email : <input type="text" name="email">
<br/>
<input type="submit" value="Insert">
</form>
</body>
</html>
PHP
<?php
$con = mysqli_connect('localhost','root','');
if (!$con) {
echo 'Not Connected To Server';
}
if (!mysqli_select_db($con,'tutorial')) {
echo 'Database Not Selected';
}
if (isset($_POST['username'])){
$Name = $_POST['username'];
}
if (isset($_POST['email'])){
$Email = $_POST['email'];
}
$sql = "INSERT INTO person (Name, Email) VALUES ('John', 'john#gmail.com')";
if (!mysqli_query($con,$sql)) {
echo 'Not Inserted';
} else {
echo 'Inserted Successfully!';
}
header("refresh:10; url=index.html");
?>
I replaced '$Name' and '$Email' with John and john#gmail.com, then I type it into the html form and the data goes into the database correctly.
I then found another HTML form online with more PHP but it does the same thing(not inserting any data to the database)
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Record Form</title>
</head>
<body>
<form action="insert1.php" method="post">
<p>
<label for="firstName">First Name:</label>
<input type="text" name="firstname" id="firstName">
</p>
<p>
<label for="lastName">Last Name:</label>
<input type="text" name="lastname" id="lastName">
</p>
<p>
<label for="emailAddress">Email Address:</label>
<input type="text" name="email" id="emailAddress">
</p>
<input type="submit" value="Submit">
</form>
</body>
</html>
PHP
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_POST['firstname']);
$last_name = mysqli_real_escape_string($link, $_POST['lastname']);
$email_address = mysqli_real_escape_string($link, $_POST['email']);
// attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email_address) VALUES ('$first_name', '$last_name', '$email_address')";
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);
?>
The fields are blank, any help will be greatly appreacited!
Btw This is how the fields display I'm using xampp server.

I had used the below code and it works fine for me.
<?php
$link = mysqli_connect("localhost", "root", "", "dummy");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
/* Collect below values from $_POST
$firstname = 'John';
$lastname = 'Doe';
$email = 'test#gmail.com';
*/
// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $firstname);
$last_name = mysqli_real_escape_string($link, $lastname);
$email_address = mysqli_real_escape_string($link, $email);
// attempt insert query execution
$sql = "INSERT INTO accounts (account_firstname, account_lastname, account_email) VALUES ('$first_name', '$last_name', '$email_address')";
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);
?>

Related

Save login form data using php

html webpage screenshotphp code shown on button clickmySql database tableI need to store user login data. i am using phpMyAdmin. When I click on submit button, data is not stored. Instead the php code is shown. Both code files are given below. What I am doing wrong. Help me. I
am unable to store user data using phpmyadmin in xampp.
my html code
<html>
<head>
<title>Yahoo Signin And Signup Form</title>
</head>
<body>
<h2 style="color: midnightblue">yahoo!</h2>
<hr color="magenta">
<form method="post" action="connect.php" >
<fieldset style="background:#6495ED;">
<legend style="padding:20px 0; font-size:20px;">Signup:</legend>
<label for ="firstName">Enter First Name</label><br>
<input type="text" placeholder="First name" id="firstName" name ="firstName">
<br>
<label for ="lastName">Enter Last Name</label><br>
<input type="text" placeholder="Last name" id="lastName" name ="lastName">
<br>
<label for ="email">Enter Email</label><br>
<input type="text" placeholder="Email" id="email" name ="email"><br>
<label for ="password">Enter Password</label><br>
<input type="password" placeholder="Password" id="password" name ="password">
<br>
<label for ="number">Enter Mobile Number</label><br>
<input placeholder="03---" id="number" name ="number"><br>
<label for ="date">Enter Date of Birth</label><br>
<input type="text" placeholder="DD/MM/YY" id="date" name ="date"><br>
<label for ="gender">Enter Gender</label><br>
<input type="text" placeholder="Male/Female/Other" id="gender" name
="gender"><br>
<br><button style="background-color:orangered;border-
color:dodgerblue;color:lightyellow">Signup</button>
</fielsdet>
</form>
</body>
</html>
my connect.php
<?php
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
$number = $_POST['number'];
$date = $_POST['date'];
$gender = $_POST['gender'];
// Making Connection with database
$con = new mysqli('localhost','root','','phpdata');
if ($con -> connect_error) {
die('Connection failed :'.$conn -> connect_error);
}
else{
$stmt = $con->query("INSERT INTO signup(firstName, lastName, email, password,
number, date, gender)
values(?,?,?,?,?,?,?)");
$stmt->bind_param("ssssiss",$firstName, $lastName, $email, $password,
$number, $date, $gender);
$stmt->execute();
echo "Sign up successful";
$stmt->close();
$con->close();
}?>
Use prepare instead of query. All everything is ok.:
$stmt = $con->prepare("INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
values(?,?,?,?,?,?,?)");
And make button type as submit:
<br><button type="submit" style="background-color:orangered;border-color:dodgerblue;color:lightyellow">Signup</button>
here is the code, it works fine with me
<?php
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
$number = $_POST['number'];
$date = $_POST['date'];
$gender = $_POST['gender'];
// Making Connection with database
$con = new mysqli('localhost','root','','phpdata');
if ($con -> connect_error) {
die('Connection failed :'.$conn -> connect_error);
}
else{
$stmt = $con->query("INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
values("'.$firstName.'","'.$lastName.'","'.$email.'","'.$password.'","'.$number.'","'.$date.'","'.$gender.'")");
if ($con->query($stmt) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$con->close();
}//end of else of connection
?>
Add type in your submit button.
<button type='submit' style="background-color:orangered;border-color:dodgerblue;color:lightyellow">Signup</button>
and also your question marks and params ara not matching. it should be match. otherwise data won't store your db
correct that line also
The main problem is you are not loading code via apache server try to open http://localhost/signup.html instead of C:/xmapp/htdocs/connect.php
It seems you want to user PDO but your connection string not correct
<?php
$firstName = trim($_POST['firstName']);
$lastName = trim($_POST['lastName']);
$email = trim($_POST['email']);
$password = md5(trim($_POST['password']));
$number = trim($_POST['number']);
$date = trim($_POST['date']);
$gender = trim($_POST['gender']);
$con= new PDO("mysql:host=127.0.0.1;dbname=phpdata", 'root', 'root');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sqli = "INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
values(?,?,?,?,?,?,?)";
try {
$stmt= $con->prepare($sqli);
$stmt->bindParam(1,$firstName);
$stmt->bindParam(2,$lastName);
$stmt->bindParam(3,$email);
$stmt->bindParam(4,$password);
$stmt->bindParam(5,$number);
$stmt->bindParam(6,$date);
$stmt->bindParam(7,$gender);
$status = $stmt->execute();
echo "Sign up successful";
$stmt->close();
$con->close();
} catch(PDOException $e) {
echo "Error ".$e->getMessage();
}
?>
another problem is with your html form button type is missing
<button type="submit".... />
Here is the complete code after analyzing it for a lot of time. in your $stmt variable there was no query, it was empty. This code works fine just copy and paste it.
<?php
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
$number = $_POST['number'];
$date = $_POST['date'];
$gender = $_POST['gender'];
// Making Connection with database
$con = new mysqli('localhost','root','','abc');
if ($con -> connect_error) {
die('Connection failed :'.$conn -> connect_error);
}
else{
$sql = "INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
values('$firstName','$lastName','$email','$password','$number','$date','$gender')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
$con->close();
}//end of else of connection
?>

Can't insert new records through PHP into mysql database

When I press the submit button I get error.
object not found error.
And the page automatically adds empty entries with auto incremented primary key (without pressing the submit button).
I am still a beginner in PHP, I searched thoroughly but I can't find out what's wrong in code.
<html>
<head>
<title>Add New Record in MySQL Database</title>
</head>
<body>
<form action="insert.php" method="post">
<p>
<label for="Name">Full Name:</label>
<input type="text" name="Name" id="Name">
</p>
<p>
<label for="Code">Code:</label>
<input type="text" name="Code" id="Code">
</p>
<p>
<label for="GPA">GPA:</label>
<input type="text" name="GPA" id="GPA">
</p>
<input type="submit" value="Submit">
</form>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "username", "password", "students");
// Check connection
if ($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$full_name = filter_input(INPUT_POST, 'full_name');
$code = filter_input(INPUT_POST, 'code');
$gpa = filter_input(INPUT_POST, 'gpa');
// attempt insert query execution
$sql = "INSERT INTO info VALUES ('$full_name', '$code', '$gpa')";
if (mysqli_query($link, $sql)) {
echo "Records added successfully. $full_name";
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
</body>
</html>
Try this:
$full_name = filter_input(INPUT_POST, 'Name');
$code = filter_input(INPUT_POST, 'Code');
$gpa = filter_input(INPUT_POST, 'GPA');
The reason why I wrote that is because your input names contain Name, Code and GPA so you need to write this exactly as your input names (case-sensitive).
Do with isset(). when the submit button clicks only the code runs.
Inside the php you should use the form input name field.
<?php
if(isset($_POST['submit'])){
$link = mysqli_connect("localhost", "username", "password", "students");
if ($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$full_name = filter_input(INPUT_POST, 'full_name');
$code = filter_input(INPUT_POST, 'code');
$gpa = filter_input(INPUT_POST, 'gpa');
//to prevent sql injection attack
$full_name = mysqli_real_escape_string($link, $full_name);
$code = mysqli_real_escape_string($link, $code);
$gpa = mysqli_real_escape_string($link, $gpa);
// attempt insert query execution
$sql = "INSERT INTO info (Name,Code,GPA) VALUES ('$full_name', '$code', '$gpa')";
if (mysqli_query($link, $sql)) {
echo "Records added successfully. $full_name";
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
}
?>
<html>
<head>
<title>Add New Record in MySQL Database</title>
</head>
<body>
<form action="insert.php" method="post">
<p>
<label for="Name">Full Name:</label>
<input type="text" name="full_name" id="Name">
</p>
<p>
<label for="Code">Code:</label>
<input type="text" name="code" id="Code">
</p>
<p>
<label for="GPA">GPA:</label>
<input type="text" name="gpa" id="GPA">
</p>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
The problem is the input name. You named Full Name input with name="Name", but you declare $full_name = filter_input(INPUT_POST, 'full_name'); in php section. you must change full_name to Name. As well as the Code and GPA input.

PHP/MySQL Creates Blank Record In Database

I have a user input form(HTML) that is supposed to take the information and insert it into a MySQL database via PHP. The PHP apparently executes and echoes "Your registration has completed successfully". A record is created in the database but the columns are blank(I have removed my server, database, and password from the PHP code).
HTML:
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<title>User Portal</title>
</head>
<div class="inputContainer">
<header>
User Information Portal
</header>
<form action="php/userPost.php" method="post">
<label for=firstName">First Name</label>
<input type="text" id=firstName" name="fname">
<br><br>
<label for="lastName">Last Name</label>
<input type="text" id="lastName" name="lname">
<br><br>
<label for="eMail">Email</label>
<input type="text" id="eMail" name="email">
<br><br>
<label class="labelRole" for="userRole">Role -</label><br>
<input type="radio" id="userRole" name="role" value="Instructor"> Instructor
<input class="submitButton" type="submit" name="submit" value="Register">
</form>
</div>
</body>
PHP:
<?php
$sname = "server-name";
$uname = "username";
$pword = "password";
$dbname = "web_tech_test";
$conn = new mysqli($sname, $uname, $pword, $dbname);
if ($conn->connect_error) {
die("Connection failure: " . $conn->connect_error);
}
$fname = !empty($_POST['firstName']);
$lname = !empty($_POST['lastName']);
$email = !empty($_POST['eMail']);
$role = isset($_POST['userRole']);
$sql = "INSERT INTO users (first_name, last_name, email, role)
VALUES ('$fname', '$lname', '$email', '$role')";
if ($conn->query($sql) === TRUE) {
echo "Your registration has completed successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
This creates a new record in the DB but all the columns are blank. Any ideas why this may be happening?
$fname = !empty($_POST['firstName']);
$lname = !empty($_POST['lastName']);
$email = !empty($_POST['eMail']);
$role = isset($_POST['userRole']);
this code returns a boolean, not a string value...
Use !empty() just for validation
example
if(empty($_POST['eMail'])) {
die("Email cannot be empty");
}
You're confusing the id and the name tags on the inputs.
The name tags are the ones which will be submitted as keys to your server.
Try this in your server php script after submitting your form to see which key/values are actually received by the server:
var_dump($_POST);
Also, if you want to check that all fields have been filled out, use something similar as this:
if (empty($_POST['firstName'])) {
die("firstname is empty!");
}
In your current example you're actually saving a boolean to your variables.
And, last but not least, never insert variables from a potentially unsafe source (like a user input) directly into your SQL. Use pdo: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers for this
Full code example to get you started:
//prepare your values
if (empty($_POST['fname']) || empty($_POST['lname']|| empty($_POST['email']|| !isset($_POST['role'])) {
die ("some values were empty or not set");
}
//prepare your database
$db = new PDO('mysql:host=server-name;dbname=web_tech_test;charset=utf8mb4', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //throw an exception if there is an error
//create your query
$stmt = $db->prepare("INSERT INTO users (first_name, last_name, email, role) VALUES (:first_name,:last_name,:email,:role)"); //create a query statement
$stmt->bindValue(":first_name", $firstName); //put your values into your statement
$stmt->bindValue(":last_name", $lastName);
$stmt->bindValue(":email", $email);
$stmt->bindValue(":role", $role);
if ($stmt->execute()) { //execute the query
echo "Your registration has completed successfully";
} else {
echo "Error :(";
}

Get and insert Data into MySQL database using PHP with xampp on localhost

I have managed to connect to database and I manage to insert using following code.
<?php
$username = 'root';
$password = '';
$db = 'demo';
$conn = new mysqli ('localhost',$username, $password, $db) or die("unable to connect");
$sql="insert into persons (first_name,last_name,email_address) values ('sara','smith','email#email.com')";
$query=mysqli_query($conn,$sql);
if($query)
echo 'data inserted';
?>
But the problem is that when I try to enter data using HTML form, it didn't work for me. I have tried to follow different tutorials and different answers here on stackoverflow. Can anyone please tell me the easiest way of inserting and getting data from MySQL using PHP ?
If there is any easy tutorial or blog from where i can learn and understand all this, I would love to watch or read.
I manage to do it in following way.
Create a file name index.php with following code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Record Form</title>
</head>
<body>
<form action="insert.php" method="post">
<p>
<label for="firstName">First Name:</label>
<input type="text" name="firstname" id="firstName">
</p>
<p>
<label for="lastName">Last Name:</label>
<input type="text" name="lastname" id="lastName">
</p>
<p>
<label for="emailAddress">Email Address:</label>
<input type="text" name="email" id="emailAddress">
</p>
<input type="submit" value="Submit">
</form>
</body>
</html>
Then create another file name as insert.php
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_POST['firstname']);
$last_name = mysqli_real_escape_string($link, $_POST['lastname']);
$email_address = mysqli_real_escape_string($link, $_POST['email']);
// attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email_address) VALUES ('$first_name', '$last_name', '$email_address')";
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);
?>
//procedural style
$mysqli = mysqli_connect('host','username','password','database_name');
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//inserting a record
$product_code = '"'.$mysqli->real_escape_string('P1234').'"';
$product_name = '"'.$mysqli->real_escape_string('42 inch TV').'"';
$product_price = '"'.$mysqli->real_escape_string('600').'"';
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO products (product_code, product_name, price) VALUES($product_code, $product_name, $product_price)");
if($insert_row){
print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br />';
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
A quick and untested example of using an HTML form with the POST method to insert data entered by a user into the db.
<?php
$result = false;
$dbhost = 'localhost';
$username = 'root';
$password = '';
$db = 'demo';
if( $_SERVER['REQUEST_METHOD']=='POST' ){
$conn = new mysqli ( $dbhost,$username, $password, $db );
if( $conn ){
$sql='insert into `persons` ( `first_name`,`last_name`,`email_address` ) values (?,?,?);';
$stmt=$conn->prepare( $sql );
$stmt->bind_param('sss', $_POST['firstname'], $_POST['lastname'], $_POST['email'] );
$result = $stmt->execute();
}
$conn->close();
}
?>
<!doctype html>
<html>
<head>
<title>Simple Form submission example</title>
</head>
<body>
<form method='post'>
<input type='text' name='firstname' />
<input type='text' name='lastname' />
<input type='text' name='email' />
<input type='submit' value='Submit' />
<?php
echo $result ? '<div>The database was updated</div>' : '';
?>
</form>
</body>
</html>
Try tutsplus or lynda, Provide you with the best tuto !

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.

Categories