PHP MySQL Insert to is not working for some reason - php

I would like help on how to fix why the user info is not inserting into the database. I am not getting any errors printed to the screen and the "Hit" is echoed when I entered info for a user that is not already in the database, so it is reaching that block of code, just not inserting into the database.
When I echoed $query for values I inputted I recieved INSERT INTO users ( first_name, last_name, email, password) VALUES ( 'tanya', 'long', 'tlong3#twc.com', 'purple03') Nothing appeared when I echoed $result Thanks
<?php
session_start();
require_once("/includes/registerFunctions.php");
require("/includes/databaseConnection.php");
?>
<?php
$name_message = "";
$password_message = "";
$email_message = "";
$missingInfo = "<div class='message'> Please fix the following errors: ". "<br>"."<ul>";
$numOfErrors = 0;
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST) && isset($_POST['submit']))
{
$first_name = mysqli_real_escape_string($connect, $_POST['fname']);
$last_name = mysqli_real_escape_string($connect, $_POST['lname']);
$email = mysqli_real_escape_string($connect,$_POST['email']);
$password = mysqli_real_escape_string($connect, $_POST['password']);
$confirm_password = mysqli_real_escape_string($connect, $_POST['cpassword']);
$content = array($first_name, $last_name, $email, $password, $confirm_password);
$contentMessage = array("First name", "Last name", "email", "password", "confirmation password");
$length = count($content);
if(!equalPasswords($password, $confirm_password))
{
$missingInfo .= "<li> Passwords do not match </li>";
$numOfErrors++;
}
if(!valid_email($email))
{
$missingInfo .= "<li>The entered email is invalid. </li>";
$numOfErrors++;
}
$min = 8;
if(strlen($password) < $min || strlen($confirm_password) < $min)
{
$missingInfo .= "<li>Please choose a password that is at least ". $min ." characters long </li>";
$numOfErrors++;
}
for($i = 0; $i < $length; $i++)
{
if(!has_presence($content[$i]))
{
$missingInfo .= "<li>". ucfirst($contentMessage[$i])." is blank "."<br> </li>";
$numOfErrors++;
}
}
$missingInfo .= "</ul></div>";
if($numOfErrors > 0)
{
echo $missingInfo;
}
$emailQuery = "SELECT email FROM users WHERE email = '$email'";
$emailResult = mysqli_query($connect, $emailQuery);
$numOfRows = mysqli_num_rows($emailResult);
if($numOfErrors == 0 && $numOfRows == 0)
{
/* Check if the email is already in use*/
echo "Hit";
$query = "INSERT INTO users (";
$query .= " first_name, last_name, email, password";
$query .= ") VALUES (";
$query .= " '{$first_name}', '{$last_name}', '{$email}', '{$password}'";
$query .= ")";
$result = mysqli_query($connect, $query);
if($result)
{
$_SESSION['fname'] = $first_name;
$_SESSION['lname'] = $last_name;
}
//$userId = $_SESSION['id'];
}
else if($numOfRows >= 1 )
{
echo "The email entered is already in use, please : ". "<a href='index.php'>login</a>";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title> Register</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="register.css">
<link href="https://fonts.googleapis.com/css?family=Amatic+SC" rel="stylesheet">
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/pure-min.css">
<style type="text/css">
form{
padding-top: 20px;
text-align: center;
}
.message
{
position: absolute;
right: 180px;
top: 60px;
width: 220px;
}
input {
border: 0;
outline: 0;
background: transparent;
border-bottom: 1px solid grey;
width: 250px;
}
div
{
padding: 10px;
}
a
{
color: #4169E1;
}
a:hover{
color:grey;
}
</style>
</head>
<body>
<form id="form" method="POST" action="register.php">
<h3 style="font-family:'Amatic SC', cursive; font-size: 20px;"> Welcome to Caruize </h3>
<div >
<input type="text" name="fname" id="fname" placeholder="First Name" autocomplete="off">
</div>
<div >
<input type="text" name="lname" id="lname" placeholder="Last Name" autocomplete="off" required>
</div>
<div >
<input type="email" name="email" id="email" placeholder="Email Address" autocomplete="off" required>
</div>
<div>
<input type="password" name="password" id="password" placeholder="Password" autocomplete="off" required>
</div>
<div>
<input type="password" name="cpassword" id="cpassword" placeholder="Confirm Password" autocomplete="off" required>
</div>
<div>
<button type="submit" name="submit" class="pure-button pure-button-primary"> Register</button> <br> <br>
<p> Already a member? </p><a style="text-decoration: none;" href="index.php">Sign in </a>
</div>
</form>
<script type="text/javascript">
var pLabel = document.getElementById("passwordLabel");
pLabel.textContent = "Too Short";
</script>
</body>
</html>

Haha, I was only inserting values into the database that was required by the form. There were about 5 other fields that I set to NOT NULL that I was not inserting into haha. Thank you all.

Related

Password hasing in PHP login system

I´m not very expirence in programming.
I want to build a login system in PHP with some security mesures on it. I consult a video on youtube to help me and I found this one: https://www.youtube.com/watch?v=pIO0pmMTJ6Y&list=PLiJgIxJAg1VZqxDFL1Lp9VTm8PRfFeQ-o&index=18&t=5666s
The question is that don´t include any password hashing function, so i add it myself on the signup.php ant it works !!! But now, i´m not able to login to the site with a password created on th signup page. I try to chang the login.php code but don´t have success. What I have to do to resolve?
signup.php
<?php
require "../private/autoload.php";
$Error ="";
$email = "";
$username = "";
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$email =$_POST["email"];
if(!preg_match("/^[\w\-]+#[\w\-]+.[\w\-]+$/",$email))
{
$Error = "Please enter a valid email";
}
$date = date ("Y-m-d H:i:s");
$url_address = get_random_string(60);
$username = trim($_POST["username"]);
if(!preg_match("/^[a-zA-Z]+$/",$username))
{
$Error = "Please enter a valid username";
}
$username = esc($username);
$password = esc($_POST["password"]);
$passwordhashed = password_hash($password,PASSWORD_DEFAULT);
$arr = false;
$arr['email']= $email;
$query = "SELECT * FROM USERS WHERE email = :email limit 1";
$stm = $connection->prepare($query);
$check = $stm->execute($arr);
if($check)
{
$data = $stm->fetchAll(PDO::FETCH_OBJ);
if(is_array($data) && count ($data) > 0)
{
$Error = "Someone is already using that email";
}
}
if($Error =="")
{
$arr['url_address'] = $url_address;
$arr['date'] = $date;
$arr['username'] = $username;
$arr['password'] = $passwordhashed;
$arr['email'] = $email;
$query = "insert into users(url_address,username,password,email,date) values(:url_address,:username,:password,:email,:date)";
$stm = $connection->prepare($query);
$stm->execute($arr);
header ("Location: login.php");
die;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>
Signup
</title>
<h1 style="text-align:center"><span style="font-family:Arial,Helvetica,sans-serif"><strong>Bem-Vindo ao Website</strong></span></h1>
<h2 style="text-align:center"><span style="color:#999999"><span style="font-family:Arial,Helvetica,sans-serif"><strong>Faz o teu signup para acederes ao site</strong></span></span></h2>
<p><span style="font-family:Arial,Helvetica,sans-serif"><strong> </strong></span></p>
<p style="text-align:center"> </p>
<p style="text-align:center"> </p>
<body style="font-family: verdana">
<style type="text/css">
form {
margin: auto;
border: solid thin #aaa;
padding: 1px;
max-width: 200px;
}
#title {
background-color: #256972;
padding: 1cm;
text-align: center;
color: white;
}
#textbox {
border: solid thin #aaa;
margin-top: 6px;
width: 98%;
}
</style>
<form method="post">
<div><?php
if(isset($Error) && $Error != "")
{
echo $Error;
}
?>
<div id="title">Signup</div>
<input id="textbox" type="text" name="username" value="<?=$username?>" placeholder="username" required><br>
<input id="textbox" type="email" name="email" value="<?=$email?>" placeholder="email" required><br>
<input id="textbox" type="password" name="password" placeholder="password" required><br><br>
<input type="submit" value="Signup">
</form>
</body>
</head>
</html>
login.php
<?php
require "../private/autoload.php";
$Error = "";
if($_SERVER["REQUEST_METHOD"]=="POST" && isset ($_SESSION ['token']) && isset ($_POST ['token']) && $_SESSION ['token'] == $_POST["token"])
{
$email =$_POST["email"];
if(!preg_match("/^[\w\-]+#[\w\-]+.[\w\-]+$/",$email))
{
$Error = "Please enter a valid email";
}
$password = ($_POST["password"]);
$passwordhashed = password_hash($password,PASSWORD_DEFAULT);
if($Error ==""){
$arr['password'] = $passwordhashed;
$arr['email'] = $email;
$query = "SELECT * FROM USERS WHERE email = :email && password = :password limit 1";
$check = $stm->execute($arr);
if($check){
$data = $stm->fetchAll(PDO::FETCH_OBJ);
if(is_array($data) && count ($data) > 0){
$data = $data[0];
$_SESSION['username'] = $data->username;
$_SESSION['url_address'] = $data->url_address;
header ("Location: index.php");
die;
}
}
}
$Error = "Wrong email or password";
}
$_SESSION ['token'] = get_random_string(60);
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<body style="font-family: verdana">
<style type="text/css">
form {
margin: auto;
border: solid thin #aaa;
padding: 1px;
max-width: 200px;
}
#title {
background-color: #256972;
padding: 1cm;
text-align: center;
color: white;
}
#textbox {
border: solid thin #aaa;
margin-top: 6px;
width: 98%;
}
</style>
<form method="post">
<div><?php
if(isset($Error) && $Error != "")
{
echo $Error;
}
?>
<div id="title">Login</div>
<input id="textbox" type="email" name="email" placeholder="email" required><br>
<input id="textbox" type="password" name="password" placeholder="password" required><br><br>
<input type="hidden" name="token" value="<?=$_SESSION ['token']?>">
<input type="submit" value="Login">
</form>
</body>
</head>
</html>
function.php
<?php
function get_random_string ($length)
{
$array = array (0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
$text = "";
$lenght = rand(4,$length);
for ($i=0;$i<$lenght;$i++) {
$random = rand(0,61);
$text .=$array[$random];
}
return $text;
}
function esc($word)
{
return addslashes ($word);
}
function check_login ($connection)
{
if(isset($_SESSION['url_address']))
{
$arr['url_address'] = $_SESSION['url_address'];
$query = "SELECT * FROM USERS WHERE url_address = :url_address limit 1 && password = :password limit 1";
$stm = $connection->prepare($query);
$check = $stm->execute($arr);
if($check)
{
$data = $stm->fetchAll(PDO::FETCH_OBJ);
if(is_array($data) && count ($data) > 0)
{
return $data[0];
}
}
}
header("Location: login.php");
die;
}
I won't answer directly, but here is the doc for hashing password with php:
first
// let's say you have a $passwordToHash variable
$passwordHashed = password_hash($passwordToHash, PASSWORD_DEFAULT);
then, you could verify that you passwordHashed is equal to passwordToHash (when you want to check if a password is in your db for ex)
// true or false
password_verify($passwordToHash, $passwordHashed)

Unable to store data in the database

I am creating a PHP registration form using AJAX, the below code that I have pasted isn't working properly. I am literally new to this AJAX concept
When I click the register button it won't respond and do anything, and even in the database the values are not getting stored. I have searched a lot for this AJAX concept.
But I don't seem to get the result what I want. Please, can any one help me. Where am I actually doing the wrong thing? Thanks in advance!
index.php
<!DOCTYPE HTML>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="script.js"></script>
<style>
.error {
color:red;
}
.button {
background-color: #4CAF50;
border: none;
color: white;
padding: 10px 25px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
.div1 {
margin-top: -19px;
margin-bottom: -25px;
margin-left: -19px;
}
.copy {
border-radius: 4px;
padding: 6px 20px;
border-style: ridge;
}
.copy1{
border-radius: 4px;
padding: 6px 28px;
border-style: ridge;
}
.copy2{
border-radius: 4px;
padding: 4px 2px;
}
</style>
</head>
<body style="background-color: #f2f2f2;">
<?php
// define variables and set to empty values
include_once 'connect.php';
$nameErr = $emailErr = $usernameErr = $passwordErr = $ageErr = "" ;
$name = $email = $username = $password = $age = "";
if (isset($_POST['submit'])) {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
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("/^[a-zA-Z ]*$/",$username)) {
$usernameErr = "Only letters";
}
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password = test_input($_POST["password"]);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// check weather password is alphanumeric
if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{6,}$/', $password))
{
$passwordErr = "Password must be alphanumeric and atleast 6 characters long!";
}
}
if (empty($_POST["age"])) {
$ageErr = "Age is required";
}
elseif($_POST["age"]< 17 ) {
$ageErr = "Age should be above 18 years";
}
else {
$age = $_POST["age"];
}
if($nameErr == "" && $emailErr == "" && $usernameErr == "" && $passwordErr == "" && $ageErr == "")
{
$check="SELECT * FROM users WHERE username = '$_POST[username]'";
$rs = mysqli_query($mysqli,$check);
$da = mysqli_fetch_array($rs, MYSQLI_NUM);
if($da[0] > 0) {
echo "Username Already in Exists<br/>";
}
else
{
$sql = "INSERT INTO users(`userid`,`username`, `password`, `email` , `name` , `age` )
VALUES ('','".$username."', '".$hashed_password."', '".$email."' , '".$name."' , '".$age."' )";
if (mysqli_query($mysqli, $sql)) {
echo "Registered successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
mysqli_close($mysqli);
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div style="padding-left: 250px" class="div1">
<h2 style="color:#009999">Registration Form :</h2>
<p><span class="error">All fields are required </span></p>
<form action="" method="post" enctype="multipart/form-data">
<span style="color:#0099ff">Name: </span>
<input type="text" name="name" class= "copy" style="margin-left: 52px" value ="<?php
if (isset($name))
echo $name;
?>">
<span class="error"> <?php echo $nameErr;?></span>
<br><br>
<span style="color:#0099ff"> E-mail: </span>
<input type="text" name="email" class= "copy" style="margin-left: 48px" value ="<?php
if (isset($email))
echo $email;
?>">
<span class="error"><?php echo $emailErr;?></span>
<br><br>
<span style="color:#0099ff"> Username: </span>
<input type="text" name="username" class= "copy" style="margin-left:26px" value ="<?php
if (isset($username))
echo $username;
?>">
<span class="error"> <?php echo $usernameErr;?></span>
<br><br>
<span style="color:#0099ff"> Password: </span>
<input type="password" name="password" class= "copy" style="margin-left:30px">
<span class="error"> <?php echo $passwordErr;?></span>
<br><br>
<span style="color:#0099ff"> Age : </span>
<input type="number" name="age" class= "copy" style="margin-left:62px" value ="<?php
if (isset($age))
echo $age;
?>">
<span class="error"> <?php echo $ageErr;?></span>
<br><br>
<input type="button" class="submit" name="submit" value="submit">
</form>
</div>
</body>
</html>
script.js
$(document).ready(function(){
$(".submit").click(function(){
var name = $("name").val();
var email = $("email").val();
var username = $("username").val();
var password = $("password").val();
var age = $("age").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name='+ name + '&email='+ email + '&username='+ username + '&password='+ password + '&age='+ age;
var dataString = $("form").serialize();
if(name==''|| email==''|| username==''|| password==''|| age=='')
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "index.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
connect.php
<?php
$databaseHost = 'localhost';
$databaseName = 'ajax1';
$databaseUsername = 'root';
$databasePassword = '';
$mysqli = mysqli_connect($databaseHost, $databaseUsername, $databasePassword, $databaseName);
?>
Try this... I hope it will help you..
index.php
<!DOCTYPE HTML>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="script.js"></script>
<style>
.error {
color:red;
}
.button {
background-color: #4CAF50;
border: none;
color: white;
padding: 10px 25px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
.div1 {
margin-top: -19px;
margin-bottom: -25px;
margin-left: -19px;
}
.copy {
border-radius: 4px;
padding: 6px 20px;
border-style: ridge;
}
.copy1{
border-radius: 4px;
padding: 6px 28px;
border-style: ridge;
}
.copy2{
border-radius: 4px;
padding: 4px 2px;
}
</style>
</head>
<body style="background-color: #f2f2f2;">
<div style="padding-left: 250px" class="div1">
<h2 style="color:#009999">Registration Form :</h2>
<p><span class="error">All fields are required </span></p>
<form action="" method="post" enctype="multipart/form-data">
<span style="color:#0099ff">Name: </span>
<input type="text" name="name" class= "name copy" style="margin-left: 52px" value ="">
<span class="namee error"> </span>
<br><br>
<span style="color:#0099ff"> E-mail: </span>
<input type="text" name="email" class= "email copy" style="margin-left: 48px" value ="">
<span class="emaile error"></span>
<br><br>
<span style="color:#0099ff"> Username: </span>
<input type="text" name="username" class= "username copy" style="margin-left:26px" value ="">
<span class="usernamee error"></span>
<br><br>
<span style="color:#0099ff"> Password: </span>
<input type="password" name="password" class= "password copy" style="margin-left:30px">
<span class="passworde error"> </span>
<br><br>
<span style="color:#0099ff"> Age : </span>
<input type="number" name="age" class= "age copy" style="margin-left:62px" value ="">
<span class="agee error"> </span>
<br><br>
<input type="button" class="submit" name="submit" value="submit">
</form>
</div>
</body>
<script>
$(document).ready(function(){
$(".submit").click(function(){
var name = $(".name").val();
var email = $(".email").val();
var username = $(".username").val();
var password = $(".password").val();
var age = $(".age").val();
if(name==''){$('.namee').text('fill value'); return false}
if(email==''){$('.emaile').text('fill value'); return false}
if(username==''){$('.usernamee').text('fill value'); return false}
if(password==''){$('.passworde').text('fill value'); return false}
if(age==''){$('.agee').text('fill value'); return false}
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name='+ name + '&email='+ email + '&username='+ username + '&password='+ password + '&age='+ age;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "gethint.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
});
});
</script>
</html>
gethint.php
<?php
$mysqli = mysqli_connect("localhost","root","","test");
$username =$_POST["username"];
$hashed_password=$_POST["password"];
$email=$_POST["email"];
$name=$_POST["name"];
$age=$_POST["age"];
$check="SELECT * FROM users WHERE username = '$_POST[username]'";
$rs = mysqli_query($mysqli,$check);
$da = mysqli_fetch_array($rs, MYSQLI_NUM);
if($da[0] > 0) {
echo "Username Already in Exists<br/>";
}
else
{
$sql = "INSERT INTO users(`userid`,`username`, `password`, `email` , `name` , `age` )
VALUES ('','".$username."', '".$hashed_password."', '".$email."' , '".$name."' , '".$age."' )";
if (mysqli_query($mysqli, $sql)) {
echo "Registered successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
mysqli_close($mysqli);
}
?>
The problem is when you run your index.php file for the first time , the php part gets executed.So make a new file for php part.
Get extra help From w3schools.com
https://www.w3schools.com/php/php_ajax_php.asp

unable to execute the ajax code

im creating a php registration form using ajax, the below code that i have pasted isnt seems to be working , im literially new to this ajax concept
when i click the register button it wont respond anything, and even in the database the values are not getting stored i have seached a lot for this ajax concept
but i don seem to get the result what i want please can any one help me where im actually going wrong please help me.
index.php
<!DOCTYPE HTML>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="script.js"></script>
<style>
.error {
color:red;
}
.button {
background-color: #4CAF50;
border: none;
color: white;
padding: 10px 25px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
.div1 {
margin-top: -19px;
margin-bottom: -25px;
margin-left: -19px;
}
.copy {
border-radius: 4px;
padding: 6px 20px;
border-style: ridge;
}
.copy1{
border-radius: 4px;
padding: 6px 28px;
border-style: ridge;
}
.copy2{
border-radius: 4px;
padding: 4px 2px;
}
</style>
</head>
<body style="background-color: #f2f2f2;">
<?php
// define variables and set to empty values
include_once 'connect.php';
$nameErr = $emailErr = $usernameErr = $passwordErr = $ageErr = "" ;
$name = $email = $username = $password = $age = "";
if (isset($_POST['name'])) {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
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("/^[a-zA-Z ]*$/",$username)) {
$usernameErr = "Only letters";
}
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password = test_input($_POST["password"]);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// check weather password is alphanumeric
if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{6,}$/', $password))
{
$passwordErr = "Password must be alphanumeric and atleast 6 characters long!";
}
}
if (empty($_POST["age"])) {
$ageErr = "Age is required";
}
elseif($_POST["age"]< 17 ) {
$ageErr = "Age should be above 18 years";
}
else {
$age = $_POST["age"];
}
if($nameErr == "" && $emailErr == "" && $usernameErr == "" && $passwordErr == "" && $ageErr == "")
{
$check="SELECT * FROM users WHERE username = '$_POST[username]'";
$rs = mysqli_query($mysqli,$check);
$da = mysqli_fetch_array($rs, MYSQLI_NUM);
if($da[0] > 0) {
echo "Username Already in Exists<br/>";
}
else
{
$sql = "INSERT INTO users(`userid`,`username`, `password`, `email` , `name` , `age` )
VALUES ('','".$username."', '".$hashed_password."', '".$email."' , '".$name."' , '".$age."' )";
if (mysqli_query($mysqli, $sql)) {
echo "Registered successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
mysqli_close($mysqli);
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div style="padding-left: 250px" class="div1">
<h2 style="color:#009999">Registration Form :</h2>
<p><span class="error">All fields are required </span></p>
<form action="" method="post" enctype="multipart/form-data">
<span style="color:#0099ff">Name: </span>
<input type="text" name="name" class= "copy" style="margin-left: 52px" value ="<?php
if (isset($name))
echo $name;
?>">
<span class="error"> <?php echo $nameErr;?></span>
<br><br>
<span style="color:#0099ff"> E-mail: </span>
<input type="text" name="email" class= "copy" style="margin-left: 48px" value ="<?php
if (isset($email))
echo $email;
?>">
<span class="error"><?php echo $emailErr;?></span>
<br><br>
<span style="color:#0099ff"> Username: </span>
<input type="text" name="username" class= "copy" style="margin-left:26px" value ="<?php
if (isset($username))
echo $username;
?>">
<span class="error"> <?php echo $usernameErr;?></span>
<br><br>
<span style="color:#0099ff"> Password: </span>
<input type="password" name="password" class= "copy" style="margin-left:30px">
<span class="error"> <?php echo $passwordErr;?></span>
<br><br>
<span style="color:#0099ff"> Age : </span>
<input type="number" name="age" class= "copy" style="margin-left:62px" value ="<?php
if (isset($age))
echo $age;
?>">
<span class="error"> <?php echo $ageErr;?></span>
<br><br>
<input type="button" class="submit" name="submit" value="submit">
</form>
</div>
</body>
</html>
script.js
$(document).ready(function(){
$(".submit").click(function(){
var name = $("name").val();
var email = $("email").val();
var username = $("username").val();
var password = $("password").val();
var age = $("age").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name='+ name + '&email='+ email + '&username='+ username + '&password='+ password + '&age='+ age;
var dataString = $("form").serialize();
if(name==''|| email==''|| username==''|| password==''|| age=='')
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "index.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
connect.php
<?php
$databaseHost = 'localhost';
$databaseName = 'ajax1';
$databaseUsername = 'root';
$databasePassword = '';
$mysqli = mysqli_connect($databaseHost, $databaseUsername, $databasePassword, $databaseName);
?>
Update the submit button with submit class
<input type="button" class="submit" name="submit" value="submit">
Update the js code with . insted of # // as # is for id
$(".submit").click(function(){
Also, use the form serialize
var dataString = $("form").serialize();
Php code change the submit to name
if(isset($_POST['name']))

PHP form-calling function failing to work properly

I have my index.php form and if a valid student name and student number are entered I'd like "Student name and number are valid." to be echoed.
I have validated the student names and student numbers. However, even when entering a valid student name and student number the message echoed is "The information you have entered is not valid. Please enter your information again."
I'm calling the function validateStudent but I must be calling it in the wrong place or incorrectly. This function is called towards the end of the PHP scrip and just before the HTML starts. Thank you.
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
// Define and set variables
$student = "";
$studentname = "";
$studentnumber = "";
$studentfile = "student.txt";
$course = "";
$coursename = "";
$coursenumber = "";
$coursemax = 0;
$coursefile = "course.txt";
$in = fopen ('course.txt', 'r') or die ("course.txt cannot be opened for reading.");
// Sanitization and Validation coding will go here
if (isset($_POST['submit'])) {
$studentname = $_POST['studentname'];
$studentnumber = $_POST['studentnumber'];
}
if (isset($_POST['studentname'])) {
$studentname = strip_tags ($_POST['studentname']);
$studentname = htmlentities ($_POST['studentname']);
}
if (isset($_POST['studentnumber'])) {
$studentnumber = strip_tags ($_POST['studentnumber']);
$studentnumber = htmlentities ($_POST['studentnumber']);
}
if (isset($_POST['course'])) {
$course = strip_tags ($_POST['course']);
$course = htmlentities ($_POST['course']);
}
$studentname = trim($_POST['studentname']);
$studentnumber = trim($_POST['studentnumber']);
// Validate student name/number against text file
function validateStudent($studentName, $studentNumber)
{
$found = false;
$fh = fopen('student.txt', 'r');
while(($line = fgetcsv($fh, null, ':')) != false) {
if(count($line) > 1) {
if($line[0] == $studentName and $line[1] == $studentNumber) {
$found = true;
break;
}
}
}
return $found;
}
// Validate course name/number against text file
function validateCourse($courseName, $courseNumber, $courseMax)
{
$found = false;
$fh = fopen('course.txt', 'r');
while(($line = fgetcsv($fh, null, ':')) != false) {
if(count($line) > 1) {
if($line[0] == $courseName and $line[1] == $courseNumber and $line[2] == $courseMax) {
$found = true;
break;
}
}
}
return $found;
}
//$DB = fopen ($coursefile, 'r') or die ("$coursefile cannot be opened for reading.");
//while ($record = fgets ($DB) ) {
//$field = explode (":", htmlentities (trim ($record)));
//echo "<option value=\"$field[1]\">$field[0] $field[1] $field[2]</option>\n";
//}
//fclose ($DB);
if (isset ($_POST[$studentname], $_POST[$studentnumber])) {
validateStudent($_POST['$studentname'], $_POST['$studentnumber']);
echo 'Student name and number are valid.\n';
}
else {
echo '<p style="color: red; text-align: center; font-size: 15px; font-weight: bold;">**The information you have entered is not valid. Please enter your information again.**</p>';
}
?>
<html>
<head>
<title>Registration Form</title>
<style>
body{background-color: #ffffe6; width:610px;}
h1 {color: #29a3a3;}
.inputbox {padding: 7px; border: #FF9966 1px solid; border-radius: 4px;}
.btn {padding: 10px; background-color: #29a3a3; border: solid 1px #FF9966; border-radius: 4px; color: #FFFFFF; font-weight: bolder; cursor: pointer;}
</style>
</head>
<body>
<h1>Course Registration</h1>
<form method="post" action="index.php">
<fieldset><legend><strong>Student Information</strong></legend>
<dl>
<dt>Student Name:</dt>
<dd><input class="inputbox" name="studentname" type="text" id="studentname" value='<?php echo htmlentities($studentname) ?>' required autofocus placeholder="Please enter your first and last name" tabindex="10" size="50"></dd>
<br>
<br>
<dt>Student Number:</dt>
<dd><input class="inputbox" name="studentnumber" type="text" id="studentnumber" value='<?php echo htmlentities($studentnumber) ?>' required placeholder="Please enter using the following format: PX-03-046" tabindex="20" size="50"></dd>
</dl>
<br>
</fieldset>
<br>
<fieldset><legend><strong>Course Selection</strong></legend>
<br>
Select a Course:<select name="course" tabindex="30">\n";
<option value="-1" >Available Courses...</option>
<?php
while(($fields = fgetcsv($in, null, ':')) != false) {
if (count($fields) > 1) {
echo "
<option value=\"$fields[1]\">$fields[0] $fields[1]</option>";
}
}
?>
</select>
<br>
<br>
<br>
<br>
<br>
<br>
</fieldset>
<div>
<p>
<input name="reset" type="reset" tabindex="40" value="Clear Form" class="btn">
<input name="submit" type="submit" tabindex="50" value="Submit Form" class="btn">
</p>
</div>
</form>
</body>
</html>
Your code has a logical error:
if (isset ($_POST[$studentname], $_POST[$studentnumber])) {
validateStudent($_POST['$studentname'], $_POST['$studentnumber']);
echo 'Student name and number are valid.\n';
}
else {
echo '<p style="color: red; text-align: center; font-size: 15px; font-weight: bold;">**The information you have entered is not valid. Please enter your information again.**</p>';
}
your code should be:
if (isset ($_POST['studentname'], $_POST['studentnumber'])) {
if (validateStudent($_POST['studentname'], $_POST['studentnumber'])){
echo 'Student name and number are valid.\n';
}
else {
echo '<p style="color: red; text-align: center; font-size: 15px; font-weight: bold;">**The information you have entered is not valid. Please enter your information again.**</p>';
}
}
also you need a form to post your variables studentname and studentnumer like:
<form method="post">
<input type="text" name="studentname"/>
<input type="text" name="studentnumber"/>
<input type="submit" name="submit"/>
</form>
Your output is because your variables $_POST['studentname'] and $_POST['studentnumber'] are not set.

How to create a Dynamic Phonebook with Groups functionality

I want to create an online phone book where user can add as many contact as he want and he must be able to create and divide those contact into groups. For eg. Friends, Family etc. All the groups must be created or deleted by the user. Can anyone help me..
Any good tutorial or a book reference will do. I will be using PHP, MySQL and a little bit of AJAX and jQuery.
Thanks
http://learning-computer-programming.blogspot.com/2008/05/creating-simple-phone-book-in-php.html will give u general idea for creating phone book.
For categorizing ur book u would be needing another table storing the nature and id of the group(group_table) which u can thru a field in main phone_table
config.php
<?php
$dbname = "phonebook"; // name of database
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("phonebook") or die(mysql_error());
?>
add.php
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Phone book form</title>
<style type="text/css">
body {
margin: 0 12%;
width: 990px;
}
form {
width: 30em;
}
fieldset {
margin: 1em 0;
padding: 1em;
border-width : .1em ;
border-style: solid;
}
form div {
padding: 0.4em 0;
}
label {
display:block;
}
input {
width: 20em;
}
input.submit {
width: auto;
}
</style>
</head>
<body>
<p>Phone Book - Enter your contact's details</p>
<form method="post" action="index.php">
<p><label for="name">Name:</label><input type="text" name="username" maxlength="20" title="Enter Name"></p>
<p><label for="phonenumber">Phone Number</label><input type="text" maxlength="12" name="phone" title="Enter phone number"></p>
<p><label for="town">Town</label><input type="text" maxlength="25" title="Enter name of town" name="town"></p>
<input type="submit" name="save" value="Save Data">
</form>
</body>
</html><!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Phone book form</title>
<style type="text/css">
body {
margin: 0 12%;
width: 990px;
}
form {
width: 30em;
}
fieldset {
margin: 1em 0;
padding: 1em;
border-width : .1em ;
border-style: solid;
}
form div {
padding: 0.4em 0;
}
label {
display:block;
}
input {
width: 20em;
}
input.submit {
width: auto;
}
</style>
</head>
<body>
<p>Phone Book - Enter your contact's details</p>
<form method="post" action="index.php">
<p><label for="name">Name:</label><input type="text" name="username" maxlength="20" title="Enter Name"></p>
<p><label for="phonenumber">Phone Number</label><input type="text" maxlength="12" name="phone" title="Enter phone number"></p>
<p><label for="town">Town</label><input type="text" maxlength="25" title="Enter name of town" name="town"></p>
<input type="submit" name="save" value="Save Data">
</form>
</body>
</html>
index.php
<?php
include_once('config.php'); // call database login details page
if(isset($_POST['save'])) {
$name = strip_tags($_POST['username']);
$phone = strip_tags($_POST['phone']);
$town = strip_tags($_POST['town']);
$query = "INSERT INTO my_contacts(name,phonenumber,town) VALUES('$name', '$phone', '$town')";
$result = mysql_query($query);
if($result) {
echo "Data successfully stored!";
}
else {
echo "Data was NOT saved!";
echo "<p> Query: ' $query ' </p>";
}
}
$query = "SELECT * from my_contacts";
$result = mysql_query($query);
echo "<h3>My Contact's Data</h3>";
echo '<table border = "1">';
echo "<tr><td>Id</td><td>Name</td><td>Phone Number</td><td>Town</td></tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr><td>".$row['id']."</td><td><a href='index.php?ID=$row[id]'>".$row['name']."</a></td><td>".$row['phonenumber'].
"</td><td>".$row['town']."</td></tr>";
}
echo "</table>";
?>

Categories