Why won't PHP write to MySQL server? - php

so I was making a website with a login system but my PHP will not import anything to MySQL.
Here is my code:
Registration:
<?php require_once './template/header.php'; ?>
<?
$reg = #$_POST['reg'];
//registration form
$fn = strip_tags(#$_POST['fname']);
$ln = strip_tags(#$_POST['lname']);
$un = strip_tags(#$_POST['username']);
$em = strip_tags(#$_POST['email']);
$em2 = strip_tags(#$_POST['email2']);
$pswd = strip_tags(#$_POST['password']);
$pswd2 = strip_tags(#$_POST['password2']);
$d = date("Y-m-d"); // Year - Month - Day
if ($reg) {
if ($em==$em2) {
// Check username
$u_check = mysql_query("SELECT username FROM users WHERE username='$un'");
$check = mysql_num_rows($u_check);
// Check email
$e_check = mysql_query("SELECT email FROM users WHERE email='$em'");
$email_check = mysql_num_rows($e_check);
if ($check == 0) {
if ($email_check == 0) {
// are rows filled in
if ($fn&&$ln&&$un&&$em&&$em2&&$pswd&&$pswd2) {
// passwords match?
if ($pswd==$pswd2) {
// how long are names
if (strlen($un)>25||strlen($fn)>25||strlen($ln)>25) {
echo "Your names are too long!";
}
else
{
// check the maximum length of password does not exceed 25 characters and is not less than 5 characters
if (strlen($pswd)>16||strlen($pswd)<6) {
echo "Passwords must be between 6 and 16 characters!";
}
else
{
//encrypt password
$pswd = md5($pswd);
$pswd2 = md5($pswd2);
$query = mysql_query("INSERT INTO users VALUES ('','$un','$fn','$ln','$em','$pswd','$d','0','Write something about yourself.','','','no')");
die("<h2>Welcome to our community!</h2>Login to your account to begin your journy...");
}
}
}
else {
echo "Your passwords don't match!";
}
}
else
{
echo "Please fill in all of the fields";
}
}
else
{
echo "Sorry, but it looks like someone has already used that email!";
}
}
else
{
echo "Username already taken ...";
}
}
else {
echo "Your E-mails don't match!";
}
}
?>
<div class="container" style="width:1000px; margin:0 auto; padding-top:25px;">
<div id="home">
<table>
<tr>
<td width="50%" valign="top">
<h2>Welcome back! Login here!</h2>
<input type="text" name="email" size="25" placeholder="E-Mail Address" /><br /><br />
<input type="password" name="pass" size="25" placeholder="Password" /><br /><br />
</td>
<td width="50%" valign="top">
<h2>Welcome! Register for free!</h2>
<form action="#" method="post">
<input type="text" size="40" name="fname" class="auto-clear" title="First Name" placeholder="First Name" value="<? echo $fn; ?>"><p />
<input type="text" size="40" name="lname" class="auto-clear" title="Last Name" placeholder="Last Name" value="<? echo $ln; ?>"><p />
<input type="text" size="40" name="username" class="auto-clear" title="Username" placeholder="Username" value="<? echo $un; ?>"><p />
<input type="text" size="40" name="email" class="auto-clear" title="Email" placeholder="Email Address" value="<? echo $em; ?>"><p />
<input type="text" size="40" name="email2" class="auto-clear" title="Repeat Email" placeholder="Email Address" value="<? echo $em2; ?>"><p />
<input type="password" size="40" name="password" value="Password ..."><p />
<input type="password" size="40" name="password2" value="Password ..."><p />
<input type="submit" name="reg" value="Sign Up!">
</form>
<!-- <select name="gender">
<option value="" disabled selected>Gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select><br /><br /> -->
</td>
</tr>
</table>
</div>
</div>
<?php require_once './template/footer.php'; ?>
Connection:
<?php
mysql_connect("localhost","root","");
mysql_select_db("HBN") or die("Couldn't connect to database!")
?>
Thank you guys in advance!

You need to tell SQL what table columns to add the values to. So, instead of writing
"INSERT INTO users VALUES ('','$un','$fn','$ln','$em','$pswd','$d','0','Write something about yourself.','','','no')"
You want to write
"INSERT INTO users (col1,col2,col3,col4,col5...) VALUES ('','$un','$fn','$ln','$em','$pswd','$d','0','Write something about yourself.','','','no')"

Related

Permission denied for PHP application with xampp

I am trying to make my first php based website and have ran into a problem. The website is very basic and is intended to allow users to enter student information into a database. I built this website following a tutorial by Derek Banas which can be found here:
https://www.youtube.com/watch?v=mpQts3ezPVg&t=25s.
Whenever I try to open my getStudentInfo.php file in my browser, I receive the following error:
Warning: require_once(C:\xampp\htdocs\practiceWebDev): failed to open stream: Permission denied in C:\xampp\htdocs\practiceWebDev\practicePHPmySQL\getStudentInfo.php on line 3
Fatal error: require_once(): Failed opening required '../../practiceWebDev' (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\practiceWebDev\practicePHPmySQL\getStudentInfo.php on line 3
Does this error mean I have something wrong with my code? Or do I need to change the php.ini or httpd.conf files associated with XAMPP? Below are the files I have dealing with connections if they are of any use. Thank you very much for any feedback you all can give. Also, I make use of mysql for my database.
mysqli_connect.php:
<?php
//IMPORTANT! This file must be saved outside of where the rest of my files related to our website are saved so that no one may access them.
DEFINE ('DB_USER' 'studentweb');
DEFINE ('DB_PASSWORD' 'turtledove');
DEFINE ('DB_HOST' 'localhost');
DEFINE ('DB_NAME' 'studentdatabase');
$databaseConnection = #mysqli_connect(DB_USER, DB_PASSWORD, DB_HOST, DB_NAME)
//using the above # symbol before mysqli_connect makes it so errors will not appear in the browser.
//# is known as the 'error control operator', and makes PHP suppress error messages associated with the expression.
OR die('Could not connect to MySql lol' . mysqli_connect_error());
//mysqli_connect_error() is a function defined in the php synthax.
?>
getStudentInfo.php:
<?php
//now we require the file outside of the current directory called mysqli_connect.php
require_once('../../practiceWebDev');
//the query below will display the information from each student in the form of a table.
$query = "SELECT first_name, last_name, email, street, province,
postal_code, phone_num, birth_date, sex, date_entered,
lunch_cost, student_id, FROM students";
//the response below is all the info that we've gotten that we want to show in our table.
$response = #mysqli_query($databseConnection, $query);
//below we will see if the query executed properly.
if($response)
{
echo '<table align="left" cellspacing="5" cellpadding="8">
<tr><td align="left"><b>First Name</b></td>
<td align="left"><b>Last Name</b></td>
<td align="left"><b>Email</b></td>
<td align="left"><b>Street</b></td>
<td align="left"><b>City</b></td>
<td align="left"><b>State</b></td>
<td align="left"><b>Zip</b></td>
<td align="left"><b>Phone</b></td>
<td align="left"><b>Birth Day</b></td></tr>';
while($row = mysqli_fetch_array($response)){
echo '<tr>';
echo '<td align=left">'.$row['first_name'].'</td><td align="left">'.$row['last_name'].'</td><td align="left">'.$row['email'].'</td>';
echo '<td align="left">'.$row['street'].'</td><td align="left">'.$row['city'].'</td><td align="left">'.$row['state'].'</td>';
echo '<td align="left">'.$row['zip'].'</td><td align="left">'.$row['phone'].'</td><td align="left">'.$row['birth_date'].'</td>';
echo '</tr>';
}
echo '</table>';
}
else
{
echo "Couldn't issue database query";
echo mysqli_error($databseConnection);
}
mysqli_close($databseConnection);
?>
studentadded.php
<html>
<head>
<title>Add Student</title>
</head>
<body>
<!--First, we need to check if this page was actually reached when the form was submitted--->
<?php
//Below we check that a POST operation was completed by the button I have named "submitButton"
if(isset($_POST['submitButton']))
{
$data_missing = array();
/*If there is an empty field when a POST operation is completed, that field's name will be
added to the data_missing array so that we may visually see which fields are not being sent*/
if(empty($_POST['first_name']))
{
$data_missing[] = 'First Name';
}
else
{
$f_name = trim($POST['first_name']);
}
if(empty($_POST['lastName']))
{
$data_missing[] = 'Last Name';
}
else
{
$l_name = trim($POST['lastName']);
}
if(empty($_POST['email']))
{
$data_missing[] = 'email';
}
else
{
$email = trim($POST['email']);
}
if(empty($_POST['street']))
{
$data_missing[] = 'street';
}
else
{
$street = trim($POST['street']);
}
if(empty($_POST['province']))
{
$data_missing[] = 'province';
}
else
{
$province = trim($POST['province']);
}
if(empty($_POST['postal_code']))
{
$data_missing[] = 'postal_code';
}
else
{
$postal_code = trim($POST['postal_code']);
}
if(empty($_POST['phone_num']))
{
$data_missing[] = 'phone_num';
}
else
{
$phone_num = trim($POST['phone_num']);
}
if(empty($_POST['birth_date']))
{
$data_missing[] = 'birth_date';
}
else
{
$birth_date = trim($POST['birth_date']);
}
if(empty($_POST['sex']))
{
$sex[] = 'sex';
}
else
{
$sex = trim($POST['sex']);
}
if(empty($_POST['lunch_cost']))
{
$data_missing[] = 'lunch_cost';
}
else
{
$lunch_cost = trim($POST['lunch_cost']);
}
if(empty($_POST['student_id']))
{
$data_missing[] = 'student_id';
}
else
{
$student_id = trim($POST['student_id']);
}
//Now lets check
if(empty($data_missing))
{
require_once('../mysqli_connect.php');
$myQuery = "INSERT INTO students (first_name, last_name, email, street, province,
postal_code, phone_num, birth_date, sex, date_entered, lunch_cost,
student_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?, NULL)";
$statement = mysqli_prepare($databaseConnection, $myQuery);
//We have to represent the data type for each of the value that will be passed into our database.
/*i Integers
d Doubles
b Blobs
s Everything Else*/
//Now lets bind variables to the '?'s passed in with the myQuery query.
mysqli_stmt_bind_param($statement, "sssssssisssd", $f_name, $l_name, $email, $street, $province,
$postal_code, $phone_num, $birth_date, $sex, $lunch_cost, $student_id);
mysqli_statement_execute($statement);
$affected_rows = mysqli_stmt_addected_rows($statement);
if($affected_rows == 1)
{
echo 'Went through properly! Student entered correctly!';
mysqli_stmt_close($statement);
mysqli_close($databaseConnection);
}
else
{
echo 'Error occurred :(';
echo '<br />';
echo mysqli_error();
mysqli_stmt_close($statement);
mysqli_close($databaseConnection);
}
}
else
{
echo 'You need to enter the following data my dude: <br />';
foreach($data_missing as $missingData)
{
echo "$missingData<br />";
}
}
}
?>
<form action="http://localhost/studentadded.php" method="post">
<b>Add a New Student</b>
<p>First Name: <input type="text" name="first_name" size="30" value="" /></p>
<p>Last Name: <input type="text" name="lastName" size="30" value="" /></p>
<p>Email: <input type="text" name="email" size="60" value="" /></p>
<p>Street: <input type="text" name="street" size="50" value="" /></p>
<p>Province: <input type="text" name="province" size="3" value="" /></p>
<p>Postal Code: <input type="text" name="postal_code" size="6" value="" /></p>
<p>Phone Number: <input type="text" name="phone_num" size="20" value="" /></p>
<p>Birth Date (YYYY-MM-DD): <input type="text" name="birth_date" size="20" value="" /></p>
<p>Sex: <input type="text" name="sexField1" size="5" maxlength="1" value="" />
<!---<p>Sex: <input type="radio" name="sexField" value="M" />
<br>
<input type="radio" name="sexField" value="F" checked /></p>--->
<!--<p>Date Entered: <input type="" name="" size="" value="" /></p>--->
<p>Lunch Cost: <input type="text" name="lunch_cost" size="5" value="" /></p>
<p>Student ID: <input type="text" name="student_id" size="10" value="" /></p>
<input type="submit" name="submitButton" value="submitValue">
<!-- type="submit" is a predefined term in html--->
</form>
</body>
</html>
addStudent.php
<html>
<head>
<title>Add Student</title>
</head>
<body>
<form action="http://localhost/studentadded.php" method="post">
<b>Add a New Student</b>
<p>First Name: <input type="text" name="first_name" size="30" value="" /></p>
<p>Last Name: <input type="text" name="lastName" size="30" value="" /></p>
<p>Email: <input type="text" name="email" size="60" value="" /></p>
<p>Street: <input type="text" name="street" size="50" value="" /></p>
<p>Province: <input type="text" name="province" size="3" value="" /></p>
<p>Postal Code: <input type="text" name="postal_code" size="6" value="" /></p>
<p>Phone Number: <input type="text" name="phone_num" size="20" value="" /></p>
<p>Birth Date (YYYY-MM-DD): <input type="text" name="birth_date" size="20" value="" /></p>
<p>Sex: <input type="text" name="sexField1" size="5" maxlength="1" value="" />
<!---<p>Sex: <input type="radio" name="sexField" value="M" />
<br>
<input type="radio" name="sexField" value="F" checked /></p>--->
<!--<p>Date Entered: <input type="" name="" size="" value="" /></p>--->
<p>Lunch Cost: <input type="text" name="lunch_cost" size="5" value="" /></p>
<p>Student ID: <input type="text" name="student_id" size="10" value="" /></p>
<input type="submit" name="submitButton" value="submitValue">
<!-- type="submit" is a predefined term in html--->
</form>
</body>
</html>
From what I can see in the tutorial files at this address:
http://www.newthinktank.com/2014/09/php-mysql-tutorial/
In the file getstudentinfo.php at the beginning of the file
You should have require_once('../mysqli_connect.php');
But you have require_once('../../practiceWebDev');
(there is no filename in this line of your code!)
So I think just changing this line of code and using correct path + the filename should solve your error
Update:
Again from what I can see in your code, in studentadded.php file you have this line of code:
require_once('../mysqli_connect.php');
So if your studentadded.php file is working without errors, then just change the line which is generating the error in getstudentinfo.php file with this line.

session variables in a PHP Login Script

I have just finished creating an entire login and register systsem in PHP, but my problem is I haven't used any sessions yet. I'm kind of a newbie in PHP and I've never used sessions before. What I want to do is , when i click on login button it home page should open with user name in body of that page ... but because of that session releated code in header.inc.php my main page couldn't load ..it shows like web page not found when i click on login button ..can any one tell me where is my mistake.. this first time i m asking question in stackoverflow ..so sorry for any mistake , and thanks in advance..
below all of my code works:
1. index.php main page
<code>
<!doctype html>
<?php include( "./inc/header.inc.php"); ?>
<?php
$reg=#$_POST['reg'];
//declaring variables tp prevent error
$fn="";// first name
$ln="";//last name
$un="";//username
$em="";//email
$em2="";//email2
$pswd="";//password
$pswd2="";//password2
$d="";//sign up date
$u_check="";//check if username exist
//registration form
$fn=strip_tags(#$_POST['fname']);
$ln=strip_tags(#$_POST['lname']);
$un=strip_tags(#$_POST['username']);
$em=strip_tags(#$_POST['email']);
$em2=strip_tags(#$_POST['email2']);
$pswd=strip_tags(#$_POST['password']);
$pswd2=strip_tags(#$_POST['password2']);
$d=date("Y-m-d");//Year-Month_Day
if($reg){
if($em=$em2){
//check if user already exist
$u_check = mysqli_query( $db_conx ,"SELECT username FROM user WHERE `username = '$un'");`
// count the amount of the row where username= $un
$check = mysqli_num_rows($u_check);
if($check == 0){
//check all the field have been filled in
//check password match
if($pswd==$pswd2){
//Encrypt Password and Password2 using Md5 before sending to database
$pwsd=md5($pswd);
$pwsd2=md5($pswd2);
$query=mysqli_query( $db_conx , "INSERT INTO user VALUES ('', '$un' , '$fn', '$ln' , '$em' , '$pswd' , '$d' , '0')");
die("<h2>Welcome To FriendsBook</h2> Login To your Account to Get Started...");
}
else{
echo "Your Password Don'T Match!";
}
}
else{
echo "UserName Already Taken..!";
}
}
else{
echo "Your Email Doesn't Match!..";
}
}
// User Login code
if(null!==(#$_POST["user_login"]) && null!==(#$_POST["password_login"])){
$password_login_md5 = md5($password_login);
$sql = mysqli_query($db_conx , "SELECT id FROM user WHERE username = '$user_login' AND password = '$password_login_md5' LIMIT 1"); //query
// check for existance
$userCount = mysqli_num_rows($sql); //Count The Name Of and return
if($userCount==1){
while($row = mysqli_fetch_array($sql , MYSQLI_NUM)){
$id = $row["id"];
}
session_start();
$_SESSION["user_login"] = $user_login;
header("location: home.php");
exit();
}else{
echo 'That Information is Incorrect , Try Again !!';
exit();
}
}
?>
<div style="width:800px; margin:0px auto 0px auto;">
<table>
<tr>
<td width="60%" valign="top">
<h2>Already a Member? Sign in below! </h2>
<form action="index.php" method="POST">
<input type="text" name="user_login" size="25" placeholder="UserName" /><br /><br />
<input type="text" name="password_login" size="25" placeholder="Password" /><br /><br />
<input type="submit" name="login" value="Login" >
</form>
</td>
<td width="40%" valign="top">
<h2>Sign Up Below</h2>
<form action="#" method="POST">
<input type="text" name="fname" maxlength="25" placeholder="First Name" title="Maximum Limit Of First Name is 25 Character" required /><br /><br />
<input type="text" name="lname" maxlength="25" placeholder="Last Name" title="Maximum Limit Of Last Name is 25 Character" required/><br /><br />
<input type="text" name="username" maxlength="25" placeholder="UserName" title="Maximum Limit Of Username is 25 Character" required/><br /><br />
<input type="email" name="email" maxlength="35" placeholder="Email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$" required /><br /><br />
<input type="email" name="email2" maxlength="35" placeholder="Re-Enter Email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$" required/><br /><br />
<input type="password" name="password" min="8" maxlength="25" placeholder="Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
title="Must contain at least one number and one uppercase and lowercase letter,
and at least 8 or more characters" required /><br /><br />
<input type="password" name="password2" min="8" maxlength="25" placeholder="Re-Enter Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
title="Must contain at least one number and one uppercase and lowercase letter,
and at least 8 or more characters" required/><br /><br />
<input type="submit" name="reg" value="Sign Up!" >
</form>
</td>
</tr>
</table>
<?php include( "./inc/footer.inc.php");?>`
2.header.inc.php code
<?php include( "./inc/connect.inc.php");
session_start();
// Store Session Data
if(isset($_SESSION["user_login"])){
header("location: home.php");
}
else
}
?>
<html>
<head>
<title>FriendsBook</title>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
</head>
<body>
<div class="headerMenu">
<div id="wrapper">
<div class="logo">
<img src="img/friendsbooklogo.PNG"/>
</div>
<div class="Search_box">
<form action="Search.php" method="GET" id="search">
<input type="text" name="q" size="60" placeholder="Search..."/>
</form>
</div>
</div>
<div id="menu">
Home
About
Sign Up
Sign IN
</div>
</div>
</body>
3.connect.inc.php
<?php
$db_conx = mysqli_connect("localhost","root","" , "friendsbook" );
?>
4.logout.php
<?php
session_start();
session_destroy();
header("Location : index.php");
?>
5.home.php
<?php
include( "./inc/header.inc.php");
echo $_SESSION["user_login"];
?>

php registration validation which stops showing form on no errors and success [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
<?php
//Form Validation
if(isset($_POST['register']))
{
//Must be at least 4-15 characters and contain letters and numbers
if(!preg_match('/^[a-zA-Z0-9]{4,15}$/', $_POST['username']))
{
$error[]='The username does not match the requirements';
}
//Password validation: must contain at least 1 letter and number. Allows characters !##$% and be 6-15 characters
if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{6,15}$/', $_POST['password1']))
{
$error[]='The password does not match the requirements';
}
//Email validation
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
$error[]='Invalid E-mail';
}
//Output error in array as each line
foreach ($error as $output)
{
echo "$output <br>";
}
}
if ((empty($errors)) && !isset($_POST['register']))
{
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" name="register">
<input type="text" placeholder="Username" maxlength="15" name="username" value="<?php echo $_POST['username']; ?>" /><br>
<input type="password" maxlength="15" name="password1" /><br>
<input type="password" maxlength="15" name="password2" /><br>
<input type="text" placeholder="your#email.com" maxlength="25" name="email" value="<?php echo $_POST['email']; ?>"/><br>
<input type="text" maxlength="20" name="county" /><br>
<input type="submit" value="Register" name="register"/>
</form>
<?php
}
?>
Hi all,
I have got to the point where it doesn't show errors but I probably didn't explain myself too clearly. After the point at which it doesn't show error messages anymore, I would like the form to no longer appear and then I can put something down like "Successful." However I can't seem to achieve this.
<?php
$sent = false;
if ( isset($_POST['register']) )
{
$error = array();
//Must be at least 4-15 characters and contain letters and numbers
if(!preg_match('/^[a-zA-Z0-9]{4,15}$/', $_POST['username']))
{
$error[]='The username does not match the requirements';
}
//Password validation: must contain at least 1 letter and number. Allows characters !##$% and be 6-15 characters
if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{6,15}$/', $_POST['password1']))
{
$error[]='The password does not match the requirements';
}
//Email validation
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
$error[]='Invalid E-mail';
}
if ( count($error) > 0)
{
foreach ($error as $output) {
echo "{$output} <br>";
}
} else {
$sent = true;
}
}//end isset register
?>
<?php if ($sent==false) { ?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" name="register">
<input type="text" placeholder="Username" maxlength="15" name="username" value="<?php if (isset($_POST['username'])) {echo $_POST['username'];} ?>" /><br>
<input type="password" maxlength="15" name="password1" /><br>
<input type="password" maxlength="15" name="password2" /><br>
<input type="text" placeholder="your#email.com" maxlength="25" name="email" value="<?php if (isset($_POST['email'])) {echo $_POST['email'];} ?>"/><br>
<input type="text" maxlength="20" name="county" /><br>
<input type="submit" value="Register" name="register"/>
</form>
<?php } else { echo "Success!"; } ?>
I believe you're trying to have a form where you accept input from users and display errors until all of them are fixed. Your idea is fine, but there are some logical errors in your code.
Here's how it works:
Display the form first
Accept user input
Do the checks for email and password
If there are any errors, display them
These are the changes I've made in your code:
Removed the if(empty($errors)). It's unnecessary
Changed if(!isset($_POST['register'])) to if(isset($_POST['register'])) -- we want to display the form if it wasn't submitted.
Added isset checks inside the <input fields to make sure they're only displayed if the variables are defined
Removed the last code block for } as it's no longer needed
Try this:
<?php
if(isset($_POST['register']))
{
$error = array(); //initializing an empty array
//Must be at least 4-15 characters and contain letters and numbers
if(!preg_match('/^[a-zA-Z0-9]{4,15}$/', $_POST['username']))
{
$error[]='The username does not match the requirements';
}
//Password validation: must contain at least 1 letter and number. Allows characters !##$% and be 6-15 characters
if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{6,15}$/', $_POST['password1']))
{
$error[]='The password does not match the requirements';
}
//Email validation
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
$error[]='Invalid E-mail';
}
//Output error in array as each line
foreach ($error as $output)
{
if(isset($output)) {
echo "$output <br>";
}
}
}
if(!isset($error)) {
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" name="register">
<input type="text" placeholder="Username" maxlength="15" name="username"
value="<?php if(isset($_POST['username'])) echo $_POST['username']; ?>" /><br>
<input type="password" maxlength="15" name="password1" /><br>
<input type="password" maxlength="15" name="password2" /><br>
<input type="text" placeholder="your#email.com" maxlength="25" name="email"
value="<?php if(isset($_POST['email'])) echo $_POST['email']; ?>"/><br>
<input type="text" maxlength="20" name="county" /><br>
<input type="submit" value="Register" name="register"/>
</form>
<?php
}
else {
echo "Successful";
}
?>

PHP register script with sha256 encryption

I am making a register script that lets a user register for an account on a website. I decided to use sha256 to encrypt the password.
Here is my code:
// Set error message as blank upon arrival to page
$errorMsg = "";
// First we check to see if the form has been submitted
if (isset($_POST['Submit'])){
//Connect to the database through our include
require_once ('includes/connect.inc.php');
// Filter the posted variables
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$email = stripslashes($_POST['email']);
$password = preg_replace("[^A-Za-z0-9]", "", $_POST['password']); // filter everything but numbers and letters
$email = strip_tags($email);
$town = preg_replace("[^A-Z a-z0-9]", "", $_POST['town']); // filter everything but spaces, numbers, and letters
// Check to see if the user filled all fields with
// the "Required"(*) symbol next to them in the join form
// and print out to them what they have forgotten to put in
if((!$forename) || (!$surname) || (!$email) || (!$password) || (!$town)){
$errorMsg = "You did not submit the following required information!<br /><br />";
if(!$forename){
$errorMsg .= "--- Forename";
} else if(!$surname){
$errorMsg .= "--- Surname";
} else if(!$email){
$errorMsg .= "--- email";
} else if(!$password){
$errorMsg .= "--- password";
} else if(!$town){
$errorMsg .= "--- town";
}
} else {
$hash = hash("sha256", $password);
$sql = "INSERT INTO customers (forename, surname, email, password, town, registeredDate, active)
VALUES('$forename','$surname','$email', '$hash', '$town', GETDATE(), 'True')" ;
$stmt2 = sqlsrv_query($conn,$sql);
} // Close else after missing vars check
} //Close if $_POST
?>
<form action="join_form.php" method="post" enctype="multipart/form-data">
<tr>
<td colspan="2"><font color="#FF0000"><?php echo "$errorMsg"; ?></font></td>
</tr>
<tr>
<td width="163"><div align="right">Forename:</div></td>
<td width="409"><input name="forename" type="text"/></td>
</tr>
<tr>
<td width="163"><div align="right">Surname:</div></td>
<td width="409"><input name="surname" type="text"/></td>
</tr>
<tr>
<td><div align="right">Email: </div></td>
<td><input name="email" type="text" /></td>
</tr>
<tr>
<td><div align="right"> Password: </div></td>
<td><input name="password" type="password" />
<font size="-2" color="#006600">(letters or numbers only, no spaces no symbols)</font></td>
</tr>
<tr>
<td><div align="right">Town: </div></td>
<td>
<input name="town" type="text" />
</td>
</tr>
<tr>
<td><div align="right"></div></td>
<td><input type="submit" name="Submit" value="Submit Form" /></td>
</tr>
</form>
When I press Submit button nothing happens. I don't get an error message, but the record does not get added to the database either.
I know it has something to do with me using
$hash = hash("sha256", $password);
Maybe I put it in the wrong place or something?
I am very new to PHP.
I changed my code entirely and used params in order to add a record to the database
<?php
require_once ('includes/connect.inc.php');
if ($_POST['Register'] == "register")
{
$params = array($_POST['email']);
$sql= "SELECT * FROM customers WHERE Email=?";
$stmt = sqlsrv_query($conn,$sql,$params);
if(sqlsrv_has_rows($stmt))
{
// echo"<h2>You have already signed up with this email </h2>";
header('Location: register_login_forms.php?error=2');
die();
} else if($_POST['password'] != $_POST['password2'])
{
// echo"<h2>Wrong Passwod</h2>";
header('Location: register_login_forms.php?error=3');
die();
}
$pass = hash("sha256", $_POST['password']);
$params = array($_POST['forename'],$_POST['surname'],$_POST['email'],$pass, $_POST['phone'], $_POST['question'],
$_POST['answer']);
$sql="INSERT INTO customers (forename,surname,email,password,phone,secret_question, secret_answer,active,registeredDate)
VALUES (?,?,?,?,?,?,?,'True',GETDATE())";
$stmt=sqlsrv_query($conn,$sql,$params);
header('Location: registerSuccess.php');
}
?>
And here is the form
<Form name = "Register" action="register.php" method="POST" >
<label>Forename</label><br />
<input required title="Please only use Letters" type="text" pattern="\s*[A-z]+\s*" name="forename" /><br/>
<label>Surname</label><br />
<input required title="Please only use Letters" type="text" pattern="\s*[A-z]+\s*" name="surname" /><br/>
<label>Email</label><br />
<input required title="Please enter a Valid Email Address" type="email" name="email" /></br>
<label>Password</label><br />
<input required title="Please have a Password of Minimum of 6 Characters with Numbers" type="password" pattern="[A-z0-9]{6,20}" name="password" /></br>
<label>Confirm Password</label><br />
<input required title="Confirm Password" type="password" pattern="[A-z0-9]{6,20}" name="password2" /></br>
<label>Secret Question</label><br />
<input required type="text" name="question" /></br>
<label>Secret Answer</label><br />
<input required type="text" name="answer" /></br>
<label>Phone Number</label><br />
<input required title="Please only use numbers" type="text" pattern="\d+" name="phone" /></br>
<input type="hidden" name="Register" value="register">
<input class="button" type = "submit"/>
</Form>

All is working except if($_POST['submit']=='Update')

I have a working registration and login system. I am trying to create a form where a user can add product registration info (via mysql update). I can't seem to get the db to actually update the fields. What am I missing here?!?
<?php
define('INCLUDE_CHECK',true);
require 'connect.php';
require 'functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined
session_name('tzLogin');
// Starting the session
session_set_cookie_params(2*7*24*60*60);
// Making the cookie live for 2 weeks
session_start();
if($_SESSION['id'] && !isset($_COOKIE['tzRemember']) && !$_SESSION['rememberMe'])
{
// If you are logged in, but you don't have the tzRemember cookie (browser restart)
// and you have not checked the rememberMe checkbox:
$_SESSION = array();
session_destroy();
// Destroy the session
}
if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();
header("Location: index_login3.php");
exit;
}
if($_POST['submit']=='Login')
{
// Checking whether the Login form has been submitted
$err = array();
// Will hold our errors
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT * FROM electrix_users WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$_SESSION['email'] = $row['email'];
$_SESSION['first'] = $row['first'];
$_SESSION['last'] = $row['last'];
$_SESSION['address1'] = $row['address1'];
$_SESSION['address2'] = $row['address2'];
$_SESSION['city'] = $row['city'];
$_SESSION['state'] = $row['state'];
$_SESSION['zip'] = $row['zip'];
$_SESSION['country'] = $row['country'];
$_SESSION['product1'] = $row['product1'];
$_SESSION['serial1'] = $row['serial1'];
$_SESSION['product2'] = $row['product2'];
$_SESSION['serial2'] = $row['serial2'];
$_SESSION['product3'] = $row['product3'];
$_SESSION['serial3'] = $row['serial3'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Store some data in the session
setcookie('tzRemember',$_POST['rememberMe']);
}
else $err[]='Wrong username and/or password!';
}
if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: index_login3.php");
exit;
}
else if($_POST['submit']=='Register')
{
// If the Register form has been submitted
$err = array();
if(strlen($_POST['username'])<4 || strlen($_POST['username'])>32)
{
$err[]='Your username must be between 3 and 32 characters!';
}
if(preg_match('/[^a-z0-9\-\_\.]+/i',$_POST['username']))
{
$err[]='Your username contains invalid characters!';
}
if(!checkEmail($_POST['email']))
{
$err[]='Your email is not valid!';
}
if(!count($err))
{
// If there are no errors
$pass = substr(md5($_SERVER['REMOTE_ADDR'].microtime().rand(1,100000)),0,6);
// Generate a random password
$_POST['email'] = mysql_real_escape_string($_POST['email']);
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['first'] = mysql_real_escape_string($_POST['first']);
$_POST['last'] = mysql_real_escape_string($_POST['last']);
$_POST['address1'] = mysql_real_escape_string($_POST['address1']);
$_POST['address2'] = mysql_real_escape_string($_POST['address2']);
$_POST['city'] = mysql_real_escape_string($_POST['city']);
$_POST['state'] = mysql_real_escape_string($_POST['state']);
$_POST['zip'] = mysql_real_escape_string($_POST['zip']);
$_POST['country'] = mysql_real_escape_string($_POST['country']);
// Escape the input data
mysql_query(" INSERT INTO electrix_users(usr,pass,email,first,last,address1,address2,city,state,zip,country,regIP,dt)
VALUES(
'".$_POST['username']."',
'".md5($pass)."',
'".$_POST['email']."',
'".$_POST['first']."',
'".$_POST['last']."',
'".$_POST['address1']."',
'".$_POST['address2']."',
'".$_POST['city']."',
'".$_POST['state']."',
'".$_POST['zip']."',
'".$_POST['country']."',
'".$_SERVER['REMOTE_ADDR']."',
NOW()
)");
if(mysql_affected_rows($link)==1)
{
send_mail( 'noreply#electrixpro.com',
$_POST['email'],
'Your New Electrix User Password',
'Thank you for registering at www.electrixpro.com. Your password is: '.$pass);
$_SESSION['msg']['reg-success']='We sent you an email with your new password!';
}
else $err[]='This username is already taken!';
}
if(count($err))
{
$_SESSION['msg']['reg-err'] = implode('<br />',$err);
}
header("Location: index_login3.php");
exit;
}
if($_POST['submit']=='Update')
{
{
mysql_query(" UPDATE electrix_users(product1,serial1,product2,serial2,product3,serial3) WHERE usr='{$_POST['username']}'
VALUES(
'".$_POST['product1']."',
'".$_POST['serial1']."',
'".$_POST['product2']."',
'".$_POST['serial2']."',
'".$_POST['product3']."',
'".$_POST['serial3']."',
)");
if(mysql_affected_rows($link)==1)
{
$_SESSION['msg']['upd-success']='Thank you for registering your Electrix product';
}
else $err[]='So Sad!';
}
if(count($err))
{
$_SESSION['msg']['upd-err'] = implode('<br />',$err);
}
header("Location: index_login3.php");
exit;
}
if($_SESSION['msg'])
{
// The script below shows the sliding panel on page load
$script = '
<script type="text/javascript">
$(function(){
$("div#panel").show();
$("#toggle a").toggle();
});
</script>';
}
?>
Here are the forms:
<!-- Panel -->
<div id="toppanel">
<div id="panel">
<div class="content clearfix">
<div class="left">
<h1>My Electrix Account </h1>
<p class="grey">View and edit your contact information and product registrations</p>
</div>
<?php
if(!$_SESSION['id']):
?>
<div class="left">
<!-- Login Form -->
<form class="clearfix" action="" method="post">
<h1>Member Login</h1>
<?php
if($_SESSION['msg']['login-err'])
{
echo '<div class="err">'.$_SESSION['msg']['login-err'].'</div>';
unset($_SESSION['msg']['login-err']);
}
?>
<label class="grey" for="username">Username:</label>
<input class="field" type="text" name="username" id="username" value="" size="23" />
<label class="grey" for="password">Password:</label>
<input class="field" type="password" name="password" id="password" size="23" />
<label><input name="rememberMe" id="rememberMe" type="checkbox" checked="checked" value="1" /> Remember me</label>
<div class="clear"></div>
<input type="submit" name="submit" value="Login" class="bt_login" />
</form>
</div>
<div class="left right">
<!-- Register Form -->
<form action="" method="post">
<h1>Not a member yet? Sign Up!</h1>
<?php
if($_SESSION['msg']['reg-err'])
{
echo '<div class="err">'.$_SESSION['msg']['reg-err'].'</div>';
unset($_SESSION['msg']['reg-err']);
}
if($_SESSION['msg']['reg-success'])
{
echo '<div class="success">'.$_SESSION['msg']['reg-success'].'</div>';
unset($_SESSION['msg']['reg-success']);
}
?>
<label class="grey" for="username">Username*:</label>
<input class="field" type="text" name="username" id="username" value="" size="23" />
<label class="grey" for="email">Email*:</label>
<input class="field" type="text" name="email" id="email" size="23" />
<label class="grey" for="first">First Name:</label>
<input class="field" type="text" name="first" id="first" size="23" />
<label class="grey" for="last">Last Name:</label>
<input class="field" type="text" name="last" id="last" size="23" />
<label class="grey" for="address1">Address line 1:</label>
<input class="field" type="text" name="address1" id="address1" size="23" />
<label class="grey" for="address2">Address line 2:</label>
<input class="field" type="text" name="address2" id="address2" size="23" />
<label class="grey" for="city">City:</label>
<input class="field" type="text" name="city" id="city" size="23" />
<label class="grey" for="state">State/Province:</label>
<input class="field" type="text" name="state" id="state" size="23" />
<label class="grey" for="zip">Zip/Postal Code:</label>
<input class="field" type="text" name="zip" id="zip" size="23" />
<label class="grey" for="country">Country:</label>
<input class="field" type="text" name="country" id="country" size="23" />
<p>
<label>A password will be e-mailed to you.</label>
<input type="submit" name="submit" value="Register" class="bt_register" />
</p>
</form>
</div>
<?php
else:
?>
<div class="left">
<h1>User Information</h1>
<p>
<?php echo $_SESSION['first']; ?>
<?php echo $_SESSION['last']; ?><br />
<?php echo $_SESSION['address1']; ?>
<?php echo $_SESSION['address2']; ?><br />
<?php echo $_SESSION['city']; ?>,
<?php echo $_SESSION['state']; ?>
<?php echo $_SESSION['zip']; ?><br />
<?php echo $_SESSION['country']; ?>
</p>
<p>Email: <?php echo $_SESSION['email']; ?></p>
<p>Downloads</p>
Log off
</div>
<div class="left right">
<!-- Product Registration Form -->
<form class="clearfix" action="" method="post">
<h1>Product Registration</h1>
<?php
if($_SESSION['msg']['upd-err'])
{
echo '<div class="err">'.$_SESSION['msg']['upd-err'].'</div>';
unset($_SESSION['msg']['upd-err']);
}
if($_SESSION['msg']['upd-success'])
{
echo '<div class="success">'.$_SESSION['msg']['upd-success'].'</div>';
unset($_SESSION['msg']['upd-success']);
}
?>
<label class="grey" for="product1">Product 1:</label>
<input class="field" type="text" name="product1" id="product1" value="<?php echo $_SESSION['product1']; ?>" size="23" />
<label class="grey" for="serial1">Serial 1:</label>
<input class="field" type="text" name="serial1" id="serial1" value="<?php echo $_SESSION['serial1']; ?>" size="23" />
<label class="grey" for="product2">Product 2:</label>
<input class="field" type="text" name="product2" id="product2" value="<?php echo $_SESSION['product2']; ?>" size="23" />
<label class="grey" for="serial2">Serial 2:</label>
<input class="field" type="text" name="serial2" id="serial2" value="<?php echo $_SESSION['serial2']; ?>" size="23" />
<label class="grey" for="product3">Product 3:</label>
<input class="field" type="text" name="product3" id="product3" value="<?php echo $_SESSION['product3']; ?>" size="23" />
<label class="grey" for="serial3">Serial 3:</label>
<input class="field" type="text" name="serial3" id="serial3" value="<?php echo $_SESSION['serial3']; ?>" size="23" />
<div class="clear"></div>
<input type="submit" name="submit" value="Update" class="bt_login" />
</form>
</div>
<?php
endif;
?>
</div>
</div> <!-- /login -->
<!-- The tab on top -->
<div class="tab">
<ul class="login">
<li class="left"> </li>
<li>Hello <?php echo $_SESSION['usr'] ? $_SESSION['usr'] : 'Guest';?>!</li>
<li class="sep">|</li>
<li id="toggle">
<a id="open" class="open" href="#"><?php echo $_SESSION['id']?'Open Panel':'Log In | Register';?></a>
<a id="close" style="display: none;" class="close" href="#">Close Panel</a>
</li>
<li class="right"> </li>
</ul>
</div> <!-- / top -->
</div> <!--panel -->
Your update query is way off. You need to do it in the form of
UPDATE `tablename`
SET col1=`value`,col2=`val2`
WHERE wherecol=`whereval`
change your query and see if that helps.
your query should be
UPDATE electrix_users
SET
product1= $_POST['product1'],
serial1 = $_POST['serial1'],
product2 = $_POST['product2'],
serial2 = $_POST['serial2'],
product3 = $_POST['product3'],
serial3 = $_POST['serial3']
WHERE usr=$_POST['username']
However you should always clean for sql injection on any user entered data. I did not do this in the example as this is something you should do in your own way. This example is given to you as an example and does not prevent any kind of sql injection as it stands now.
ALWAYS DO WHAT YOU CAN TO PREVENT SQL INJECTION!

Categories