Hi am trying to write code that validates in the backend. The code should stop as soon as there is an error. In my case, even if the conditions are satisfied the code stops in the first name validation block itself.
Also I wish to have only backend validation.
Here is the php code clientRegister.php
<?php
require_once("connection.php");
session_start();
// define variables and set to empty values
$clientFirstName = $clientLastName =$clientEmail = $clientPassword =
$clientCPassword = $clientContact = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// First Name Validation
if (empty($_POST["clientFirstName"])) {
die("error: empty field");
} else {
$clientFirstName = test_input($_POST["clientFirstName"]);
// check if name only contains letters and whitespace
if (!preg_match("[a-zA-Z ]",$clientFirstName)) {
die("Error: Only letters and white space allowed");
}
}
// Last Name Validation
if (empty($_POST["clientLastName"])) {
die("error: empty field");
} else {
$clientLastName = test_input($_POST["clientLastName"]);
// check if name only contains letters and whitespace
if (!preg_match("[a-zA-Z ]",$clientLastName)) {
die("Error: Only letters and white space allowed");
}
}
// Email Validation
if (empty($_POST["clientEmail"])) {
die("error: empty field");
} else {
$clientEmail = test_input($_POST["clientEmail"]);
// check if e-mail address is well-formed
if (!filter_var($clientEmail, FILTER_VALIDATE_EMAIL)) {
die("Error: Invalid email format");
}
}
// Password Validation
if (empty($_POST["clientPassword"])) {
die("error: empty field");
}
// Confirm Password Validation
if (empty($_POST["clientCPassword"])) {
die("error: empty field");
}
if ($clientPassword != $clientCPassword) {
die("error: passwords mismatch");
}else{
$hashedClientPassword = password_hash($clientPassword, PASSWORD_DEFAULT);
}
if (empty($_POST["clientContact"])) {
die("error: empty field");
} else {
$clientContact = test_input($_POST["clientContact"]);
// check if number is correct
if (!preg_match("[0-9]",$clientContact)) {
die("error: Only 0-9 allowed");
}
}
$check_email = $conn->query("SELECT clientEmail FROM tbl_clients WHERE
clientEmail='$clientEmail'");
$emailCount=$check_email->num_rows;
if ($emailCount==0) {
$newClient = "INSERT INTO tbl_clients(clientFirstName, clientLastName,
clientEmail, clientPassword, clientContact) VALUES('$clientFirstName','$clientLastName','$clientEmail','$hashedClientPassword','$clientContact')";
if ($newClient === false){
$result = array();
$result[] = array("status" => "Error");
}else{
echo "Your have been signed up - please now Log In";
$result = array();
$result[] = array("First Name" => $clientFirstName, "Last Name" => $clientLastName, "Email" => $clientEmail, "Password" => $hashedClientPassword, "Contact" => $clientContact, "status" => "success");
}
}else {
echo "Already Exists";
$result = array();
$result[] = array("status" => "Error");
}
echo json_encode($result);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<h2>Reg User</h2>
<form method="post" action="clientRegister.php">
<label>
First Name:<input type="text" name="clientFirstName"><br/>
Last Name:<input type="text" name="clientLastName"><br/>
Email:<input type="text" name="clientEmail"><br/>
Password:<input type="password" name="clientPassword"><br/>
Confirm Password:<input type="password" name="clientCPassword"><br/>
Contact:<input type="text" name="clientContact"><br/>
<input type="submit" value="Register" name="submit">
</label>
</form>
</body>
</html>
You have missing pattern delimiters for your preg_match()
Replace your patterns with following sample:
if (!preg_match("[a-zA-Z ]",$clientFirstName)) {
die("Error: Only letters and white space allowed");
}
With:
if (!preg_match("/[a-zA-Z ]/",$clientFirstName)) {
die("Error: Only letters and white space allowed");
}
Also your
($clientPassword != $clientCPassword)
will always return false because you have not assigned new $_POST values to them. And since you have initialized both variables as empty. So (empty != empty) always return false.
So you should compare like this:
($_POST["clientPassword"] != $_POST["clientCPassword"])
Regarding your query, it was not executed
$newClient = "INSERT INTO tbl_clients(clientFirstName, clientLastName, clientEmail, clientPassword, clientContact) VALUES('$clientFirstName','$clientLastName','$clientEmail','$hashedClientPassword','$clientContact')";
Which I think you meant:
$newClient = $conn->query("INSERT INTO tbl_clients(clientFirstName, clientLastName, clientEmail, clientPassword, clientContact) VALUES('$clientFirstName','$clientLastName','$clientEmail','$hashedClientPassword','$clientContact')");
Note: Your queries are vulnerable to sql injection and you should use prepare statement
DEMO:
http://sandbox.onlinephpfunctions.com/code/d435ae025dc9e22b677823ff37712bb712b71e1b
You can test this file:
https://pastebin.com/AgfquEMC
Related
I'm practicing doing simple form validation and have come unstuck trying to use a function to replace code that I repeat several times throughout the validation script.
I am trying to write a function that saves an error message to an $errors array when validation fails for that form field.
The function I'm using does not return any error messages but does not display the message that is should do when validation fails.
I'm testing it on just one filed, the username field and with just one validation rule, username cannot be blank.
NB/ The form and validation worked when I was not trying to use a function.
Here is what I have, what a I doing wrong? I'm struggling to get to grips with functions :-(
functions.php
<?php
//Function to deal with saving error messages to errors array
// #param - 2 parameters. Name of field that has the error; Error message string
// #return - an error message string
function errorHandler($errField, $errMsg){
$errors[$errField] = $errMsg;
return $errors;
}
index.php
<?php
include_once '_includes/headers.php';
include_once '_includes/functions.php';
?>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
//Initialize variables
$data = array();//Store cleaned valid data for output
$errors = array();//Store error messages
$form_is_submitted = false;
$errors_detected = false;
if(isset($_POST['registerBtn'])){
$form_is_submitted = true;
//VALIDATE FORM
//Validate - Username
if (isset($_POST['username'])) {
$username = trim($_POST['username']);
//Username cannot be blank - validation
if($username !== ''){
$data['username'] = htmlentities($username);
//Get the length of the string
$stringLength = strlen($username);
//Username minimum 5 maximum 15 characters long - validation
if($stringLength < 5 || $stringLength > 15){
$errors_detected = true;
$errors['username'] = ' Invalid length. Must be between 5 - 15 characters!';
}else {
$data['username'] = htmlentities($username);
}
//Username must only be alphanumeric characters - validation
if(!ctype_alnum($username)){
$errors_detected = true;
$errors['username'] = ' Invalid characters. Alphanumeric characters only!';
}else {
$data['username'] = htmlentities($username);
}
}else {
$errors_detected = true;
//Call error message function
if($errors_detected === true){
errorHandler('username', ' Field cannot be blank!');
}
}
}else {
$errors_detected = true;
$errors['username'] = ' Is not set!';
}
//Validate - Email
if(isset($_POST['email'])){
$email = trim($_POST['email']);
//Email cannot be blank - validation
if($email !== ''){
$data['email'] = htmlentities($email);
//Email must be valid format - validation
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors_detected = true;
$errors['email'] = ' Invalid email format!';
}else {
$data['email'] = htmlentities($email);
}
}else{
$errors_detected = true;
$errors['email'] = ' Email address is required!';
}
}else {
$errors_detected = true;
$errors['email'] = " is not set!";
}
}
//Declare form output variable
$output = '';
//IF VALID SUBMISSION
if($form_is_submitted === true && $errors_detected === false){
$output .= '<h3>Form successfully submitted</h3>';
echo $output;
foreach($data as $keys => $values){
echo "<p>$keys : $values</p>";
}
} else {
//IF INVALID SUBMISSION
if($errors_detected === true){
$output .= '<h2>There are errors on the form</h2>';
echo $output;
foreach($errors as $key => $value){
echo "<p>" . htmlentities($key) . ':' . htmlentities($value) . "</p>";
}
}
//DISPLAY/REDISPLAY FORM
$self = htmlentities($_SERVER['PHP_SELF']);
$output ='
<form action="'. $self .'" method="post">
<fieldset id="registration">
<legend>Register</legend>
<p>Insert your profile information:</p>
<div>
<label for="username">Username</label>
<input id="username" name="username" type=text value="' . (isset($data['username']) ? $data['username'] : '') . '" />
</div>
<div>
<label for="email">Email</label>
<input id="email" name="email" type=email value="' . (isset($data['email']) ? $data['email'] : '') . '" />
</div>
<input type="submit" id="registerBtn" name="registerBtn" value="Register" />
</fieldset>
</form>
';
echo $output;
}
?>
<?php
include_once '_includes/footers.php';
?>
UPDATE:
I have updated my function to use the $errors array in my function. This should now no longer be a scope issue I think. As per Francesco Malatesta below ...
First of all, you should study something about objects, classes, exceptions and more complex stuff for this kind of job. I am assuming you want to learn about functions and do some practice.
You should, first of all, pass the errors array as a parameter.
Like this:
function errorHandler($errorsArray, $errField, $errMsg){
$errorsArray[$errField] = $errMsg;
return $errorsArray;
}
And then, in your index.php file:
errorHandler($errors, 'username', ' Field cannot be blank!');
This should work, because you must use the $errors array in your function. It's a scope-related problem.
However, after this, forget everything (well, not everything) and study OOP and Exceptions :)
Have you heard about Exceptions?
Simple example to use a exception:
<?php
try {
// your if's
if(40 > 30) {
throw new Exception("40 is a bigger");
}
} catch (Exception $error) {
echo 'Your error is: '.$error->getMessage();
}
?>
I would like to write a logic for data validation before insert into database. If the data not valid, then it will prompt user errors, but then I facing problem which not the logic that I wish:
(1) Message "Data successfully inserted!" shown even the error checking message was prompt.
(2) Message "Data successfully inserted!" shown even no data was entered in the form then click submit.
How should I change the logic to the one that I wish to have?
<?php
// Initialize variables to null.
$comp_nameError ="";
$compLicenseeNameError ="";
if(isset($_POST['comp_name'])) {$comp_name= $_POST['comp_name'];}
if(isset($_POST['comp_licensee_name'])) {$comp_licensee_name= $_POST['comp_licensee_name'];}
//On submitting form below function will execute
if (isset($_POST['submit'])) {
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//-------------------------Form Validation Start---------------------//
if (empty($_POST["comp_name"])) {
$comp_nameError = "Name is required";
} else {
$comp_name = test_input($_POST["comp_name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comp_name)) {
$comp_nameError = "Only letters and white space allowed";
}
}
if (empty($_POST["comp_licensee_name"])) {
$compLicenseeNameError = "Company Licensee Name is required";
} else {
$comp_licensee_name = test_input($_POST["comp_licensee_name"]);
}
//-------------------------Form Validation End---------------------//
// attempt a connection
$host="host=xx.xx.xx.xx";
$port="port=xxxx";
$dbname="dbname=xxxx";
$credentials="user=xxxxxx password=xxxxxxx";
$dbh = pg_connect("$host $port $dbname $credentials");
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
// execute query
$sql = "INSERT INTO t_comp(comp_name, comp_licensee_name)VALUES('$comp_name', '$comp_licensee_name')";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
echo "Data successfully inserted!";
// free memory
pg_free_result($result);
// close connection
pg_close($dbh);
}
//php code ends here
?>
<html>
<head>
<link rel="stylesheet" href="style/style.css" />
</head>
<body>
<div class="maindiv">
<div class="form_div">
<form method="post" action="compReg.php">
<span class="error">* required field.</span>
<br>
<hr/>
<br>
Company Name:<br><input class="input" type="text" name="comp_name" value="">
<span class="error">* <?php echo $comp_nameError;?></span>
<br>
Company Licensee:<br><input class="input" type="text" name="comp_licensee_name" value="">
<span class="error">* <?php echo $compLicenseeNameError;?></span>
<br>
<input class="submit" type="submit" name="submit" value="Submit">
</form>
</div>
</div>
</body>
</html>
I'd accumulate the errors into an array, and proceed to the insert part only if it's empty:
$errors = array();
if (empty($_POST["comp_name"])) {
$errors[] = "Name is required";
} else {
$comp_name = test_input($_POST["comp_name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comp_name)) {
$errors[] = "Only letters and white space allowed in the computer name";
}
}
if (empty($_POST["comp_licensee_name"])) {
$errors[] = "Company Licensee Name is required";
} else {
$comp_licensee_name = test_input($_POST["comp_licensee_name"]);
}
if (!empty($errors)) {
echo "The following errors occurred:<br/>" . implode('<br/>', $errors);
exit();
}
// If we didn't exit, continue to the insertion code
<?php
// Initialize variables to null.
$comp_nameError ="";
$compLicenseeNameError ="";
if(isset($_POST['comp_name'])) {$comp_name= $_POST['comp_name'];}
if(isset($_POST['comp_licensee_name'])) {
$comp_licensee_name= $_POST['comp_licensee_name'];}
//On submitting form below function will execute
if (isset($_POST['submit'])) {
// check boolean variable value
$is_valid = 1;
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//-------------------------Form Validation Start---------------------//
if (empty($_POST["comp_name"])) {
$comp_nameError = "Name is required";
} else {
$comp_name = test_input($_POST["comp_name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comp_name)) {
$validation_error = "Only letters and white space allowed";
$is_valid = 0;
}
}
if (empty($_POST["comp_licensee_name"])) {
$validation_error = "Company Licensee Name is required";
$is_valid =0;
} else {
$comp_licensee_name = test_input($_POST["comp_licensee_name"]);
}
//-------------------------Form Validation End---------------------//
// attempt a connection
if($is_valid == 1 ){
$host="host=xx.xx.xx.xx";
$port="port=xxxx";
$dbname="dbname=xxxx";
$credentials="user=xxxxxx password=xxxxxxx";
$dbh = pg_connect("$host $port $dbname $credentials");
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
// execute query
$sql = "INSERT INTO t_comp(comp_name, comp_licensee_name)VALUES('$comp_name', '$comp_licensee_name')";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
echo "Data successfully inserted!";
// free memory
pg_free_result($result);
// close connection
pg_close($dbh);
} else {
echo $validation_error;
die;
}
}
//php code ends here
?>
I attempted PHP and MySQL for the first time today following a tutorial, I was told using $MySQL was outdated and told to use $mysqli which I've attempted. I've uploaded my page to my server on ipage but am only getting a white screen. Its likely there's an error in my code, the server runs sql 5.5.32. The thing is I'm not even getting the echo back messages in Internet Explorer.
Edited with a bind / edited with 'db_table to 'db_table' /added form
<?php
//Database Setup
$mysqli_db = new mysqli($db_host,$db_name,$db_username,$db_password);
function webmailSignUp()
{
$webmailFullName = $_POST['webmailFullName'];
$webmailName = $_POST['webmailUserName'];
$webmailExEmail = $_POST['webmailExEmail'];
$webmailPhone = $_POST['webmailPhone'];
$webmailDOB = $_POST['webmailDOB'];
//Check that the fields are not empty
if ((!empty($webmailFullName)) or (!empty($webmailName)) or (!empty($webmailExEmail)) or (!empty($webmailPhone)) or (!empty($webmailDOB)))
{
//Check that there is no existing name in the table
if (checkUser($userName) == false)
{
//Adding the person to the Database Query
$query = "INSERT INTO '$db_table'(userFullName,userName,userExEmail,userPhone,userDOB) VALUES(?,?,?,?,?)";
//Binding to Prevent SQL injection
$requery = $mysqli_db->prepare($query);
$requiry->bind_param($webmailFullName,$webmailName,$webmailExEmail,$webmailPhone,$webmailDOB);
if ($requery->execute())
{
echo "Person has been added";
}
else
{
echo "bind failed";
}
}
else
{
echo "There is already a user registered with this username. Please try a different one.";
}
}
else
{
echo "One of your fields are blank! Please try again";
}
}
function checkUser($userNameCheck)
{
//Check the field userName is the same as the Posted Username
$Field = "userName"; //The Field to check
$query = "SELECT '$Field' WHERE '$Field'='$webmailName' FROM '$db_table' LIMIT 1";
$result = mysqli_query($query, $mysqli_db) or die(mysql_error());
if (!$row = mysqli_fetch_array($result) or die(mysql_error()))
{
return false; //username was not found in the field in the table
}
else
{
return true; //username was found in the field in the table
}
}
function close()
{
$mysqli_db->close();
}
//Main Code Sequence
error_reporting(-1);
ini_set('display_errors',1);
if(isset($_POST['webmailRegisterButton']))
{
echo("firstbit");
webmailSignUp();
close();
echo "End of Registration";
}
if(isset($_POST['webamilForgottenPWSubmit']))
{
webmailForgottenPassword();
close();
echo "End of Password Reset Request";
}
?>
Form:
<form method="POST" action="../_webmail/mailDB.php">
<div class="popupTitleCell"><h3>Name:</h3></div>
<div class="popupInputCell"><input type="text" name="webmailFullName" class="popupInputField"></div>
<div class="popupSpacer2"><p>Your Full Name (ex. John Coles)</p></div>
<div class="popupTitleCell"><h3>UserName:</h3></div>
<div class="popupInputCell"><input type="text" name="webmailUserName" value="#allcoles.com" class="popupInputField"></div>
<div class="popupSpacer2"><p>Preference email (ex john#allcoles.com)</p></div>
<div class="popupSpacer"><hr></div>
<div class="popupTitleCell"><h3>Existing Email:</h3></div>
<div class="popupInputCell"><input type="text" name="webmailExEmail" class="popupInputField"></div>
<div class="popupSpacer2"><p>REQUIRED to recieve SignIn details</p></div>
<div class="popupTitleCell"><h3>Phone Number:</h3></div>
<div class="popupInputCell"><input type="text" name="webmailPhone" class="popupInputField"></div>
<div class="popupSpacer2"><p>(allows for SMS confirmation)</p></div>
<div class="popupTitleCell"><h3>Date of Birth:</h3></div>
<div class="popupInputCell"><input type="text" id="datepickerRegister" name="webmailDOB"></div>
<div class="popupSpacer2"><p>Select your DOB from the calender</p></div>
<div class="popupSpacer"><hr></div>
<div class="popupButtonCell">
<button type="submit" name="webmailRegisterSubmit" value="register" id="submitButton" class="popupButton">
<span>Register</span></button></div>
</form>
Any help would be appreciated.
Can you also put the code of the form you are using to submit data on this file. Because if you directly open this file no code will be execute. Also please try this
<?php
//Main Code Sequence
error_reporting(-1);
ini_set('display_errors',1);
//Database Setup
$db_host = "localhost";
$db_name = "test";
$db_table = "emailUser";
$db_username = "root";
$db_password = "";
$mysqli_db = new mysqli($db_host,$db_username,$db_password, $db_name);
function webmailSignUp()
{
$webmailFullName = $_POST['webmailFullName'];
$webmailName = $_POST['webmailUserName'];
$webmailExEmail = $_POST['webmailExEmail'];
$webmailPhone = $_POST['webmailPhone'];
$webmailDOB = $_POST['webmailDOB'];
//Check that the fields are not empty
if ((!empty($webmailFullName)) or (!empty($webmailName)) or (!empty($webmailExEmail)) or (!empty($webmailPhone)) or (!empty($webmailDOB)))
{
//Check that there is no existing name in the table
if (checkUser($userName) == false)
{
//Adding the person to the Database Query
$query = "INSERT INTO '$db_table(userFullName,userName,userExEmail,userPhone,userDOB) VALUES($webmailFullName,$webmailName,$webmailExEmail,$webmailPhone,$webmailDOB)";
echo "Person has been added";
}
else
{
echo "There is already a user registered with this username. Please try a different one.";
}
}
else
{
echo "One of your fields are blank! Please try again";
}
}
function checkUser($userNameCheck)
{
//Check the field userName is the same as the Posted Username
$Field = "userName"; //The Field to check
$query = "SELECT '$Field' WHERE '$Field'='$webmailName' FROM '$db_table' LIMIT 1";
$result = mysqli_query($query, $mysqli_db) or die(mysql_error());
if (!$row = mysqli_fetch_array($result) or die(mysql_error()))
{
return false; //username was not found in the field in the table
}
else
{
return true; //username was found in the field in the table
}
}
function close()
{
$mysqli_db->close();
}
if(isset($_POST['webmailRegisterButton']))
{
echo("firstbit");
webmailSignUp();
close();
echo "End of Registration";
}
if(isset($_POST['webamilForgottenPWSubmit']))
{
webmailForgottenPassword();
close();
echo "End of Password Reset Request";
}
?>
I am writing a code for sign up form and data query on mysql database. The sign up form is here:-
<form action="index.php" method="POST" enctype="multipart/form-data">
First Name:<input type="text" name="name"><br>
Last Name : <input type="text" name="lname"><br>
Username : <input type="text" name="uname"><br>
Password : <input type="text" name="password"><br>
age : <input type="text" name="age"><br>
Email : <input type="text" name="email"><br>
Chose_Images : <input type="file" name="images"><br>
<input type="submit" name="submit">
</form>
Now, the index.php file is here:-
<?php
require'store.inc.php';
if (isset($_POST['submit'])) {
# code...
$first_name = mysql_real_escape_string(htmlentities($_POST['name']));
$last_name = mysql_real_escape_string(htmlentities($_POST['lname']));
$username = mysql_real_escape_string(htmlentities($_POST['uname']));
$password = mysql_real_escape_string(htmlentities($_POST['password']));
$password_hash = md5($password);
$age = mysql_real_escape_string(htmlentities($_POST['age']));
$email = mysql_real_escape_string(htmlentities($_POST['email']));
if (isset($first_name) && isset($last_name) &&isset($username) &&isset($password) &&isset($age) &&isset($email)) {
# code...
if (!empty($first_name) && !empty($last_name) &&!empty($username) &&!empty($password) &&!empty($age) &&!empty($email)) {
$errors = array();
// cheking string limit............
if (strlen($first_name) > 50) {
# code...
$errors[] = 'PLease dont cross the strign limit in first name colum'.'<br>';
}elseif (strlen($last_name) > 50) {
# code...
$errors[] = 'PLease dont cross the strign limit in first name colum'.'<br>';
}elseif (strlen($username) > 50) {
# code...
$errors[] = 'Your username is out of string limit'.'<br>';
}elseif (strlen($password) > 40) {
# code...
$errors[] = 'Your password is too long';
}elseif (strlen($age) > 50) {
# code...
$errors[] = 'you can not register into the site';
}elseif (strlen($email) > 50) {
# code...
$errors[] = 'You are out of Email string limit';
}
// coding of the first function start...
function connect_database(){
$server_connect = mysql_connect('localhost','root','');
$server_database = mysql_select_db('reg_log',$server_connect);
if ($server_connect && $server_database) {
# code...
return true;
} else {
return false;
}
}
// coding of the first function END...........
// coding of the function check_data() start...
function check_data(){
global $username;
connect_database();
$select = "SELECT `username` FROM `users` WHERE `username` = '$username'";
$select_query = mysql_query($select);
$num_rows = mysql_num_rows($select_query);
if ($num_rows == 1) {
# code...
return false;
} elseif ($num_rows == 0) {
# code...
return true;
}
}
//coding of the function End..................
// *********Varibles about Images which will be Global varibles..........Using addslashes for security
$image = addslashes(file_get_contents($_FILES['images']['tmp_name']));
$image_name = addslashes($_FILES['images']['name']);
$image_size = addslashes(getimagesize($_FILES['images']['tmp_name']));
//*******Varible Stored.....................................................
//Coding of Inserting Data in the database...By this function code will insert data in to database after all check...........
function insert_data(){
global $first_name,$last_name,$username,$password_hash,$age,$email,$images;
connect_database();
$insert = "INSERT INTO users VALUES('','$first_name','$last_name','$username','$password_hash','$age','$email','$images')";
$insert_query = mysql_query($insert);
if ($insert_query) {
# code...
return true;
}
}
}
}
}
if (empty($errors)) {
# code...
if (check_data()) {
# code...
insert_data();
}
}else{
foreach ($errors as $error) {
# code...
echo $error.'<br>';
}
}
?>
Both files are same. I mean, both codes are stored in the same file named 'index.php'. The 'store.inc.php' only contains:-
$server_connect = mysql_connect('localhost','root','');
$server_database = mysql_select_db('reg_log',$server_connect);
Now, When I open the index.php via localhost in my browser, It's showing an error:-
Fatal error: Call to undefined function check_data() in C:\xampp\htdocs\oop\user_reg\index.php on line 145
But, I have already a function named check_data() and the function alone is working good. But something bad happened with my code. I want to fix it and unable to do. I need help badly from you guys. Thank You.
you are using this function check_data() under an if , and then you call it from outside of the if.
try move this function exactly before this lines
if (empty($errors)) {
# code...
if (check_data()) {
I have heard of this issue but can't seem to figure it out. I have the database and table names correct. I am not finding any errors and i even inserted a table myself on phpmyadmin that worked but when I tried to do it on my site it doesnt work. I even tested the connection..Not sure what to do now
Maybe someone can take a look at my code and see if they notice anything
<?php
if(mysql_connect('<db>', '<un>', '<pw>') && mysql_select_db('smiles'))
{
$time = time();
$errors = array();
if(isset($_POST['guestbook_name'], $_POST['guestbook_message'])){
$guestbook_name = mysql_real_escape_string(htmlentities($_POST['guestbook_name']));
$guestbook_message = mysql_real_escape_string(htmlentities($_POST['guestbook_message']));
if (empty($guestbook_name) || empty($guestbook_message)) {
$errors[] = 'All Fields are required.';
}
if (strlen($guestbook_name)>25 || strlen($guestbook_message)>255) {
$errors[] = 'One or more fields exceed the character limit.';
}
if (empty($errors)) {
$insert = "INSERT INTO 'guestbook'VALUES('','$time','$guestbook_name','$guestbook_message')";
if($insert = mysql_query($insert)){
header('Location: '.$_SERVER['PHP_SELF']);
} else{
$errors[] = 'Something went wrong . Please try again.';
}
} else {
foreach($errors as $error) {
echo '<p>'.$error.'</p>';
}
}
}
//display entries
}
else {
'Fixing idiot';
}
?>
<hr />
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>" method="POST">
<p>Post Somethign</p>
<br />
Name:<br /><input type="text" name="guestbook_name" maxlength="25" />
<br />
Message:
<br />
<textarea name="guestbook_message" rows="6" coles="30"maxlength="255"></textarea>
<input type="submit" value="Post" />
</form>
Remove quotes from table name 'guestbook' and leave a space between it and values
Table name doesn't need quotes and supossing you're using id autoincrement, don't insert an empty string. So it should be:
$insert = "INSERT INTO guestbook VALUES('$time','$guestbook_name','$guestbook_message')";
Also, take a look at your $time value. What MySQL data type is?
After the insert, try to display the mysql error:
$conn = mysql_connect('<db>', '<un>', '<pw>');
mysql_query($insert)
if (mysql_errno($conn)){
$errors[] = mysql_error($conn);
}else{
header('Location: '.$_SERVER['PHP_SELF']);
}
EDIT: The hole snippet should be similar to:
<?php
$conn = mysql_connect('<db>', '<un>', '<pw>')
if( $conn && mysql_select_db('smiles')) //Note $conn
{
$time = time();
$errors = array();
if(isset($_POST['guestbook_name'], $_POST['guestbook_message'])){
$guestbook_name = mysql_real_escape_string(htmlentities($_POST['guestbook_name']));
$guestbook_message = mysql_real_escape_string(htmlentities($_POST['guestbook_message']));
if (empty($guestbook_name) || empty($guestbook_message)) {
$errors[] = 'All Fields are required.';
}
if (strlen($guestbook_name)>25 || strlen($guestbook_message)>255) {
$errors[] = 'One or more fields exceed the character limit.';
}
if (empty($errors)) {
mysql_query($insert)
$insert = "INSERT INTO guestbook VALUES('$time','$guestbook_name','$guestbook_message')";
if (mysql_errno($conn)){
$errors[] = mysql_error($conn);
}else{
header('Location: '.$_SERVER['PHP_SELF']);
}
} else {
foreach($errors as $error) {
echo '<p>'.$error.'</p>';
}
}
}
//display entries
}
you can try below query for insertion:
$insert = "INSERT INTO guestbook VALUES('','{$time}','{$guestbook_name}','{$guestbook_message}')";