PHP Form No Errors Not Inserting - php

I have a form, below, that was working for a while, however for some reason the code has now stopped inserting what the user would input via the form. Once the form was working, the only things I changed were the style, and nothing on the database site, or with the insertion of the data.
I get zero errors when I hit the Submit button, and it takes me to the page that I want the form to take the user too.
<form action="insert.php" method="post">
<p>
<label for="firstName">First Name:</label>
<input type="text" name="name" id="Name">
</p>
<p>
<label for="emailAddress">Email Address:</label>
<input type="text" name="email" id="email">
</p>
<input type="submit" value="Submit">
and my PHP code is:
<?php
$link = mysqli_connect("localhost", "root", "root", "travelsite");
// 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, $_REQUEST['name']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);
// attempt insert query execution
$sql = "INSERT INTO subscribe (name, email) VALUES ('$name', '$email')";
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);
?>

Try using $_POST['name'] and $_POST['email'].
Also as mentioned on the comments: you got your variables mixed up. (thx #NitinP)
Try also using a prepare statement like:
/* create a prepared statement */
if ($stmt = mysqli_prepare($link, "INSERT INTO subscribe (name, email) VALUES (?, ?)")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ss", $name, $email); /*or $first_name*/
/* execute query */
mysqli_stmt_execute($stmt);
printf("%d Row inserted.\n", mysqli_stmt_affected_rows($stmt));
/* close statement */
mysqli_stmt_close($stmt);
}
For more information see the link under Procedural style

Related

MYSQL database not showing inserted data from HTML form

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);
?>

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 :(";
}

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.

Error when trying to Inserting into data into the database. Simple form

I'm new to PHP I have put together a simple form to input data into a database but the data doesn't seem to be inserting into the database. I've been trying to get it working all day.
shows the error Error to Inserting into database at the end of the code.
html
<div id="wrapper">
<section id="top_area">
<article class="box-right">
<form action="script/data.php" method="post">
<p>
<label>Company Name:</label>
<input name="company_name" required="required" placeholder="Joes Cleaners" type="text">
</p>
<p>
<label>Ref:</label>
<input name="ref_num" required="required" placeholder="D123" type="text">
</p>
<p>
<label>Website:</label>
<input name="website" required="required" placeholder="joescleaner.co.uk" type="text">
</p>
<p>
<label>Email:</label>
<input name="email" required="required" placeholder="joescleanersm#gmail.com" type="email">
</p>
<p>
<label>Telephone:</label>
<input name="tel" required="required" placeholder="0712345678" type="number">
</p>
<p>
<label>Message:</label>
<input name="message" required="required" placeholder="hello" type="text">
</p>
<p>
<input value="Submit" type="submit">
</p>
</form>
</article>
</section>
</div>
PHP
<?php
$db_hostname = 'localhost';
$db_database = 'form';
$db_username = 'user';
$db_password = 'password';
// Connect to server.
$db_server = mysql_connect($db_hostname, $db_username, $db_password)
or die("Unable to connect to MySQL: " . mysql_error());
// Select the database.
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
// Select the database.
mysql_select_db("form")
or die("Unable to select database: " . mysql_error());
// Get values from form
$company_name = $_POST['company_name'];
$ref_num = $_POST['ref_num'];
$website = $_POST['website'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$message = $_POST['message'];
// Insert data into mysql
$sql="INSERT INTO users (company_name, ref_num, website, email, tel, message)
VALUES ('$company_name', '$ref_num', '$website', '$email', $tel, $message, NOW())";
$result = mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
header('Location: ../thankyou.php');
}
else {
echo "Error to Inserting into database";
}
// close mysql
mysql_close();
?>
You should start using PDO for DB access, mysql_query is deprecated.
PDO let's you make prepared statements. These are secured against SQL Injections (your code isn't).
$stmt = $dbh->prepare("INSERT INTO users (company_name, ref_num, website, email, tel, message) VALUES (:company_name, :ref_num, :website, :email, :tel, :message, NOW())");
$stmt->bindParam(':company_name', $company_name);
$stmt->bindParam(':ref_num', $ref_num);
// And bind the remaining parameters
[...]
$stmt->execute();
If this fails, you can get detailed informations by running
print_r($stmt->errorInfo());
That should help you with finding errors in your SQL.
$dbh is a new PDO instance (see PDO::__construct)
As in your query you are trying to insert more than column values.
Your query is :
$sql="INSERT INTO users (company_name, ref_num, website, email, tel, message) VALUES ('$company_name', '$ref_num', '$website', '$email', $tel, $message, NOW())"
Either remove NOW() data or add another column for NOW() data
Also you can try below query.
$sql="INSERT INTO users (company_name, ref_num, website, email, tel, message) VALUES ('$company_name', '$ref_num', '$website', '$email', $tel, $message)"
When fixed column errors like Programming Student says, you should modify your mysql_query command:
it needs the db connection you opened before.
Try this:
$result = mysql_query($db_server, $sql);
Why don't try Object Oriented syntax ?
if ($db_server->query($sql) === TRUE) {
header('Location: ../thankyou.php'); } else {
echo "Error: " . $conn->error;
}
}

Sending Variables to MySQLi

i have been staring at this page for half an hour trying to figure out where i am going wrong. The first two variables are found and inserted into database, however the last two, 'email' and 'password' are not found, not inserted into database but still however pass the if statement. Any help will be much appreciated.
Form.php
<form name="signup" method="POST" action="signup.php">
<label for="signupFirstName">First Name</label>
<input type="text" id="signupFirstName" name="signupFirstName" />
<label for="signupLastName">Last Name</label>
<input type="text" id="signupLastName" name="signupLastName"/>
<label for="signupEmail">Email</label>
<input type="text" id="signupEmail" name="signupEmail" />
<label for="signupConfirmEmail">Confirm Email</label>
<input type="text" id="signupConfirmEmail" name="signupConfirmEmail"/>
<label for="signupPassword">Password</label>
<input type="text" id="signupPassword" name="signupPassword"/>
<label for="signupConfirmPassword">Confirm Password</label>
<input type="text" id="signupConfirmPassword" name="signupConfirmPassword"/>
<button name="submit" type="submit" >Submit Form</button>
</form>
signup.php
<?php
if (isset($_POST['signupFirstName']) || isset($_POST['signupLastName']) || isset($_POST['signupEmail']) || isset($_POST['signupPassword']) ) {
echo $_POST['signupEmail'];
$mysqli = new mysqli('localhost', 'user1', 'password', 'db2');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO members (First_Name, Last_Name, Email, Password) VALUES (?,?,?,?)");
$stmt->bind_param('ssss',$sample,$lastName,$email,$password);
// escape the POST data for added protection
$sample = isset($_POST['signupFirstName'])
? $mysqli->real_escape_string($_POST['signupFirstName'])
: '';
$lastName = isset($_POST['signupLastName'])
? $mysqli->real_escape_string($_POST['signupLastName'])
: '';
$email = isset($_POST['signupEmail'])
? $mysqli->real_escape_string($_POST['signupEmail'])
: '';
$password = isset($_POST['signupPassword'])
? $mysqli->real_escape_string($_POST['signupPassword'])
: '';
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
}
else{
echo "broken";
}
?>
You seem to be binding the params to your query before you actually set the variables. Move the bind_param() call above the execute() call.
You can also refactor your code to take out a lot of the junk. Example below:
<?php
function arr_get($array, $key) {
if (isset($array[$key])) {
return $array[$key];
}
return '';
}
if (isset($_POST['signupFirstName']) || isset($_POST['signupLastName']) || isset($_POST['signupEmail']) || isset($_POST['signupPassword']) ) {
echo $_POST['signupEmail'];
$mysqli = new mysqli('localhost', 'user1', 'password', 'db2');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO members (First_Name, Last_Name, Email, Password) VALUES (?,?,?,?)");
$stmt->bind_param('ssss', arr_get($_POST, 'signupFirstName'), arr_get($_POST, 'signupLastName'), arr_get($_POST, 'signupEmail'), arr_get($_POST, 'signupPassword'));
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
}
else {
echo "broken";
}
?>

Categories