I am trying to create a user profile registration for my site. The basics are already in place, where users can now signup and login to the site.
Each member receives a unique Member ID in the DB and after logging in they are given access to the page below. It is a simple form that loads data from the database as pre-filled values in the html form input fields. Changing this data and submit the data, stores the data correctly in the database. All thanks to examples and advice from experts at this site.
My question is how would I make the form to reload, or the fields to update with the new data from the DB without having to reload the page manually after clicking the submit button?
It would also be greatly appreciated with any feedback about the security of this form. I have tried to study mySQL PDO and prepared statements to avoid SQL injection but I feel that I have a long way to go before fully understand it all and make sure the site is secure.
<?php require('includes/config.php');
//Redirect to login page if not logged in
if(!$user->is_logged_in()){ header('Location: login.php'); }
//Get user profile data from DB
$sth= $db->query ("SELECT username, firstname, middlename, lastname, email FROM members");
$sth->bindColumn (1, $username);
$sth->bindColumn (2, $firstname);
$sth->bindColumn (3, $middlename);
$sth->bindColumn (4, $lastname);
$sth->bindColumn (5, $email);
while ($sth->fetch (PDO::FETCH_BOUND))
//Process form when submitted
if(isset($_POST['submit'])){
//if nothing is wrong, store data in DB
if(!isset($error)){
try {
//update user profile in database with a prepared statement
$sql = "UPDATE members SET username = :username,
firstname = :firstname,
middlename = :middlename,
lastname = :lastname,
email = :email
WHERE memberID = :memberID";
$stmt = $db->prepare($sql);
$stmt->bindParam(':username', $_POST['username'], PDO::PARAM_STR);
$stmt->bindParam(':firstname', $_POST['firstname'], PDO::PARAM_STR);
$stmt->bindParam(':middlename', $_POST['middlename'], PDO::PARAM_STR);
$stmt->bindParam(':lastname', $_POST['lastname'], PDO::PARAM_STR);
$stmt->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
$stmt->bindParam(':memberID', $_SESSION['memberID'], PDO::PARAM_STR);
$stmt->execute();
//catch error message if something is wrong
} catch(PDOException $e) {
$error[] = $e->getMessage();
}
}
}
//define page title
$title = 'Profile Registration';
//include member header
require('layout/header_member.php');
?>
<div class="container">
<h2>Please Register Your Profile</h2>
<p>Get started and register your profile below</p>
<p>Your member ID is: <?php echo $_SESSION['memberID']; ?> </p>
<?php
//show any error messages from the database here
if(isset($error)){
foreach($error as $error){
echo '<p class="bg-danger">'.$error.'</p>';
}
}
?>
</div>
<hr>
<div class="container">
<form class="form-horizontal" role="form" method="post" action="<? echo $_SERVER['PHP_SELF']; ?>">
<div class="form-group">
<label class="control-label col-sm-2" for="username">Display name</label>
<div class="col-sm-10">
<input type="text" required class="form-control" name="username" id="username" placeholder="Your Display Name" value="<?php if(isset($error)){ echo $_POST['username']; } ?><?php echo $username; ?>" >
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="firstname">First name</label>
<div class="col-sm-10">
<input type="text" required class="form-control" name="firstname" id="firstname" placeholder="Your first name" value="<?php if(isset($error)){ echo $_POST['firstname']; } ?><?php echo $firstname; ?>" >
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="middlename">Middle initials</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="middlename" id="middlename" placeholder="Middle initials" value="<?php if(isset($error)){ echo $_POST['middlename']; } ?><?php echo $middlename; ?>" >
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="lastname">Last name</label>
<div class="col-sm-10">
<input type="text" required class="form-control" name="lastname" id="lastname" placeholder="Your last name" value="<?php if(isset($error)){ echo $_POST['lastname']; } ?><?php echo $lastname; ?>" >
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="email">Email</label>
<div class="col-sm-10">
<input type="email" required class="form-control" name="email" id="email" placeholder="Your email address" value="<?php if(isset($error)){ echo $_POST['email']; } ?><?php echo $email; ?>" >
</div>
</div>
<button type="submit" name="submit" value="submit" class="btn btn-default">Submit</button>
</form>
</div>
<?php
//include footer
require('layout/footer.php');
?>
You can change the values of your HTML form to this:
value="<?php
if(isset($_POST['username'])) {
echo $_POST['username'];
} else {
echo $username;
} ?>"
The values submitted will show if the form failed (which you have used as $error) and also should the form successfully submit and update the database. In other words, it will always have either $username or the value that was last submitted in the form.
You could also look into "Sanitize filters" to filter away any unwanted characters that the user posts.
Related
please i'm kinda new to website development. i tried to create a registration page to work with my database but my registration form page is not responding to the php coding page.
please i need your assistance. thank
This is my registration.html page
i don't know if the error is from my registration form page
<form action="student.php" name="register" id="register" method="POST" data-aos="fade">
<div class="form-group row">
<div class="col-md-6 mb-3 mb-lg-0">
<input type="text" name="firstname" id="firstname" class="form-control" placeholder="First name" required>
</div>
<div class="col-md-6">
<input type="text" name="lastname" id="lastname" class="form-control" placeholder="Last name" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<input type="text" name="studentid" id="studentid" class="form-control" placeholder="Student ID" value="" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<input type="text" name="level" class="form-control" placeholder="Level" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<p class="mb-0">Gender</p>
<input name="gender" type="radio" value="m" required> Male
<input name="gender" type="radio" value="f" required> Female
</div>
</div>
<div class="form-group row">
<div id="date-picker" class="col-md-12 md-form md-outline input-with-post-icon datepicker" inline="true">
<input type="text" name="dob" class="form-control" id="date9" placeholder="DD/MM/YYYY" required>
<i class="fas fa-calendar input-prefix"></i>
</div>
</div>
<script>
$('.datepicker').datepicker({
inline: true;
});
</script>
<div class="form-group row">
<div class="col-md-12">
<input type="email" name="email" class="form-control" placeholder="Email" value="" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<input type="phone" name="phonenumber" id="phonenumber" class="form-control" placeholder="+234 8179 5523 71" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<input type="department" name="department" class="form-control" placeholder="Department" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<input type="password" name="password" value="" id="password" class="form-control" placeholder="Password" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<input type="password" name="confirmpassword" id="confirmpassword" value="" class="form-control" placeholder="Confirm Password" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-6">
<input type="submit" name="submit" class="btn btn-primary py-3 px-5 btn-block btn-pill" value="SUBMIT">
</div>
</div>
</form>
This is my Php page for the form
or maybe the error is from my php code. please help detect the problem guys. Thanks.
<?php
session_start();
// initializing variables
$studentid = "";
$email = "";
$errors = array();
// connect to the database
$db = mysqli_connect('localhost', 'root', '', 'oneschool');
// REGISTER USER
if (isset($_POST['submit'])) {
// receive all input values from the form
$firstname = mysqli_real_escape_string($db, $_POST['firstname']);
$lastname = mysqli_real_escape_string($db, $_POST['lastname']);
$studentid = mysqli_real_escape_string($db, $_POST['studentid']);
$level = mysqli_real_escape_string($db, $_POST['level']);
$gender = mysqli_real_escape_string($db, $_POST['gender']);
$dob = mysqli_real_escape_string($db, $_POST['dob']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$phonenumber = mysqli_real_escape_string($db, $_POST['phonenumber']);
$department = mysqli_real_escape_string($db, $_POST['department']);
$password_1 = mysqli_real_escape_string($db, $_POST['password']);
$password_2 = mysqli_real_escape_string($db, $_POST['confirmpassword']);
// form validation: ensure that the form is correctly filled ...
// by adding (array_push()) corresponding error unto $errors array
if (empty($studentid)) { array_push($errors, "Student ID is required"); }
if (empty($email)) { array_push($errors, "Email is required"); }
if (empty($password_1)) { array_push($errors, "Password is required"); }
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// first check the database to make sure
// a user does not already exist with the same username and/or email
$user_check_query = "SELECT * FROM student_registra WHERE studentid='$studentid' OR email='$email' LIMIT 1";
$result = mysqli_query($db, $user_check_query) or die(mysqli_error($db));
$user = mysqli_fetch_assoc($result);
if ($user) { // if user exists
if ($user['studentid'] === $studentid & $user['email'] === $email) {
array_push($errors, "Student Id already taken");
}
if ($user['email'] === $email) {
array_push($errors, "email already exists");
}
}
// Finally, register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
$query = "INSERT INTO student_registra (firstname, lastname, studentid, level, gender, dob, email, phonenumber, department, password)
VALUES('$firstname', '$lastname', '$studentid', '$level', '$gender', '$dob', '$email', '$phonenumber', '$department', '$password')";
mysqli_query($db, $query);
$_SESSION['studentid'] = $studentid;
$_SESSION['success'] = "Registration Sucessful";
header('location: index.html');
}
}
i don't know what seems to be the problem, because i run it the first time it worked, but when i shutdown my laptop and turn it on back again after my lunch, it stop working.
Instead of it to read the .php code it's rather displaying the whole .php code and i've checked the code, i can't find what seems to be the problem.
please guys, i'll need your help in fixing this or detecting the problem.
thanks
EDIT, You have a lot of useless codes that make your code so slow, Like $_SESSION['success']; This is not neccessary, Change your index.html to index.php and delete it because it do nothing, You can check session by student id You have two gender Inputs, how comes you assign one of them? This is first mistake
Secondly, Use Prepared Statements to avoid SQLI Attacks
Thirdly How comes you header a html page when you're in php page? change index.html to index.php
And Use this code instead:
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
$prepared = "INSERT INTO student_registra (firstname, lastname, studentid, level, gender, dob, email, phonenumber, department, password)
VALUES('$firstname', '$lastname', '$studentid', '$level', '$gender', '$dob', '$email', '$phonenumber', '$department', '$password')";
$query = $prepared;
mysqli_query($db, $query);
$_SESSION['studentid'] = $studentid;
# Change your files index.html To index.php
header('location: index.php');
}
I am aware there are a lot of questions on this regarding this issue, but I have looked through them all and none of the solutions seem to fix the issue for me. I have a form that when submitted, posts the data and it is retrieved via if(isset), as far as I know, all the syntax is correct, and the name attributes of the inputs are correct.
When I submit the form, the data in the form gets inserted into a mysql database, which works, the only issue is the blank page. Here is the php code at the top of the page and the relative html code.
PHP
<?php
require('connection.php');
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$number = $_POST['number'];
$body = $_POST['message'];
try {
$stmt = $db->prepare("INSERT INTO `contact` (`c_name`, `c_email`, `c_number`, `c_body`) VALUES (:name, :email, :num, :body)");
$stmt->execute(array(':name' => $name, ':email' => $email, ':num' => $number, ':body' => $body));
return $stmt;
} catch(PDOException $e) {
echo $e->getMessage();
}
}
?>
HTML
<form method="post">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" name="name" class="form-control" id="name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" name="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="text" name="number" class="form-control" id="number">
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea name="message" class="form-control" id="message" rows="6"></textarea>
</div>
<input type="submit" name="submit" class="btn btn-primary" />
</form>
I'm currently trying to complete this project for school and I would really appreciate some help.
I have been trying to learn PHP so I could extract data from my HTML and put it into my MySQL (which I'm accessing through XAMP). I have a problem that says:
The requested URL was not found on this server.
The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.
If you think this is a server error, please contact the webmaster.' when I press the register button. I don't know what this means? I have a table called usertable in the database Login so I feel like it should work.
This is my PHP code:
<?php
session_start();
$con = mysqli_connect('localhost', 'root', 'ocr2020');
mysqli_select_db($con, 'login');
$name = $_POST['user'];
$pass = $_POST['pass'];
$fname= $_POST['forename'];
$sname = $_POST['surname'];
$mobile = $_POST['mobile'];
$email = $_POST['email'];
$dateofB= $_POST['dateB'];
$s= "select * from usertable where name='$name'";
$s2= "select * from usertable";
$result= mysqli_query($con,$s);
$num= mysqli_num_rows($result);
$num2= mysqli_num_rows($s2);
$id= $num2+1;
if($num==1){
echo" Username Is No Longer Available";
}else{
$reg= " insert into usertable(patientID, Forename, Surname, Username, Password, Email, Mobile,
DateOfBirth) values ('$id', '$fname', '$sname', '$name', '$pass', '$email', '$mobile', '$dateOfB')";
mysqli_query($con, $reg);
echo" Registration Successful";
}
?>
As I said, I would really appreciate any help or advice. Thanks!
Edit:
Here is the updated code having taken on everyone's comments:
<?php
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);.
session_start();
$con = mysqli_connect('localhost', 'root', 'ocr2020');
mysqli_select_db($con, 'login');
$name = $_POST['user'];
$pass = $_POST['pass'];
$fname= $_POST['forename'];
$sname = $_POST['surname'];
$mobile = $_POST['mobile'];
$email = $_POST['email'];
$dateofB= $_POST['dateB'];
$s= "select * from usertable where name='$name'";
$result= mysqli_query($con,$s);
$num= mysqli_num_rows($result);
if($num>0){
echo" Username Is No Longer Available";
}else{
$reg= " insert into usertable(patientID, Forename, Surname, Username, Password, Email, Mobile, DateOfBirth) values ('$id', '$fname', '$sname', '$name', '$pass', '$email', '$mobile', '$dateOfB')";
mysqli_query($con, $reg);
echo" Registration Successful";
}
?>
Here is the code from the login.php page which is where I press the 'register button' and it creates the problem:
<html>
<section id="loginBox">
<div class="container">
<div class="login-box">
<div class="row">
<div class="col-md-6 login-left">
<h3> Login Here </h3>
<form action="registration.php" method="POST">
<div class="form-group">
<label> Username </label>
<input type="text" name="user" placeholder="Enter your username" class="form-control" required>
</div>
<div class="form-group">
<label> Password </label>
<input type="password" name="password" placeholder="Enter your password" class="form-control" required>
</div>
<button type="submit" class="btn btn-primary"> Login </button>
</form>
</div>
<div class="col-md-6 login-right">
<h3> Register Here </h3>
<form action="validation.php" method="POST">
<div class="form-group">
<label> Username </label>
<input type="text" name="user" placeholder="Enter your username" class="form-control" required>
</div>
<div class="form-group">
<label> Password </label>
<input type="password" name="password" placeholder="Enter your password" class="form-control" required>
</div>
<div class="form-group">
<label> Forename </label>
<input type="text" name="forename" placeholder="Enter your forename" class="form-control" required>
</div>
<div class="form-group">
<label> Surname </label>
<input type="text" name="surname" placeholder="Enter your surname" class="form-control" required>
</div>
<div class="form-group">
<label> Mobile</label>
<input type="text" name="mobile" placeholder="Enter your mobile" class="form-control" required>
</div>
<div class="form-group">
<label> Email </label>
<input type="text" name="email" placeholder="Enter your email" class="form-control" required>
</div>
<div class="form-group">
<label> Date of Birth</label>
<input type="date" name="dateB" placeholder="Enter your date of birth" class="form-control" required>
</div>
<button type="submit" class="btn btn-primary"> Register </button>
</form>
</div>
</div>
</div>
</div>
</section>
</body>
</html>
I am new at this and still learning. I have a search page and want to use the input to search a mysql table and display results in a form to update the record back into the table.
Every time I try and run it I get a PHP Notice: Undefined variable: password in /var/www/html/update.php on line 106, referer: http://172.20.10.161/search.php
in the error_log.
All help would be most appreciated.
I have google and tried various methods to get this right, i feel there is some little thing I am missing here.
Below is the code from my search.php page
<?php
session_start();
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
header("location: login.php");
exit;
}
?>
<form action="update.php" method="post">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" value="">
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Search">
</div>
</form>
Then on my page that should show the results if have the following.
update.php
top of page
<?php
session_start();
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
header("location: login.php");
exit;
}
?>
Code in page to run query
<?php
require_once "include/dbconf.php";
if(isset($_POST['Search']))
{
$name=$_POST['name'];
$sql = "SELECT (name, surname, email, username, password) from net_users WHERE name LIKE '%".$name."%'";
$result = mysqli_query($link, $sql) or die ('Something went wrong');
while($row=mysqli_fetch_array($result))
{
$username =$row['username'];
$password =$row['password'];
$name =$row['name'];
$surname =$row['surname'];
$email =$row['email'];
}
}
mysqli_close($link);
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" value="<?php echo $name; ?>">
</div>
<div class="form-group">
<label>Surname</label>
<input type="text" name="surname" class="form-control" value="<?php echo $surname; ?>">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" value="<?php echo $email; ?>">
</div>
<div class="form-group">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
</div>
<div class="form-group">
<label>Password</label>
<input type="text" name="password" class="form-control" value="<?php echo $password; ?>">
/div>
<div class="form-group">
<input type="update" class="btn btn-primary" value="update">
</div>
</form>
I am hoping to pull the desired input on search $name to search the mysql db and return the results in the form on the update page to update the information back into the database.
I would recommend a couple of changes to update.php.
<?php
session_start();
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
// Can everyone logged in update the system. If not, filter it as required
header("location: login.php");
exit;
}
?>
Given the following connection file dbconf.php with a procedual MySQLi - https://www.php.net/manual/en/mysqli.quickstart.dual-interface.php
<?php
/*
Database credentials.
Assuming you are running MySQL server with default setting (user 'root' with no password)
*/
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'xxxxxxxx');
define('DB_PASSWORD', '**********');
define('DB_NAME', 'users');
/* Attempt to connect to MySQL database */
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check connection
if($link === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
The search query will need to account for SQL Injection - How can I prevent SQL injection in PHP?.
<?php
require_once "include/dbconf.php";
// placeholder for the returned data
$data = array();
// Verify the search query is present
// Or handle empty
if(isset($_POST['name']))
{
// SQL injection - https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php
$name=$_POST['name'];
// TODO: Verify that you need the password here
// Generally passwords are not to be stored as plain text
$sql = "SELECT (id, name, surname, email, username, password) from net_users WHERE name LIKE '?'";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($stmt, 's', $name);
// Execute the query
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
// Copy the result to a local array
// Each entry in $data will be an associative array of values
$data[] = $row;
}
} else {
// TODO : Handle this more gracefully
die('Search query missing');
}
mysqli_close($link);
if (empty($data))
{
// TODO: No records matched, handle gracefully
die('No records matched');
}
?>
Once you have the data, output as needed. Note that I have also selected id column - As all other fields are updateable, it would not be possible to identify the record if all the fields are changed. To work around this, you need a value that will always identify the record being updated. I have chosen the id column, but any other unique - non-updateable field would do.
<?php
foreach($data as $record)
{
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<input type="hidden" name="id" value="<?php echo $record['id']; ?>" />
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" value="<?php echo $record['name']; ?>">
</div>
<div class="form-group">
<label>Surname</label>
<input type="text" name="surname" class="form-control" value="<?php echo $record['surname']; ?>">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" value="<?php echo $record['email']; ?>">
</div>
<div class="form-group">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $record['username']; ?>">
</div>
<div class="form-group">
<label>Password</label>
<input type="text" name="password" class="form-control" value="<?php echo $record['password']; ?>">
/div>
<div class="form-group">
<input type="update" class="btn btn-primary" value="update">
</div>
</form>
<?php
}
?>
I want show message about existing username under username input tag and when show the message other the data doesn't lose. But this codes don't work.
Here is my code for existing username:
<?php
//click register button
if(isset($_POST['register']))
{
//Retrieve the field values from our registration form.
$username = $_POST['username'];
//Now, we need to check if the supplied username already exists.
$sql = "SELECT COUNT(user_username) AS num FROM users WHERE user_username = :username";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['num'] > 0){
echo "<script>";
echo "$(document).ready(function(){document.getElementById('existing_username').innerHTML = 'existing'})";
echo "</script> ";
//the following code is work but other data like name, password is lost in input element
//echo '<div class="alert alert-danger"> <b>'.$username.'</b> This username already exist!</div>';
} }
?>
And here is my code for input data:
<form action="register.php" method="post">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="username"><b>USERNAME</b></label>
<input class="form-control" type="text" id="username" name="username">
</div>
</div>
</div>
<span class="text-danger" id="existing_username"></span>
<button class="btn btn-primary" type="submit" name="register" value="Register">Register</button>
</form>
when show the message other the data doesn't lose
What data?!
ok,so you should store the error message which is Username exist in a variable,like below :
<?php
//click register button
if(isset($_POST['register']))
{
//Retrieve the field values from our registration form.
$username = $_POST['username'];
//Now, we need to check if the supplied username already exists.
$sql = "SELECT COUNT(user_username) AS num FROM users WHERE user_username = :username";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['num'] > 0){
echo "<script>";
echo "$(document).ready(function(){document.getElementById('existing_username').innerHTML = 'existing'})";
echo "</script> ";
$error = "<b>".$username."</b> :This username already exist!";
//this code is work but other data is lost
} }
?>
<form action="register.php" method="post">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="username"><b>USERNAME</b></label>
<input class="form-control" type="text" id="username" name="username">
</div>
</div>
</div>
</form>
Check this answers too Embed Php in Html
You need to provide value attribute for your form fields. For example:
<input class="form-control" type="text" id="username" name="username" value="<?php echo $username ?>">
OR
<input class="form-control" type="text" id="name" name="name" value="<?php echo $name ?>">
etc.
Of course you need to define these variables in you code first. If form have been submitted - take them from $_POST. If not - set them as empty values.
Code example with 2 fields:
<?php
$name = null;
$username = null;
//click register button
if (isset($_POST['register'])) {
//Retrieve the field values from our registration form.
$name = $_POST['name'];
$username = $_POST['username'];
//Now, we need to check if the supplied username already exists.
$sql = "SELECT COUNT(user_username) AS num FROM users WHERE user_username = :username";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row['num'] > 0) {
echo "<script>";
echo "$(document).ready(function(){document.getElementById('existing_username').innerHTML = 'existing'})";
echo "</script> ";
$error = "<b>".$username."</b> :This username already exist!";
//this code is work but other data is lost
}
}
?>
<form action="register.php" method="post">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="name"><b>NAME</b></label>
<input class="form-control" type="text" id="name" name="name" value="<?php echo $name ?>">
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="username"><b>USERNAME</b></label>
<input class="form-control" type="text" id="username" name="username" value="<?php echo $username ?>">
</div>
</div>
</div>
<span class="text-danger" id="existing_username"></span>
<button class="btn btn-primary" type="submit" name="register" value="Register">Register</button>
</form>