Can't save on the database but my validation is working - php

Good day! I’m making a page where the students can update their profile. So I need a method of validation. YES my validation code is working, but it does not save in the database. And after she/he complete answering the fields that are required he will proceed to another page.
Here’s my code:
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: login.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to login.php");
}
// Everything below this point in the file is secured by the login system
// We can display the user's username to them by reading it from the session array. Remember that because
// a username is user submitted content we must use htmlentities on it before displaying it to the user.
// Database Variables (edit with your own server information)
$server = 'localhost';
$user = 'root';
$pass = '';
$db = 'testing';
// Connect to server and select databse.
mysql_connect("$server", "$user", "$pass")or die("cannot connect");
mysql_select_db("$db")or die("cannot select DB");
$sql ="SELECT * FROM users_info WHERE username = '".$_SESSION['user']['username']."' ";
$result=mysql_query($sql);
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
// define variables and set to empty values
$nameErr = $addressErr = $ageErr = $cellnoErr = $emailErr = $fathers_nameErr = $f_occupationErr = $mothers_nameErr = $m_occupationErr = "";
$name = $address = $age = $cellno = $telno = $email = $fathers_name = $f_occupation = $mothers_name = $m_occupation = "";
while($rows=mysql_fetch_array($result)){
$test=mysql_fetch_array($result);
if(!$result)
{
die("Error: Data not found..");
}
$name = $test['name'];
$address = $test['address'];
$age = $test['age'];
$cellno = $test['cellno'];
$telno = $test['telno'];
$email = $test['email'];
$fathers_name = $test['fathers_name'];
$f_occupation = $test['f_occupation'];
$mothers_name = $test['mothers_name'];
$m_occupation = $test['m_occupation'];
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
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 and white space allowed";
}
}
if (empty($_POST["address"]))
{$addressErr = "Address is required";}
else
{$address =($_POST["address"]);}
if (empty($_POST["age"]))
{$ageErr = "Age is required";}
else
{$age = ($_POST["age"]);}
if (empty($_POST["cellno"]))
{$cellnoErr = "Cellphone Number is required";}
else
{$cellno = ($_POST["cellno"]);}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
}
if (empty($_POST["fathers_name"]))
{$fathers_nameErr = "Father's Name is required";}
else
{$fathers_name = ($_POST["fathers_name"]);}
if (empty($_POST["f_occupation"]))
{$f_occupationErr = "Father's Occupation is required";}
else
{$f_occupation = ($_POST["m_occupation"]);}
if (empty($_POST["mothers_name"]))
{$mothers_nameErr = "Mother's Name is required";}
else
{$mothers_name =($_POST["mothers_name"]);}
if (empty($_POST["m_occupation"]))
{$m_occupationErr = "Mother's Occupation is required";}
else
{$m_occupation =($_POST["m_occupation"]);}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
mysql_query ("UPDATE `users_info` SET `name` ='$name', `address` ='$address',`age` ='$age', `cellno` ='$cellno' , `telno` ='$telno', `email` ='$email', `fathers_name` ='$fathers_name', `f_occupation` ='$f_occupation', `mothers_name` ='$mothers_name', `m_occupation` ='$m_occupation' WHERE username = '".$_SESSION['user']['username']."' ") or die(mysql_error());
header("Location: myprofile.php");
}
?>

You assign the variables and then redirect the page, maybe you should put them in an session also in order to shown them in the form.

Related

Login check with php MySQL and HTML

I am building a website's login page for an assignment. When I hash the password in the file that checks the users details it doesn't match with the stored hashed password in the database. The code always goes to the last else statement and relinks me to the login page with the wrong password sv equal to 1. If I don't hash the password, then copy and paste the hashed password from the database into the login form the login works. If anyone can help this would be greatly appreciated
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
$email = $_POST["email"];
$pass1 = $_POST["pass"];
$pass = hash('sha256', $pass1);
if(isset($_SESSION['user_type']))
{
unset($_SESSION['user_type']);
}
include("group_detail.php");
$query = "SELECT * from employee WHERE email = '$email' AND password = '$pass'";
$result_employee = $db->query($query);
$employee_row = mysqli_fetch_assoc($result_employee);
if(!empty($employee_row)){
$_SESSION['id'] = $employee_row['employee_ID'];
$_SESSION['name'] = $employee_row['name'];
$_SESSION['user_type'] = $employee_row['title'];
header('Location: homepage.html');
}else{
$query = "SELECT * from customer WHERE email = '$email' AND password = '$pass'";
$result_customer = $db->query($query);
$customer_row = mysqli_fetch_assoc($result_customer);
if(!empty($customer_row)){
$_SESSION['id'] = $customer_row['customer_ID'];
$_SESSION['name'] = $customer_row['name'];
$_SESSION['user_type'] = 'Customer';
$_SESSION['email'] = $customer_row['email'];
header('Location: homepage.html');
}
else{
$_SESSION['wrong_password'] = 1;
header('Location: login.php');
}
}
The registration code
<<?php
// this code checks all reuired fields are filled in appropriately
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
$nameErr = $phoneErr = $emailErr = $passwordErr = "";
$name = $address = $eircode = $email = $password = $phone = "";
$employee_ID = 0;
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo $nameErr;
if (empty($_POST["name"])) {
$nameErr = "Your name is required for registration";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and a space allowed";
}
}
if (empty($_POST["phone"])) {
$phoneErr = "Your phone number is required for registration";
} else {
$phone = test_input($_POST["phone"]);
}
if(empty($_POST['email']))
{
$emailErr = "Your Email is required for registration";
} else {
include ("group_detail.php");
$email_test = test_input($_POST["email"]);
$sql = "SELECT * from customer WHERE email = '$email_test'";
// Checks if another account uses this email
$result = $db->query($sql); // runs the query
$num_rows_3= mysqli_num_rows($result); // counts how many rows the query applies to
if($num_rows_3 == 0){
// Sets email value if no one else has used this email to sign up before
$email = test_input($_POST["email"]);
}
else{
// Lets the customer know this email is already in use
$emailErr = "Another account has previously been registered with this email. If this is you, you can login ";
}
}
if(empty($_POST['pass1']))
{
$passwordErr = "Password required";
} else {
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
if($pass1 == $pass2){
$pass = hash('sha256',$pass1);
// $pass = $pass1;
} else{
$passwordErr = "The passwords you enter must match";
}
}
if(empty($_POST['address']))
{
$address = "";
}else{
$address = test_input($_POST['address']);
}
if(empty($_POST['eircode']))
{
$eircode = "";
}else{
$eircode = test_input($_POST['eircode']);
}
if ($phoneErr == "" && $nameErr == "" && $passwordErr == "" && $emailErr == "")
{
// This code enters the data from the form into the customer table
include ("group_detail.php");
$q = "INSERT INTO customer(";
$q .= "name, phone, password, email, address, eircode";
$q .= ") VALUES (";
$q .= "'$name', '$phone', '$pass', '$email', '$address', '$eircode')";
$result = $db->query($q);
$sql = "SELECT customer_ID FROM customer ORDER BY customer_ID DESC LIMIT 1";
$result1 = $db->query($sql);
$row = mysqli_fetch_assoc($result1);
$_SESSION['customer'] = $row['customer_ID'];
header('Location: homepage.html');
}
}
?>
Solution
Your field is of the incorrect length. When you use the SHA256 hash function you get an output similar to:
ef92b778bafe771e89245b89ecbc08a44a4e166c06659911881f383d4473e94f // password123
If you're password field is only 15 characters then the saved value will be truncated:
ef92b778bafe771
However, during the comparison the full value from the logon script is used against the truncated version stored in the DB and therefore there is no match. Because, as you can see above, they aren't the same.
To fix you need to ALTER the table so that the field is at least varchar(64). Then new accounts will work as expected (note: old hashes still won't work - they need to be redone!)
Additional information
There are a few other issues with your code...
You shouldn't be putting variables directly into your code. Instead it is preferred to use a Prepared Statement with parametrised queries where you bind the variables later.
Which basically means in the query we use a place holder ? where we want a variable and then bind variables to the place holders later on
This is mainly to prevent SQL injection and protect you from incorrect input
It is best to use the PHP built in functions password_* to hash and verify passwords.
It's more secure than simply using hash
salts are auto-generated which protects you from things like rainbow tables
The default algorithm for password_hash requires a field length of 60+ characters
There's no need to store excess data in SESSION
The data is already stored in the DB so just fetch it as and when needed
It seems that you have one table for customers and another for employees
This isn't a good design there should be one table for users and then you can set flags for employee, customer, supplier etc.
Your test_input function carries out functions that are usually done on display not on save.
Below is a quick re-write that addresses some of the above (note: the below code is not complete it doesn't, for example, carry out all of the same validation - e.g. checking for illegal characters - it's just for illustrative purposes)
Register
<?php
ini_set('display_errors', true);
ini_set('log_errors', true);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
$errors = [];
$name = $_POST["name"] ?? null;
$phone = $_POST["phone"] ?? null;
$email = $_POST['email'] ?? null;
$address = $_POST['address'] ?? null;
$eircode = $_POST['eircode'] ?? null;
$pass1 = $_POST['pass1'] ?? null;
$pass2 = $_POST['pass2'] ?? null;
// Check passwords are the same and assign hash to $pass
$pass = $pass1 === $pass2 ? password_hash($pass1, PASSWORD_DEFAULT) : null;
// Check the required fields are present and not empty
if (!$name || !$phone || !$email || !$pass) {
$errors[] = "Required fields are missing.";
}
// Check if the email address already exists in the DB
$checkEmailExistsSQL = "SELECT COUNT(*) as countEmails FROM user WHERE email = ?";
$checkEmailExistsQuery = $mysqli->prepare($checkEmailExistsSQL);
$checkEmailExistsQuery->bind_param("s", $email);
$checkEmailExistsQuery->execute();
$emailExists = $checkEmailExistsQuery->get_result()->fetch_assoc()["countEmails"];
if ($emailExists !== 0) {
$errors[] = "The email address already exists in the DB";
}
// Check if there were errors and output them; then exit the script
if (count($errors)) {
foreach($errors as $error) {
echo $error, PHP_EOL;
}
exit;
}
include("group_detail.php");
$insertSQL = "
INSERT INTO user
(name, phone, password, email, address, eircode)
VALUES
(?, ?, ?, ?, ?, ?)
";
$insertQuery = $mysqli->prepare($insertSQL);
$insertQuery->bind_param("ssssss", $name, $phone, $pass, $email, $address, $eircode);
$insertQuery->execute();
// Success the user is registered
Logon
<?php
ini_set('display_errors', true);
ini_set('log_errors', true);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
$email = $_POST["email"] ?? null;
$pass = $_POST["pass"] ?? null;
// You can remove the old user id. But you don't need to
//
// There's no need to store excess data on the user in
// the SESSION super global; any data that you need
// access to can be retrieved from the DB at will.
// Copying data into SESSION only eats into memory.
unset($_SESSION["id"]);
// Check that something was submitted for email and password
if (!$email || !$pass) {
echo "Error: all fields need to be completed";
exit;
}
include("group_detail.php");
$sql = "SELECT id, password FROM user WHERE email = ?";
$query = $mysqli->prepare($sql);
$query->bind_param("s", $email);
$query->execute();
// Check to see if the email address is registered.
// Then check to see if the password is a match.
if (
!($user = $query->get_result()->fetch_assoc())
|| !password_verify($pass, $user["password"])
) {
echo "Error: the email address or password isn't correct";
exit;
}
// Success the user is logged on
//
$_SESSION["id"] = $user["id"];

Insert from php into mysql database

I've created an mail server with dovecot postfix and mysql.
The user should be able to create a new mail adress via a php webpage which will insert the data into the mysql database.
It also does insert it into the DB, but the connection to the mail server wont work with that credentials.
When I insert the same things myself sirectly into the DB it works, can you please give that code a look and tell me what might be wrong?
I think it has something todo with the password hash generation with doveadm.
<?php
ob_start();
session_start();
if( isset($_SESSION['user'])!="" ){
header("Location: home.php");
}
include_once 'dbconnect.php';
$error = false;
if ( isset($_POST['btn-signup']) ) {
// clean user inputs to prevent sql injections
$name = trim($_POST['name']);
$name = strip_tags($name);
$name = htmlspecialchars($name);
$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// basic name validation
if (empty($name)) {
$error = true;
$nameError = "Please enter your full name.";
} else if (strlen($name) < 3) {
$error = true;
$nameError = "Name must have atleat 3 characters.";
} else {
// check email exist or not
$query = "SELECT username FROM accounts WHERE username='$name'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count!=0){
$error = true;
$nameError = "Benutzeraccount existiert schon.";
}
}
//basic email validation
if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
} else {
// check email exist or not
$query = "SELECT resetmail FROM accounts WHERE resetmail='$email'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count!=0){
$error = true;
$emailError = "Kontakt E-Mail Adresse bereits in Verwendung.";
}
}
// password validation
if (empty($pass)){
$error = true;
$passError = "Please enter password.";
} else if(strlen($pass) < 6) {
$error = true;
$passError = "Password must have atleast 6 characters.";
}
// password encrypt using SHA256();
$password = shell_exec('/usr/bin/doveadm pw -s SHA512-CRYPT -p '. $pass);
// if there's no error, continue to signup
if( !$error ) {
$query = "INSERT INTO accounts(username,domain,at,complete,resetmail,password,quota,enabled,sendonly) VALUES('$name','chillihorse.de','#','test','$email','$password','2048','1','0')";
$res = mysql_query($query);
if ($res) {
$errTyp = "success";
$errMSG = "Successfully registered, you may login now";
unset($name);
unset($email);
unset($pass);
} else {
$errTyp = "danger";
$errMSG = "Something went wrong, try again later...";
}
}
}
?>

PHP MySQL Update not working when using variable in WHERE clause

I've checked dozens of threads on here and on other sites, and I cannot figure out why my code is not working. I am trying to use PHP to update MySQL using a variable to identify WHERE. The code I have works if I swap the variable for a number, and the variable works everywhere else in my script. It's just this one line that does not.
The line in question is:
$change = "UPDATE reg_info SET fname='$fname', lname='$lname', email='$email', explevel='$experience', addinfo='$additional', event='$regEvent' where id='$id'";
I've also tried the following:
$change = mysqli_query("UPDATE reg_info SET fname='$fname', lname='$lname', email='$email', explevel='$experience', addinfo='$additional', event='$regEvent' where id='$id'");
$change = "UPDATE reg_info SET fname='$fname', lname='$lname', email='$email', explevel='$experience', addinfo='$additional', event='$regEvent' where id=".$id;
$change = 'UPDATE reg_info SET fname="'.$fname.'", lname="'.$lname.'", email="'.$email.'", explevel="'.$experience.'", addinfo="'.$additional.'", event="'.$regEvent.'" where id='.$id;
From what I've seen on other threads, at least one of these should worked for me.
Can anyone point me in the right direction, please?
If it helps the entire string of PHP code is:
<?php
$fnameErr = $lnameErr = $emailErr = $experienceErr = $regEventErr = "";
$fname = $lname = $email = $experience = $regEvent = "";
$id = $_GET["id"];
$errors = "yes";
$servername = "localhost";
$username = "root";
$password = "5tTtFzaz6dIO";
$database = "project2db";
$conn = new mysqli($servername, $username, $password, $database);
$query = mysqli_query($conn, "SELECT * FROM reg_info where id=".$id);
$row = mysqli_fetch_array($query, MYSQLI_NUM);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
$fnameErr = "First name is required";
$errors = "yes";
} else {
$fname = test_input($_POST["fname"]);
if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
$fnameErr = "Only letters and white space allowed";
$errors = "yes";
}
else {
$errors = "no";
}
}
if (empty($_POST["lname"])) {
$lnameErr = "Last name is required";
$errors = "yes";
} else {
$lname = test_input($_POST["lname"]);
if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
$lnameErr = "Only letters and white space allowed";
$errors = "yes";
}
else {
$errors = "no";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
$errors = "yes";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email address";
$errors = "yes";
}
else {
$errors = "no";
}
}
if (empty($_POST["experience"])) {
$experienceErr = "Experience level is required";
$errors = "yes";
} else {
$experience = test_input($_POST["experience"]);
$errors = "no";
}
if (empty($_POST["additional"])) {
$regEvent = "";
} else {
$additional = test_input($_POST["additional"]);
}
if (empty($_POST["regEvent"])) {
$regEventErr = "Event is required";
$errors = "yes";
} else {
$regEvent = test_input($_POST["regEvent"]);
$errors = "no";
}
if($errors == "no") {
$change = 'UPDATE reg_info SET fname="'.$fname.'", lname="'.$lname.'", email="'.$email.'", explevel="'.$experience.'", addinfo="'.$additional.'", event="'.$regEvent.'" where id='.$id;
$result=$conn->query($change);
if ($result) {
echo '<script language="javascript">';
echo 'alert("New record created successfully.")';
echo '</script>';
header('Location: regtable.php');
} else {
echo '<script language="javascript">';
echo 'alert("Error. New record not created.")';
echo '</script>';
header('Location: regtable.php');
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I figured out the issue! Whenever the form was submitted, the new POST data did not have anything assigned to the html id="id" that was passed into the PHP code to create the $id variable.
Since there was nothing in the form, $id was null, and thus the query did not update the database, even though the query and connection were completely valid.
Thanks to everyone who posted comments and advice, I really appreciate it.
Since the query in itself is valid, I can only guess that somehow the data is causing the issue. Try the following, which escapes every value that will be used in the query:
$fname = mysqli_real_escape_string( $conn, $fname );
$lname = mysqli_real_escape_string( $conn, $lname );
$email = mysqli_real_escape_string( $conn, $email );
$experience = mysqli_real_escape_string( $conn, $experience );
$additional = mysqli_real_escape_string( $conn, $additional );
$regEvent = mysqli_real_escape_string( $conn, $regEvent );
$id = mysqli_real_escape_string( $conn, $id );
$change = "UPDATE reg_info SET fname='$fname', lname='$lname', email='$email', explevel='$experience', addinfo='$additional', event='$regEvent' where id='$id'";

How to echo Empty Entry Prohibited Message generated from a query in php?

I have a form which when submitted, checks this query ->
if(isset($_POST['update']) && !empty($_POST['name']) && !empty($_POST['reg_name']))
I want to echo a message "Please fill up all the required fields." if the required fields are not filled up.
In short, it should highlight the field name which is not filled up.
The Full Code:
include ('database/abcd.php');
if ($con->connect_error)
{
die("Connection failed: " . $con->connect_error);
}
if(isset($_POST['update']))
{
$error = array();
if(empty($_POST['name']))
$error[] = 'Please fill name field';
if(empty($_POST['reg_name']))
$error[] = 'Pleae fill reg_name field';
if(count($error) < 1)
{
$name = $_POST['name'];
$reg_name = $_POST['reg_name'];
$established = $_POST['established'];
$industry = $_POST['industry'];
$about = $_POST['about'];
$website = $_POST['website'];
$mail = $_POST['mail'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$city = $_POST['city'];
$facebook = $_POST['facebook'];
$wiki = $_POST['wiki'];
$twitter = $_POST['twitter'];
$google = $_POST['google'];
$member_username = $_SESSION['username'];
$process="INSERT INTO notifications (member_username, process, icon, class) VALUES ('$_POST[member_username]','$_POST[process]','$_POST[icon]','$_POST[class]')";
if (!mysqli_query($con,$process))
{
die('Error: ' . mysqli_error($con));
}
$sql = "UPDATE `company_meta` SET `name` = '$name', reg_name = '$reg_name', wiki = '$wiki', established = '$established', industry = '$industry', about = '$about', website = '$website', mail = '$mail', phone = '$phone', address = '$address', city = '$city', facebook = '$facebook', twitter = '$twitter', google = '$google' WHERE `member_username` = '$member_username'";
if ($con->query($sql))
{
header('Location: edit.php');
}
}
else
{
$errors = implode(',' $error);
echo $errors;
}
$con->close();
}
I think what you are pass in name or reg_name is check first .may be name or reg_name can content white space so that it not showing message otherwise above code is working correctly..
if(isset($_POST['update'])) // This first check whether it is an update call
{
$error = array(); // Here we initialize an array so that we can put the messages in it.
if(empty($_POST['name'])) // If the name field is empty, push a message in $error array.
$error[] = 'Please fill name field';
if(empty($_POST['reg_name'])) // Same as above field
$error[] = 'Pleae fill reg_name field';
if(count($error) < 1) // Now this checks if the $error array has no value. If it has value it means that either or both of the above fields are empty and the else block will be executed.
{
// Submit your form
}
else
{
$errors = implode(',' $error);
echo $errors;
}
}
else
{
// Update not triggered.
}

Validation works but does not save in database

I'm creating an update page for the students who wants to update or edit their information in their profile.. When they edit/update their record i need to validate.. My validation is working properly but it does not save in the database..
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: login.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to login.php");
}
// Everything below this point in the file is secured by the login system
// We can display the user's username to them by reading it from the session array. Remember that because
// a username is user submitted content we must use htmlentities on it before displaying it to the user.
// Database Variables (edit with your own server information)
$server = 'localhost';
$user = 'root';
$pass = '';
$db = 'testing';
// Connect to server and select databse.
mysql_connect("$server", "$user", "$pass")or die("cannot connect");
mysql_select_db("$db")or die("cannot select DB");
$sql ="SELECT * FROM users_info WHERE username = '".$_SESSION['user']['username']."' ";
$result=mysql_query($sql);
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
// define variables and set to empty values
$nameErr = $addressErr = $ageErr = $cellnoErr = $emailErr = $fathers_nameErr = $f_occupationErr = $mothers_nameErr = $m_occupationErr = "";
$name = $address = $age = $cellno = $telno = $email = $fathers_name = $f_occupation = $mothers_name = $m_occupation = "";
while($rows=mysql_fetch_array($result)){
$test=mysql_fetch_array($result);
if(!$result)
{
die("Error: Data not found..");
}
$name = $test['name'];
$address = $test['address'];
$age = $test['age'];
$cellno = $test['cellno'];
$telno = $test['telno'];
$email = $test['email'];
$fathers_name = $test['fathers_name'];
$f_occupation = $test['f_occupation'];
$mothers_name = $test['mothers_name'];
$m_occupation = $test['m_occupation'];
}
if (isset($_POST['save']))
{
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 and white space allowed";
}
}
if (empty($_POST["address"]))
{$addressErr = "Address is required";}
else
{
$address = ($_POST["address"]);
}
if (empty($_POST["age"]))
{$ageErr = "Age is required";}
if (empty($_POST["cellno"]))
{$cellnoErr = "Cellphone Number is required";}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
if(!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
if (empty($_POST["fathers_name"]))
{$fathers_nameErr = "Father's Name is required";}
if(!preg_match("/^[a-zA-Z ]*$/",$fathers_name))
{
$fathers_nameErr = "Only letters and white space allowed";
}
if (empty($_POST["f_occupation"]))
{$f_occupationErr = "Father's Occupation is required";}
if(!preg_match("/^[a-zA-Z ]*$/",$fathers_name))
{
$fathers_nameErr = "Only letters and white space allowed";
}
if (empty($_POST["mothers_name"]))
{$mothers_nameErr = "Mother's Name is required";}
if(!preg_match("/^[a-zA-Z ]*$/",$mothers_name))
{
$mothers_nameErr = "Only letters and white space allowed";
}
if (empty($_POST["m_occupation"]))
{$m_occupationErr = "Mother's Occupation is required";}
if(!preg_match("/^[a-zA-Z ]*$/",$m_occupation))
{
$m_occupationErr = "Only letters and white space allowed";
}
function validate($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
mysql_query ("UPDATE `users_info` SET `name` ='$name', `address` ='$address',`age` ='$age', `cellno` ='$cellno' , `telno` ='$telno', `email` ='$email', `fathers_name` ='$fathers_name', `f_occupation` ='$f_occupation', `mothers_name` ='$mothers_name', `m_occupation` ='$m_occupation' WHERE username = '".$_SESSION['user']['username']."' ") or die(mysql_error());
header("Location: myprofile.php");
}
}
?>
In common.php, includes session_start(); and everything. I just wonder why, if i update/edit the record it does not save in the database and no display in the next page where their profile is.
return ends execution of a function. You're returning in the validate() function before you execute the query:
function validate($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
// Doesn't go any further...
mysql_query ("UPDATE `users_info` SET `name` ='$name', `address` ='$address',`age` ='$age', `cellno` ='$cellno' , `telno` ='$telno', `email` ='$email', `fathers_name` ='$fathers_name', `f_occupation` ='$f_occupation', `mothers_name` ='$mothers_name', `m_occupation` ='$m_occupation' WHERE username = '".$_SESSION['user']['username']."' ") or die(mysql_error());
header("Location: myprofile.php");
}
The variables are not set in your function. Please see Variable Scope
You need to pass the variables into the function to use them. Also when calling return in your function it immediately stops the execution of that function. Your update is never triggered.
PHP Return
Not sure what the variable $data holds. And I do not see the call to the validate function
function validate($data, $test)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
$name = $test['name'];
$address = $test['address'];
$age = $test['age'];
$cellno = $test['cellno'];
$telno = $test['telno'];
$email = $test['email'];
$fathers_name = $test['fathers_name'];
$f_occupation = $test['f_occupation'];
$mothers_name = $test['mothers_name'];
$m_occupation = $test['m_occupation'];
mysql_query ("UPDATE `users_info` SET `name` ='$name', `address` ='$address',`age` ='$age', `cellno` ='$cellno' , `telno` ='$telno', `email` ='$email', `fathers_name` ='$fathers_name', `f_occupation` ='$f_occupation', `mothers_name` ='$mothers_name', `m_occupation` ='$m_occupation' WHERE username = '".$_SESSION['user']['username']."' ") or die(mysql_error());
header("Location: myprofile.php");
exit();
}

Categories