In this I created a simple HTML form in which the email and password entered from HTML form are not saving in the MYSQL database! what changes do I made so that data can be save in MYSQL database.
This is my HTML code :
<form style="position: relative;" action="pass.php" method="post" >
<div style="position: absolute; left: 107px; top: 130px; text-align: center; width: 450px;">
<input type="email" name="email" style="border:none" size="45" placeholder="Email" /><br>
<br>
<input type="password" name="password" style="border:none" size="45" placeholder="Password" /><br /><br>
<button type="submit" class="inbutton"></button>
</div>
</form>
This is php code :
<?php
if( $_POST )
{
$con = mysql_connect("mysqlhostname","username","password","databasename");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("databasename", $con);
$users_email = $_POST['email'];
$users_password = $_POST['password'];
$users_email = mysql_real_escape_string($users_email);
$users_password = mysql_real_escape_string($users_password);
$query = "INSERT INTO pass (`email`, `password`) VALUES ('$users_email', '$users_password');";
mysql_query($query);
mysql_close($con);
}
?>
In Html file : give the name property of submit button
<html>
<body>
<form style="position: relative;" action="pass.php" method="post" >
<div style="position: absolute; left: 107px; top: 130px; text-align: center; width: 450px;">
<input type="email" name="email" style="border:none" size="45" placeholder="Email" /><br>
<br>
<input type="password" name="password" style="border:none" size="45" placeholder="Password" /><br /><br>
<button type="submit" class="inbutton" name="Save">Save</button>
</div>
</form>
</body>
</html>
This is php code :
In Your PHP File Do the small changes : pass.php
<?php
if( isset( $_POST['Save'] ) )
{
$con = mysql_connect("mysqlhostname","username","password","databasename");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db( "databasename", $con );
$users_email = $_POST['email'];
$users_password = $_POST['password'];
$users_email = mysql_real_escape_string($users_email);
$users_password = mysql_real_escape_string($users_password);
$query = "INSERT INTO pass ( email, password ) VALUES ( '$users_email', '$users_password' )";
mysql_query( $query, $con );
mysql_close($con);
}
?>
In an offline discussion, we discovered that OP's code is not going into the outer if statement. Here's some sample code on how I would structure it.
Things to notice:
give the submit button a name and then check for that in $_POST
Use PDO instead of mysql API
wrap everything in a try/catch block to see any errors
Gotta run. Good luck!
<form action="pass.php" method="post" >
<input type="email" name="email" size="45" placeholder="Email" />
<br>
<input type="password" name="password" size="45" placeholder="Password" />
<br>
<input type="submit" name="submit" value="Submit">
</form>
/*****************************************/
/**************** pass.php ***************/
/*****************************************/
<?php
// Please use PDO instead of mysql because mysql is deprecated and officially removed as of PHP 7.
// Read about it here: https://phpdelusions.net/pdo
if(isset($_POST['submit'])) {
// Wrap everything in a try/catch block so you can actually see the error.
try {
/*****************************************/
/************* DB CONNECTION *************/
/*****************************************/
// Change this to match your DB credentials
$host = '127.0.0.1';
$db = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
// This is your DB connection. Use it below.
$pdo = new PDO($dsn, $user, $pass, $opt);
/*****************************************/
/************ FORM PROCESSING ************/
/*****************************************/
// Get values from form.
// Do any validation you want here.
$email = $_POST['email'];
$password = $_POST['password'];
/*****************************************/
/*************** DB INSERT ***************/
/*****************************************/
$stmt = $pdo->prepare('INSERT INTO pass (email, password) VALUES (?, ?)');
$stmt->execute(array(
$email,
$password
));
/*****************************************/
/*********** OUTPUT ANY ERRORS ***********/
/*****************************************/
} catch (Exception $e) {
var_dump($e->getMessage());
}
}
php file if($_POST) It should be if( isset( $_POST ['Save'] ) ) and
<button type="submit" class="inbutton"> it should be <button type="submit" class="inbutton" name="Save">
try below php code
<?php
if( isset( $_POST['Save'] ) )
{
$servername = "mysqlhostname"; //localhost or your server name
$username = "username"; //root or your username
$password = "password"; //password or server hasn't password it should be `$password = "";`
$dbname = "databasename"; //your database name
// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($con->connect_error) {
die("Could not connect: " . $con->connect_error);
}
$users_email = $_POST['email'];
$users_password = $_POST['password'];
$sql = "INSERT INTO pass (email, password) VALUES ('$users_email', '$users_password')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$con->close();
}
?>
I got result
Related
I am trying to pinpoint the problem in these form scripts.
I would like to create a line in the SQL server with the data that will be inserted into the HTML form, but each time only the empty line is created without also inserting the form inputs.
HTML
<form action="insert2.php" method="post">
<label for="First_name">First_name:</label>
<input type="text" name="First_name" id="First_name">
<label for="PASSWORD">PASSWORD:</label>
<input type="text" name=value name="pass" id="pass">
<label for="Emailaddress">Emailaddress:</label>
<input type="text" name=value name="email" id="email">
<input name="submit" type="submit" value="Submit">
</form>
PHP
<?php
if(isset($_POST['submit'])){
$First_name = $_REQUEST['First_name'];
$pass = $_REQUEST['password'];
$email = $_REQUEST['Emailaddress'];
}
$servername = "host";
$username = "user";
$password = "";
$dbname = "dbname";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users(First_name, PASSWORD, Emailaddress)
VALUES ('$First_name', '$pass', '$email')";
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
The posted values should be set as $_POST['ExampleField'] not just a variable with that name.
Ex: $First_name should be $_POST['First_name']
If you look in your error logs you are likely getting undefined variable errors with the code as it is now, because $First_name, $PASSWORD and $Emailaddress are never defined.
Also you should avoid directly putting variables into queries like that, it opens you up to large security risks. I would recommend reading up on SQL Injection (https://www.w3schools.com/sql/sql_injection.asp) and binding parameters (https://www.php.net/manual/en/pdostatement.bindparam.php) to see how to avoid those risks.
You need to retrieve the values after a submit of some sort. You have a submit button but you'll want to give it a name (I named it submit). This code should work but you'll be vulnerable to injection attacks.
PHP
<?php
if(isset($_POST['submit'])){
$First_name = $_REQUEST['First_name'];
$pass = $_REQUEST['PASSWORD'];
$email = $_REQUEST['Emailaddress'];
}
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users(First_name, PASSWORD, Emailaddress)
VALUES('$First_name','$pass','$email')";
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
HTML
<form action="insert2.php" method="post">
<label for="First_name">First_name:</label>
<input type="text" name="First_name" id="First_name">
<label for="PASSWORD">PASSWORD:</label>
<input type="text" name="PASSWORD" id="PASSWORD">
<label for="Emailaddress">Emailaddress:</label>
<input type="text" name="Emailaddress" id="Emailaddress">
<input name="submit" type="submit" value="Submit">
</form>
so i am working on the simple project and i dont know why, but i can't insert data into the database
Here is my connection to database
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$database = "register";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $register);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
And in this part of code i am trying to insert data:
<?php
if (isset($_POST['submitreg'])){
$username = mysqli_real_escape_string($conn, $_POST['username']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$sql = "INSERT INTO users (email, username, password) VALUES ('$email', '$username', '$password')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
header("Location: signin.php");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
mysqli_close($conn);
?>
And then i am inserting the code, i am getting this error:
Error: INSERT INTO users (email, username, password) VALUES ('gerulisjonas#gmail.com', 'jonas2422', 'password')
Thank you in advance :)
extra:
Form
<form id="register" class="signinform" action="includes/registerinc.php" method="post">
<div class="formcenter">
<input type="text" name="username" value="" placeholder="user name"><br>
<input type="email" name="email" value="" placeholder="email"><br>
<input type="password" id="passwordid" name="password" value="" placeholder="password"><br>
<input type="password" name="passwordtwo" value="" placeholder="repeat password"><br>
<input type="submit" name="submitreg" class="btn btn-success" value="Register"></input>
</div>
</form>
When creating your connection you named the variable that holds the database name $database, but when you pass it along to mysqli_connect you are using $register.
Try this instead:
$database = "register";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
Hey guys sorry I did bother you, i just run trough my code and i found that i did not included connection.php file in my register.php file
The reasons behind my needing this are complicated but I have a currently working HTML form that inserts a row into my MYSQL database. However... I need to combine the two separate processes into one HTML file but after many attempts at arranging the code cannot come to a working solution. Hopefully someone can point me in the right direction.
Here is the HTML file:
<form method="post" action="process.php">
<input type="text" name="id" placeholder="Enter ID" /><br />
<input type="hidden" name="user_text" id="hiddenField" value="x" /><br />
<input type="submit" value="Submit" />
</form>
Here is the related process.php file:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//mysql credentials
$mysql_host = "localhost";
$mysql_username = "*";
$mysql_password = "*";
$mysql_database = "*";
$u_name = $_POST["id"];
$u_text = $_POST["user_text"];
if (empty($u_name)){
die("Please enter your id");
}
//Open a new connection to the MySQL server
$mysqli = new mysqli($mysql_host, $mysql_username, $mysql_password, $mysql_database);
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$statement = $mysqli->prepare("INSERT INTO users_data (contractor_id, status) VALUES(?, ?)"); //prepare sql insert query
$statement->bind_param('ss', $u_name, $u_text); //bind values and execute insert query
}
?>
I know this isn't the right way to do things but it isn't for a public site, more a personal logging project. Thank you in advanced!
You can simply have a file like this:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
process();
}
else {
show_form();
}
function show_form () {
?>
<form method="post">
<input type="text" name="id" placeholder="Enter ID" /><br />
<input type="hidden" name="user_text" id="hiddenField" value="x" /><br />
<input type="submit" value="Submit" />
</form>
<?php
}
function process () {
//mysql credentials
$mysql_host = "localhost";
$mysql_username = "*";
$mysql_password = "*";
$mysql_database = "*";
$u_name = $_POST["id"];
$u_text = $_POST["user_text"];
if (empty($u_name)){
die("Please enter your id");
}
//Open a new connection to the MySQL server
$mysqli = new mysqli($mysql_host, $mysql_username, $mysql_password, $mysql_database);
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$statement = $mysqli->prepare("INSERT INTO users_data (contractor_id, status) VALUES(?, ?)"); //prepare sql insert query
$statement->bind_param('ss', $u_name, $u_text); //bind values and execute insert query
}
If you do not set theaction for form, by default, it submits to itself
I think I am successfully connecting to my database by:
<?php
$user = 'root';
$pass = '9KSroMDjEqNmEYY4';
$db = 'chatservice';
$host = '127.0.0.1';
$conn = new mysqli($host, $user, $pass, $db, 3306) or die("Unable to connect");
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
?>
My question is how I would use the registration code to successfully add a user to the database. When entering the form I press register I do not get any error messages stating that the registration didn't succeed. It seems that the php code is not being reached after the initial connection. I am new to php and mySQL so any tips on formatting would be nice too!
<?php
require('connect.php');
if(isset($_POST['user']) && isset($_POST['password'])){
$user = $_POST['user'];
$id = $_POST['IDNUM'];
$password = $_POST['password'];
$query = "INSERT INTO 'users' (user ,IDNUM ,password) VALUES('$user', '$id', '$password')";
$result = mysqli_query($query);
if($result){
$msg = "Registered Sussecfully";
echo $msg;
}
else
$msg = "Error Registering";
echo $msg;
}
?>
<div class="register-form">
<title>Chat Page Start</title>
<form action="" methods="POST">
<p>
<label>Username: </label>
<input id="user" type="text" name="user" placeholder="user" />
</p>
<p>
<label>ID: </label>
<input id="IDNUM" type="text" name="IDNUM" placeholder="ID number" />
</p>
<p>
<label>Password: </label>
<input id="password" type="password" name="password" placeholder="password" />
</p>
<a class="btn" href="login.php">Login</a>
<input class="btn register" type="submit" value="Register" />
</form>
</div>
Another thing is how would I check the status of my database connection and where I should be checking this status?
your database connection is mysqli_connect and you execute the query in mysql_query is not proper.
<?php
require('connect.php');
if(isset($_POST['user']) && isset($_POST['password'])){
$user = $_POST['user'];
$id = $_POST['IDNUM'];
$password = $_POST['password'];
$query = "INSERT INTO 'users' (user ,IDNUM ,password) VALUES('$user', ' $id ', '$password')";
$result = mysqli_query($query,$conn);
if($result){
$msg = "Registered Sussecfully";
}
else
$msg = "Error Registering";
}
?>
You are connecting database using mysqli:
$conn = new mysqli('localhost', $user, $pass, $db, 3306) or die("Unable to connect");
And executing query using mysql:
$query = "INSERT INTO 'users' (user ,IDNUM ,password) VALUES('$user', '$IDNUM', '$password')";
$result = mysql_query($query);
I tried changing the code to this so it connects to the DB before anything else but now it just lingers on verify.php, no redirect, no data being sent to DB.
<?php
if(isset($_POST['submit'])){
# connect to the database here
$host="XXXXXXX"; // Host name
$username="XXXX"; // Mysql username
$password="XXXX"; // Mysql password
$db_name="XXXX"; // Database name
mysql_connect("$host", "$username", "$password")or die("cannot connect for insert");
mysql_select_db("$db_name")or die("cannot select DB to insert data");
$user_name = mysql_real_escape_string($_POST['user_name']);
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$email = mysql_real_escape_string($_POST['email']);
$user_password = mysql_real_escape_string($_POST['password']);
$insert_query = "INSERT INTO teachers(`user_name`,`fname`,`lname`,`email`,`password`)
VALUES('".$user_name."$','".$fname."','".$lname."','".$email."','".$user_password."');";
mysql_query($insert_query) or die(mysql_error());
mysql_close();
};
?>
You should put or die(mysql_error()); in following line:
$sql = mysql_query($query) or die(mysql_error());
Instead of:
mysql_real_escape_string($_POST['password']))or die(mysql_error());
Another thing is that you have wrong if-else statements.
You code to check which field is empty should be in following if statement:
if($row||empty($_POST['user_name'])|| empty($_POST['fname'])||empty($_POST['lname'])|| empty($_POST['email'])||empty($_POST['password'])|| empty($_POST['re_password'])||$_POST['password']!=$_POST['re_password']){
# if a field is empty, or the passwords don't match make a message
# YOU SHOULD PUT YOUR CODE TO CHECK EMPTY FIELDS SEPARATELY HERE
}
else {
# If all fields are not empty, and the passwords match,
}
You should change your check if the user already exists to something like this:
if(count($row) > 0)
instead of just
if($row)
If you only want to test if data gets inserted limit you the code to this:
<?php
if(isset($_POST['submit'])){
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="lurnn"; // Database name
/* sanitize post variables */
$user_name = mysql_real_escape_string($_POST['user_name']);
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$email = mysql_real_escape_string($_POST['email']);
$user_password = mysql_real_escape_string($_POST['password']);
/* Database insert query */
mysql_connect($host, $username, $password)or die("cannot connect for insert");
mysql_select_db($db_name)or die("cannot select DB to insert data");
$insert_query = "INSERT INTO teachers(`user_name`,`f_name`,`l_name`,`email`,`password`)
VALUES('".$user_name."','".$fname."','".$lname."','".$email."','".$user_password."')";
mysql_query($insert_query) or die(mysql_error());
mysql_close();
};
?>
MYSQLI_ version:
<?php
if(isset($_POST['submit'])){
$host = "host";
$user = "user";
$password = "password";
$database = "database";
/* sanitize post variables */
$user_name = mysql_real_escape_string($_POST['user_name']);
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$email = mysql_real_escape_string($_POST['email']);
$user_password = mysql_real_escape_string($_POST['password']);
// open connection to database
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link){
echo ("Unable to connect to database!");
}
ELSE {
//INSERT VALUES INTO DATABASE
$query = "INSERT INTO teachers(`user_name`,`f_name`,`l_name`,`email`,`password`)
VALUES('".$user_name."','".$fname."','".$lname."','".$email."','".$user_password."')";
mysqli_query($link,$query) or die(mysql_error());
echo var_dump($query);
}
//close connection to database
mysqli_close($link);
};
?>
If this all fails try the following:
<?php
function submit_form(){
$host = "";
$user = "";
$password = "";
$database = "";
/* sanitize post variables */
$user_name = mysql_real_escape_string($_POST['user_name']);
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$email = mysql_real_escape_string($_POST['email']);
$user_password = mysql_real_escape_string($_POST['password']);
// open connection to database
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link){
echo ("Unable to connect to database!");
}
ELSE {
//INSERT VALUES INTO DATABASE
$query = "INSERT INTO teachers(`user_name`,`f_name`,`l_name`,`email`,`password`)
VALUES('".$user_name."','".$fname."','".$lname."','".$email."','".$user_password."')";
mysqli_query($link,$query) or die("Insert query failed");
echo var_dump($query);
}
//close connection to database
mysqli_close($link);
}
$form = <<<EODuserform
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Form</title>
</head>
<form action="{$_SERVER['PHP_SELF']}" method="POST" name="userform">
<label for='user_name'>Username:</label></br>
<input type="text" name="user_name" id="first" maxlength="25" tabindex='1' VALUE="user_name" /></br>
<label for='fname'>First Name:</label></br>
<input type="text" name="fname" id="first" maxlength="25" tabindex='2' VALUE="firstname" /></br>
<label for='lname'>Last Name:</label></br>
<input type="text" name="lname" id='lastname' maxlength="25" tabindex='3' VALUE="lastname" /></br>
<label for='email'>E-mail:</label></br>
<input type="text" name="email" id='email' maxlength="100" tabindex='4' VALUE="email" /></br>
<label for='password'>Password:</label></br>
<input type="password" name="password" id='password' maxlength="25" tabindex='5' VALUE="password" /></br>
<label for='re-password'>Re-type password:</label></br>
<input type="password" name="re-password" id='re-password' maxlength="25" tabindex='6' VALUE="re-password" /></br>
<input type="submit" name="submit" value="Sign Up" tabindex='6' />
</form>
</body>
</html>
EODuserform;
IF(!IsSet($_POST['submit'])){ // Check if form is not send, if not display empty form.
echo $form;
}
ELSE{
// in the case you want to send something to the database use
submit_form();
echo ('Thanks for submitting your form');
}
?>