mysqli_real_escape_string() expects parameter 1 to be mysqli - php

Here is my complete code....
Connect.php
$connect = #mysql_connect ($host, $username, $password, $db_name) or die ('error');
$select = #mysql_select_db($db_name, $connect) or die('check');
password .php
//forgot password update
include('C:\wamp\www\header.html');
//check if form has been submitted
include('C:\wamp\www\connect.php');
//connecting to db
$errors = array();
if(isset($_POST['submitted'])) {
if (empty($_POST['username']))
{
$errors[]='Please enter a username.';
}
else
{
$u = mysqli_real_escape_string($connect,trim($_POST['username']));
}
//check for current password
if (empty($_POST['password']))
{
$errors[]='Current password does not match.';
}
else
{
$p = mysqli_real_escape_string($connect,trim($_POST['password']));
}
//check for a new password and match with confirm pass.
if(!empty($_POST['password1']))
{
if($_POST['password1'] != $_POST['cpass'])
{
$errors[] = 'The entered password and confirm password do not match.';
}
else
{
$np = mysqli_real_escape_string($connect,trim($_POST['password1']));
}
}
if(empty($errors)){
//if everything is fine.
//verify the entered email address and password.
$q="SELECT username FROM users WHERE (username='$u' AND password=SHA1('$p'))";
$r=#mysqli_query($connect,$q);
$num = #mysqli_num_rows($r);
if($num==1)
//if it matches.
//get user id
{
$row=mysqli_fetch_array($r, MYSQLI_NUM);
//udpdate query.
$q="UPDATE users SET password= SHA1('$np') WHERE username=$row[0]";
$r=#mysqli_query($connect, $q);
if (mysqli_affected_rows($connect) ==1)
{
echo '<h3>Your password has been updated.</h3>';
}
else {
echo '<h3>Whops! Your password cannot be changed due a system error. Try again later. Sorry</h3>';
echo '<p>' .mysqli_error($connect). 'Query:' . $q.'</p>';
}
exit();
}
else
{
//invalid email and password
echo 'The entered username and password do not match.';
}
}
else
{
//report the errors.
echo '<h1> Err... </h1>
<p> The following error(s) have occured</p>';
foreach ($errors as $msg)
{
echo "--$msg<br />\n";
}
echo '</p><p>Please Try Again.</p><p><br/></p>';
}
mysqli_close($connect);
}
?>
<html>
<head></head>
<body>
<div id="container">
<h1>Change your password</h1>
<form action="password.php" method="post">
Username:<br>
<input type="text" name="username" size="20" maxlength="80" />
<br>
Current Password<br/>
<input type="password" name="password" />
<br/>
New Password<br/>
<input type="password" name="password1" />
<br/>
Confirm New Password<br/>
<input type="password" name="cpass" />
<br/>
<input type="submit" name="submit" value="Change Password"/>
<input type="hidden" name="submitted" value="TRUE"/>
</form>
</div>
<?php
include('C:\wamp\www\footer.html');
?>

http://www.php.net/manual/en/mysqli.real-escape-string.php
mysqli_real_escape_string
Parameters
link
Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()
escapestr
The string to be escaped.
Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.
The first parameter must be a link identifier and not a string containing the DB name as it seems to be.

first parameter must be a link identifier, a value returned by http://www.php.net/manual/en/function.mysqli-connect.php or http://www.php.net/manual/en/mysqli.init.php
Blockquote

Related

PHP - the form values cannot be passed correctly

At first, I apologize for the mess of code.
I am new to PHP and I was watching a video and practicing update the password and confirmation. I was able to pass the e-mail validation(empty), however once I tried to submit password and new password along with, it kept showing that I did not fill in the password and the new password.
Could someone help me to review my code? Thank you very much.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
include ('connection.php');
$errors = array();
if (empty($_POST['email']))
{
$errors[] = 'Require your email! ';
}
else
{
$e = mysqli_real_escape_string($dbc, trim($_POST['email']));
}
if (empty($_POST['password']))
{
$errors[] = 'Require your password!';
}
else
{
$p = mysqli_real_escape_string($dbc, trim($_POST['password']));
}
if (!empty($_POST['newpass']))
{
if ($_POST['newpass'] != $_POST['conpass'])
{
$errors[] = "Your new password does not match the confirmed password!";
}
else
{
$np = mysqli_real_escape_string($dbc, trim($_POST['newpass']));
}
}
else
{
$errors[] = 'You forgot to enter your new password!';
}
if(empty($errors))
{
$q = "SELECT id FROM users WHERE (email='$e' AND password='$p')";
$r = mysqli_query($dbc, $q);
$num = mysqli_num_rows($r);
if($num == 1)
{
$row = mysqli_fetch_array($r, MYSQLI_NUM);
$q = "UPDATE users SET password='$np' WHERE id = '$row[0]'";
$r = mysqli_query($dbc, $q);
if (mysqli_affected_rows($dbc) == 1 )
{
echo "You have succesfully update your password.";
}
else
{
echo "Your password could not be changed due to a system error, please try again.";
}
mysqli_close($dbc);
}
else
{
echo "The Email and the password were in correct.";
}
}
else
{
echo "Error! The following error(s) occured: <br />";
foreach($errors as $msg)
{
echo $msg."<br />";
}
}
}
?>
<h1>Change Password</h1>
<form action="update.php" method="post">
<p>Email: <input type="text" name="email" size="20" maxlenght="30" value="<?php if(isset($_POST['email'])){echo $_POST['email'];} ?>" /></p>
<p>Current Password: <input type="password" name"password" size="20" maxlength="30" value="<?php if(isset($_POST['password'])){echo $_POST['password'];} ?>" /></p>
<p>New Password: <input type="password" name"newpass" size="20" maxlength="30" value="<?php if(isset($_POST['newpass'])){echo $_POST['newpass'];} ?>" /></p>
<p>Confirm Password: <input type="password" name"conpass" size="20" maxlength="30" value="<?php if(isset($_POST['conpass'])){echo $_POST['conpass'];} ?>" /></p>
<p><input type="submit" name="submit" value="Change Password" /></p>
</form>
You have syntax errors in your HTML code.
You missed = signs at these lines:
<input type="password" name"password" ...
should be <input type="password" name = "password"
<input type="password" name"newpass" ...
should be <input type="password" name = "password"
<input type="password" name"conpass" ...
should be <input type="password" name = "conpass"
The name tag is important for GET and POST methods. Thats what allows data to be sent from the input fields to the server.
OK, here is updated version of your code:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
include ('connection.php');
$errors = array();
$email=trim($_POST['email']);
$password=trim($_POST['password']);
$newpass=trim($_POST['newpass']);
$conpass=trim($_POST['conpass']);
if (empty($email)) {
$errors[] = 'Require your email! ';
} else {
$e = mysqli_real_escape_string($dbc, $email);
}
if (empty($password)) {
$errors[] = 'Require your password!';
} else {
$p = mysqli_real_escape_string($dbc, $password);
}
if (!empty($newpass)) {
if ($newpass != $conpass){
$errors[] = "Your new password does not match the confirmed password!";
} else {
$np = mysqli_real_escape_string($dbc, $newpass));
}
} else {
$errors[] = 'You forgot to enter your new password!';
}
if(empty($errors)){
$q = "SELECT `id` FROM `users` WHERE (`email` LIKE '$e' AND `password` LIKE '$p') LIMIT 0, 1";
$r = mysqli_query($dbc, $q);
$num = mysqli_num_rows($r);
if($num == 1){
$row = mysqli_fetch_array($r, MYSQLI_NUM);
$q = "UPDATE `users` SET `password` LIKE '$np' WHERE `id = '$row[0]'";
$r = mysqli_query($dbc, $q);
if (mysqli_affected_rows($dbc) == 1 ){
echo "You have succesfully update your password.";
} else {
echo "Your password could not be changed due to a system error, please try again.";
}
mysqli_close($dbc);
} else {
echo "The Email and the password were in correct.";
}
} else {
echo "Error! The following error(s) occured: <br />";
foreach($errors as $msg){
echo $msg."<br />";
}
}
}
First before empty() check you need to trim() POST's, Also in MySQL query strings you need to search with LIKE for password and email, not = becouse that is string not integer.
Also:
<p>Email: <input type="text" name="email" size="20" maxlenght="30" value="<?php if(isset($_POST['email'])){echo $_POST['email'];} ?>" /></p>
<p>Current Password: <input type="password" name="password" size="20" maxlength="30" value="<?php if(isset($_POST['password'])){echo $_POST['password'];} ?>" /></p>
<p>New Password: <input type="password" name="newpass" size="20" maxlength="30" value="<?php if(isset($_POST['newpass'])){echo $_POST['newpass'];} ?>" /></p>
<p>Confirm Password: <input type="password" name="conpass" size="20" maxlength="30" value="<?php if(isset($_POST['conpass'])){echo $_POST['conpass'];} ?>" /></p>
<p><input type="submit" name="submit" value="Change Password" /></p>
You forgot to put = after name attributes.

PHP and MySQL, issue with form token

I am new to PHP and trying to implement a method by which a user can be added to the database, I am following a tutorial and before I went to work, it was working fine, but now, it is stopping at this statement:
//Check the form token is valid
else if($_POST['formToken'] != $_SESSION['formToken'])
{
$message = 'Invalid form submission';
}
Is there something I'm missing? Full code:
AddUser.php
<?php
//Begin our session
session_start();
//set a form token
$formToken = md5( uniqid('auth', true) );
//set the session form token
$_SESSION['formToken'] = $formToken;
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Add User</h2>
<form action="addUserSubmit.php" method="post">
<fieldset>
<p>
<label for="Username">Username</label>
<input tupe="text" id="Username" name="Username" value="" maxlength="20" />
</p>
<p>
<label for="Password">Password</label>
<input tupe="text" id="Password" name="Password" value="" maxlength="20" />
</p>
<p>
<input type="hidden" name="formToken" vale="<?php echo $formToken; ?>" />
<input type="submit" value="$rarr; Login" />
</p>
</fieldset>
</form>
</body>
</html>
addUserSubmit.php
<?php
//begin our session
session_start();
//Check if username, password and form token have been sent
if(!isset($_POST['Username'], $_POST['Password'], $_POST['formToken']))
{
$message = 'Please enter a valid username and password';
}
//Check the form token is valid
else if($_POST['formToken'] != $_SESSION['formToken'])
{
$message = 'Invalid form submission';
}
//Check the username is the correct length
else if (strlen($_POST['Username']) > 20 || strlen($_POST['Usernamw']) < 4)
{
$message = 'Incorrect Username lenght, please try again';
}
//Check the username only has alpha numeric characters
else if (ctype_alnum($_POST['Username']) != true)
{
$message = "Username must be alpha numeric";
}
else if (ctype_alnum($_POST['Password']) != true)
{
$message = "Password must be alpha numeric";
}
else
{
//Enter the data into the database
$username = filter_var($_POST['Username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['Password'], FILTER_SANITIZE_STRING);
//Encrypt the password
$password = shal($password);
//Connect to the database
$SQLusername = "name";
$SQLpassword = "password";
$SQLhostname = "localhost";
$databaseName = "jfitness";
try
{
//connection to the database
$dbhandle = mysql_connect($SQLusername, $SQLpassword, $SQLhostname)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db($databaseName, $dbhandle)
or die("Could not select database");
$sql = "INSERT INTO
customers (Username, Password)
VALUES
('$_POST[$username]','$_POST[$password]')";
if(!mysql_query($sql, $dbhandle))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
//close the connection
mysql_close($dbhandle);
}
catch (Exception $ex)
{
}
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<p><?php echo $message; ?>
</body>
</html>
There is a typo I think.. Try changing,
<input type="hidden" name="formToken" vale="<?php echo $formToken; ?>" />
to:
<input type="hidden" name="formToken" value="<?php echo $formToken; ?>" />

How to check user already present in database change the username

// php code start------------->
<?php
// define variables and set to empty values
$nameErr=$empidErr=$usernameErr=$passwordErr="";
$name=$empid=$username=$password="";
if(isset($_POST['submit']))
{
if (empty($_POST["empid"])) {
$empid = "";
} else {
$empid = test_input($_POST["empid"]);
}
if (empty($_POST["name"])) {
$name = "";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["etype"])) {
$etype = "";
} else {
$etype = test_input($_POST["etype"]);
}
if (empty($_POST["username"])) {
$usernameErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
// check if name only contains letters and whitespace
if (!preg_match("/[0-9A-Za-z ^-_#. ]*$/",$username)) {
$usernameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password = test_input($_POST["password"]);
// check if name only contains letters and whitespace
if (!preg_match("/[0-9A-Za-z ^-_#. ]*$/",$password)) {
$passwordErr = "Only letters and white space allowed";
}
}
}
//collect the data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if((strlen($name)>0)&&(strlen($empid)>0)&&(strlen($etype)>0)&&(strlen($username)>0)&&(strlen($password)>0))
{
include "connection.php";
//Here to check the username is aleady present in database or not
$query = mysql_query("SELECT * FROM signin WHERE username='$username' ", $con);
//$result = mysql_query($query) or die('Error: ' . mysqli_error($con));
if (mysql_num_rows($query) <=0)
{
echo "<script>alert('User already Exists Change the username');</script>";
echo"<script>window.location.href = 'signin.php';</script>";
}
else
{
//if not present in database then create the new user in database.
$sql="INSERT INTO signin (emp_name,emp_id,emp_type,username,password,create_datetime)
VALUES ('$name','$empid','$etype','$username','$password',now())";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "<script>alert('New User Added Successfully');</script>";
echo"<script>window.location.href = 'login.php';</script>";
}
mysqli_close($con);
}
?>
//php code end------------<
//html code------------------>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<legend> <b><i> Information</i></b></legend><br>
Employee ID:-<input type="text" name="empid" placeholder="Enter Employee ID" size="10" value="<?php echo $rum1?>" readonly>
Employee Name:-<input type="text" name="name" placeholder="Surname Middlename Father Name" size="50" value="<?php echo $rum2;?>" readonly>
Employee Type:-<input type="text" name="etype" placeholder="Type" value="<?php echo $rum3;?>" readonly><br /><br />
Username:-<input type="text" name="username" id="loginid" placeholder="Username" size="30" value="<?php echo $unm;?>">
<span class="error">* <?php echo $usernameErr;?></span> <br /><br />
Password:-<input type="password" id="password" name="password" size="30">
<span class="error">* <?php echo $passwordErr;?></span> <br />
</fieldset>
<br>
<input name="submit" type="submit" value="Submit">
<input name="reset" type="submit" value="Reset">
<br ><br >
</form>
</fieldset>
</body>
</html>
//html code end---------------------<
In above php code is work but i want to check username.if the username present in the database then give the alert as the user is already present in the database change the username please. So please sir or madam suggest any code or changes in this php code and suggest any solution to check the user present in database or not.if user first time register then new user is added and if user multiple second time register then give alert is user already register please do your login.
to know if present mysql_num_rows should return 1 or special cases more than one
so change this
if (mysql_num_rows($query) <=0)
{
echo "<script>alert('User already Exists Change the username');</script>";
echo"<script>window.location.href = 'signin.php';</script>";
}
To this
if (mysql_num_rows($query) >0)
{
echo "<script>alert('User already Exists Change the username');</script>";
echo"<script>window.location.href = 'signin.php';</script>";
}
Dont use mysql function as they are depriciated. Learn mysqli or PDO

PHP MySQL form insertion query

I am working on this registration system where I have a captcha control at the end. I have error reporting included, no error appears. Output page says capcha successfull. While I can see in DB no data being inserted..
Form:
<h2>Registration Form</h2>
Username:<input type="text" name="username" id="username" size="5" class="username" />
Password:<input type="password" name="password1" id="password" />
Repeat Password:<input type="password" name="password2" id="password" />
Full Name:<input type="text" name="name" id="username" class="username" / >
Mobile/Phone:<input type="text" name="phone" id="username" class="username" />
Email Address:<input type="text" name="email" id="username" class="username" />
<img src="captcha.php"><input type="text" name="vercode" />
<input type="submit" name="register" id="button" value="Sign Up" />
PHP:
include 'db_connect.php';
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password1 = $_POST['password1'];
$password2 = $_POST['password2'];
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
if ($username=='')
{
echo 'Please choose an username for yourself.';
exit();
}
if ($password1=='')
{
echo 'Oops, looks like you forgot to enter the password. Please enter the password.';
exit();
}
if ($password2=='')
{
echo 'Oops, looks like you forgot to re-enter the password. Please enter the password.>';
exit();
}
if ($name=='')
{
echo 'Please enter your first and the last name.';
exit();
}
if ($phone=='')
{
echo 'Please enter your house phone or mobile number.';
exit();
}
if ($email=='')
{
echo 'Please enter your email address.';
exit();
}
//duplicate Entry Validation
$check_email = "SELECT * FROM users WHERE email='$email'";
$run = mysql_query($check_email);
if(mysql_num_rows($run)>0) {
echo "Alert('Email $email already exist in our database!)";
exit();
}
//Data Insertion
$query = "insert into users (username,password,name,phone,email) value ('$username','$password1','$name','$phone','$email')";
if(mysql_query($query)) {
echo "Registration Successfull";
}
}
//Captcha Validation
if ($_POST["vercode"] != $_SESSION["vercode"] OR $_SESSION["vercode"]=='') {
echo '<strong>Incorrect Captcha Code Entered.</strong>';
} else {
echo '<strong>Captcha Verification successful.</strong>';
};
?>
MySQL is deprecated already, you should use MySQLi instead. Try this:
PHP:
<?php
/* ESTABLISH CONNECTION */
session_start();
$con=mysqli_connect("YouHost","YouUsername","YourPassword","YourDatabase");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
if (isset($_POST['register'])) { /* THIS SHOULD BE register, BECAUSE YOU NAMED YOUR SUBMIT BUTTON register, NOT submit */
$username = mysqli_real_escape_string($con,$_POST['username']);
$password1 = mysqli_real_escape_string($con,$_POST['password1']);
$password2 = mysqli_real_escape_string($con,$_POST['password2']);
$name = mysqli_real_escape_string($con,$_POST['name']);
$phone = mysqli_real_escape_string($con,$_POST['phone']);
$email = mysqli_real_escape_string($con,$_POST['email']);
/* YOU SHOULD PRACTICE USING ESCAPE_STRING TO PREVENT SOME OF SQL INJECTIONS */
if (empty($username))
{
echo 'Please choose a username for yourself.';
exit();
}
if (empty($password1))
{
echo 'Oops, looks like you forgot to enter the password. Please enter the password.';
exit();
}
if (empty($password2))
{
echo 'Oops, looks like you forgot to re-enter the password. Please enter the password.>';
exit();
}
if (empty($name))
{
echo 'Please enter your first and the last name.';
exit();
}
if (empty($phone))
{
echo 'Please enter your house phone or mobile number.';
exit();
}
if (empty($email))
{
echo 'Please enter your email address.';
exit();
}
/* duplicate Entry Validation */
$check_email = "SELECT * FROM users WHERE email='$email'";
$run = mysqli_query($con,$check_email);
if(mysqli_num_rows($run)>0) {
echo "Alert('Email $email already exist in our database!)";
exit();
}
/* Data Insertion. YOU SHOULD ALSO CONSIDER IF THE PASSWORD 1 AND 2 ARE THE SAME */
if($password1==$password2 && !empty($username) && !empty($name) && !empty($phone) && !empty($email)){ /* IF PASSWORD1 IS THE SAME WITH PASSWORD2 */
/* INSERT QUERY */
$query = mysqli_query($con,"INSERT INTO users (username,password,name,phone,email) VALUES ('$username','$password1','$name','$phone','$email')");
echo "Registration Successfull";
} /* END OF IF PASSWORD1 IS EQUALS TO PASSWORD2 */
else {
echo "Alert('Password is not the same.')";
exit();
}
/* Captcha Validation */
if ($_POST["vercode"] != $_SESSION["vercode"] OR $_SESSION["vercode"]=='') {
echo '<strong>Incorrect Captcha Code Entered.</strong>';
} else {
echo '<strong>Captcha Verification successful.</strong>';
};
} /* END OF ISSET SUBMIT */
?>
Your HTML file:
<html>
<body>
<h2>Registration Form</h2>
<form action='YourPHPFile' method='POST'>
Username:<input type="text" name="username" id="username" size="5" class="username" />
Password:<input type="password" name="password1" id="password" />
Repeat Password:<input type="password" name="password2" id="password" />
Full Name:<input type="text" name="name" id="username" class="username" / >
Mobile/Phone:<input type="text" name="phone" id="username" class="username" />
Email Address:<input type="text" name="email" id="username" class="username" />
<img src="captcha.php"><input type="text" name="vercode" />
<input type="submit" name="register" id="button" value="Sign Up" />
</form>
</body>
</html>

inserting data into mysql from an html textboxes. using php/mysql

I can't see where i am going wrong, it just won't let me connect to the mysql database and i only get error message when trying to save details.?????? i think there may be a problem where it shows $sql for inserting the values into the table. the first part newstudent.php works, but sql.php does not work.
//new student.php
<html>
<head>
</head>
<body>
<h2>Your details</h2>
<form name="frmdetails" action="sql.php" method="post">
ID Number :
<input name="txtid" type="text" />
<br/>
Password :
<input name="txtpassword" type="text" />
<br/>
Date of Birth :
<input name="txtdob" type="text" />
<br/>
First Name :
<input name="txtfirstname" type="text" />
<br/>
Surname :
<input name="txtlastname" type="text" />
<br/>
Number and Street :
<input name="txthouse" type="text" />
<br/>
Town :
<input name="txttown" type="text" />
<br/>
County :
<input name="txtcounty" type="text" />
<br/>
Country :
<input name="txtcountry" type="text" />
<br/>
Postcode :
<input name="txtpostcode" type="text" />
<br/>
<input type="submit" value="Save" name="submit"/>
</form>
</body>
</html>
//sql.php
$conn=mysql_connect("localhost", "20915184", "mysqluser");
mysql_select_db("db5_20915184", $conn);
// If the form has been submitted
$id=$_POST['txtstudentid'];
$password=$_POST['txtpassword'];
$dob=$_POST['txtdob'];
$firstname=$_POST['txtfirstname'];
$lastname=$_POST['txtlastname'];
$house=$_POST['txthouse'];
$town=$_POST['txttown'];
$county=$_POST['txtcounty'];
$country=$_POST['txtcountry'];
$postcode=$_POST['txtpostcode'];
// Build an sql statment to add the student details
$sql="INSERT INTO student
(studentid,password,dob,firstname,lastname,house,town,county,country,postcode) VALUES
('$id','$password','$dob','$firstname','$lastname','$house','$town','$county','$country','$postcode')";
$result = mysql_query($sql,$conn);
if($result){
echo"<br/>Your details have been updated";
echo "<BR>";
echo "<a href='Home.html'>Back to main page</a>";
}
else {
echo "ERROR";
}
// close connection
mysql_close($conn);
?>
The username comes before the password in mysql_connect();
Try running the sql statement in phpmyadmin and see if it works there!
With in your if else statement, where you echo "ERROR", try printing mysql_error() this would show that your mysql_connect() is wrong If the username/password combo is wrong.
To clean this up a bit, Here is what the if/else should look like
if($result){
echo"<br/>Your details have been updated";
echo "<BR>";
echo "<a href='Home.html'>Back to main page</a>";
} else {
echo "There has been an error <br/>";
print mysql_error();
}
EDIT :
Also, Prevent sql injection with mysql_real_escape_string() on all posted values
Well your code is incomplete, you must insert when the button is clicked also its important to check if a field isset before saving the field in the database also important to filter and sanitize user inputs before submitting. Learn to use prepared statements, with mysqli prepared or PDO whatever works for you, Also don't store passwords in plain text/md5 use password_hash() and password_verify()
Your code with mysqli prepared should look like :
<html>
<head>
</head>
<body>
<h2>Your details</h2>
<form name="frmdetails" action="sql.php" method="post">
ID Number :
<input name="txtid" type="text" />
<br/>
Password :
<input name="txtpassword" type="text" />
<br/>
Date of Birth :
<input name="txtdob" type="text" />
<br/>
First Name :
<input name="txtfirstname" type="text" />
<br/>
Surname :
<input name="txtlastname" type="text" />
<br/>
Number and Street :
<input name="txthouse" type="text" />
<br/>
Town :
<input name="txttown" type="text" />
<br/>
County :
<input name="txtcounty" type="text" />
<br/>
Country :
<input name="txtcountry" type="text" />
<br/>
Postcode :
<input name="txtpostcode" type="text" />
<br/>
<input type="submit" value="Save" name="submit"/>
</form>
</body>
</html>
sql.php
<?php
$servername = "localhost";
$username = "20915184";
$password = "mysqluser";
$dbname = "db5_20915184";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$errors = "";
if (isset($_POST['submit'])) { // submit button clicked
// validate fields
if (empty($_POST['txtstudentid'])) {
echo "enter id";
$errors++;
} else {
$id = userData($_POST['txtstudentid']);
}
if (empty($_POST['txtpassword'])) {
echo "enter password";
$errors++;
} else {
$password = userData($_POST['txtpassword']);
$hash = password_hash($password, PASSWORD_DEFAULT); //hashing password
}
if (empty($_POST['txtdob'])) {
echo "enter date of birth";
$errors++;
} else {
$dob = userData($_POST['txtdob']);
}
if (empty($_POST['txtfirstname'])) {
echo "enter first name";
$errors++;
} else {
$firstname = userData($_POST['txtfirstname']);
}
if (empty($_POST['txtlastname'])) {
echo "enter last name";
$errors++;
} else {
$lastname = userData($_POST['txtlastname']);
}
if (empty($_POST['txthouse'])) {
echo "enter house";
$errors++;
} else {
$house = userData($_POST['txthouse']);
}
if (empty($_POST['txttown'])) {
echo "enter town";
$errors++;
} else {
$town = userData($_POST['txttown']);
}
if (empty($_POST['txtcounty'])) {
echo "enter country";
$errors++;
} else {
$country = userData($_POST['txtcounty']);
}
if (empty($_POST['txtpostcode'])) {
echo "enter post code";
$errors++;
} else {
$postcode = userData($_POST['txtpostcode']);
}
if ($errors <= 0) { //all fields are set no errors
//start query
//check if user id does not exist
$statement = $conn->prepare("SELECT studentid FROM students WHERE studentid = ?");
$statement->bind_param('s', $id);
$statment->execute();
$statement->bind_result($studentID);
if ($statement->num_rows == 1) {
echo "the student Id " . $studentID . " already registered please login";
} else {
// no results then lets insert
$stmt = $conn->prepare("INSERT INTO students (studentid,password,dob,firstname,lastname,house,town,country,postcode) VALUES(?,?,?,?,?,?,?,?,?)");
$stmt->bind_param("sssssssss", $id, $hash, $dob, $firstname, $lastname, $house, $town, $country, $postcode);
$stmt->execute();
echo "<p>Your Details have been updated<br> <a href=\"Home.html\">Back to main page";
$stmt->close();
$conn->close();
}
}
}
//filter userinput
function userData($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
There are many good tutorials on the net on this, hopes this will help, I'm also open to suggestions and corrections incase I missed something.
**> Question mark (?)(placeholder) is used to assign the value.In Prepared
Statements we assign in the values in bind parameter function so that
our query is processed in secure way and prevent from SQL injections.**
In Prepared Statements we pass or attach the values to database query with the help of Bind Parameter function.
You have to attach all the variables whose value you want in your query with their appropriate Data Types just like we pass the 's' means the variable contains a string Data Type.
To execute the query in Prepared Statements you have to use execute() function with query object.
Remove the parameter from your with the inside inside and put in an empty string. i.e
VALUES('','$password','$dob',
etc etc

Categories