PHP MySQL Update not working when using variable in WHERE clause - php

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'";

Related

Error Too Many Redirects

Trying to create my server.php script, so everythning was fine, till now. I wanted to prevent form resubmission and added header('location: index.php'); to my script. And then I faced the problem:ERR_TOO_MANY_REDIRECTS. And as many of you already understand my database was full of a junk. So, here is my code:
<?php
$username = $email = $password = "";
$usernameErr = $emailErr = $passwordErr = "";
$servername = 'localhost';
$serveruser = 'root';
$serverpassword = 'root';
$db = 'example';
$conn = new mysqli($servername, $serveruser, $serverpassword, $db);
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['register'])) {
$username = mysqli_real_escape_string($conn,$_POST['username']);
$email = mysqli_real_escape_string($conn,$_POST['email']);
$password = mysqli_real_escape_string($conn,$_POST['password']);
if(empty($username)) {
$usernameErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
if(!preg_match("/^[a-zA-z ]*$/", $username)){
$usernameErr = "Only letters and whitespaces allowed";
}
}
if(empty($email)) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Wrong email format";
}
}
if(empty($password)) {
$passwordErr = "Password required";
} else {
$password = test_input($_POST["password"]);
}
}
if ($usernameErr == "" && $emailErr == "" && $passwordErr == "") {
$sql = "INSERT INTO users (username, email, password)
VALUES('$username','$email','$password')";
if($conn->query($sql) === TRUE) {
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
header("location: index.php");
}
function test_input($data) {
$data = trim($data);
$data = htmlspecialchars($data);
$data = stripslashes($data);
return $data;
}
?>
To prevent TOO MANY REDIRECT put this code
if ($usernameErr == "" && $emailErr == "" && $passwordErr == "") {
$sql = "INSERT INTO users (username, email, password)
VALUES('$username','$email','$password')";
if($conn->query($sql) === TRUE) {
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
header("location: index.php");
}
within
if(isset($_POST['register'])) { //.................}
this block after checking errors
And to prevent re-submission of form use accepted answer on this question
Preventing form resubmission
You can do couple of ways to stop this:
1) You can write either of these, unset($_POST['register']); or $_POST = array(); just before header('location:index.php');so it will not pass through if(isset($_POST['register'])) condition and so it will not go in infinite loop.
2) Or use full URL in header like this: header("location: mydomain.com/index.php"); It will stop infinite loop too.

Check mysqli Insert Query excuted ok and display message and send email

I am creating a registration form for a project, nothing secure or advanced, i am still fairly new to php etc.
I insert the data needed to into a login table and a customer tbl, the data inserts fine. But i cant get the code to check that its worked and fire off a an email and display a message to the user.
I have tried using a value retrieved from the database which would only be there is the user registered successfuly.
if($userID != null)
{
$msg1 = "Thank You! you are now registered, please check your email for a verification link to verify your new account! ";
$col1 = "green";
//require_once "Mail.php";
require_once "inc/email.php";
}
I have also tried this
if($query)
{
$msg1 = "Thank You! you are now registered, please check your email for a verification link to verify your new account! ";
$col1 = "green";
//require_once "Mail.php";
require_once "inc/email.php";
}
Thanks,
Edit - Here is all the code,
<?php
include ("inc/mysql.php");
error_reporting(0);
$msg = "";
$col = 'green';
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$name = $email = $chkemail = $password = $chkpassword =$address = $towncity = $postcode = "";
//Required field validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$msg = "Name is required";
$col = 'red';
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$msg = "Email is required";
$col = 'red';
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["chkemail"])) {
$msg = "Please confirm your email address";
$col = 'red';
} else {
$chkemail = test_input($_POST["chkemail"]);
}
if (empty($_POST["password"])){
$msg = "Please enter a password";
$col = 'red';
}
if (empty($_POST["chkpassword"])){
$msg = "Please confirm your password ";
$col = 'red';
} else{
$chkpassword = test_input($_POST["chkpassword"]);
if(($_POST["password"]) != $chkpassword) {
$msg = "Please check your password is correct";
$col = 'red';
} else{
$password = test_input($_POST["password"]);
}
}
if (empty($_POST["address"])) {
$msg = "Please enter the first line of your address";
$col = 'red';
} else {
$address = test_input($_POST["address"]);
}
if (empty($_POST["towncity"])) {
$msg = "Please enter the first line of your Town or City";
$col = 'red';
} else {
$towncity= test_input($_POST["towncity"]);
}
if (empty($_POST["postcode"])) {
$msg = "Please enter your postcode";
$col = 'red';
} else {
$postcode = test_input($_POST["postcode"]);
$customerVeri = "N";
if($customerVeri == "N"){
$name = mysqli_real_escape_string($db, $name);
$email = mysqli_real_escape_string($db, $email);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password.substr($email,0,3));
$chkpassword = md5($password.substr($email,0,3));
$verifyLink = md5(substr($name,0,3).substr($email,0,3));
$sql="SELECT customerEmail FROM customer_tbl WHERE customerEmail='$email'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if(mysqli_num_rows($result) == 1)
{
$msg1 = "Sorry...This email already exists, please enter another or login...";
$col1 = "red";
}
else
{
$query = mysqli_query($db, "INSERT INTO login_tbl (customerEmail, customerPassword)VALUES ('$email', '$password')");
$sql="SELECT userID FROM login_tbl WHERE customerEmail='$email'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
$userID = $row['userID'];
$query2 = mysqli_query($db, "INSERT INTO customer_tbl (customerName, userID, customerEmail, customerPassword, customerAddress, customerTowncity, customerPostcode, customerVerified, customerVerifiedlink)VALUES ('$name', '$userID', '$email', '$password','$address','$towncity','$postcode','$customerVeri','$verifyLink')");
echo("Error description: " . mysqli_error($db));
}
}
}
}
if($userID != null)
{
$msg1 = "Thank You! you are now registered, please check your email for a verification link to verify your new account! ";
$col1 = "green";
//require_once "Mail.php";
require_once "inc/email.php";
}
echo '<div style="color:'.$col.'">';
echo $msg;
echo '</div>';
echo '<div style="color:'.$col1.'">';
echo $msg1;
echo '</div>';
?>
Seems there was no issue, but instead an issue with the email.php that stopped the rest of the statement being executed. Now to pick that to bits. Sometimes a few hours away from the screen is all it needs!
Thanks all that answered..
You shouldn't check every statement for the success
The modern programming doesn't work this way. Any statement can report an error in case one occurs. While if there was no error, then everything went all right.
So, just get rid of all conditions and send your email.

Validating html forms using php

I have a form which needs to be validated using php before inserting form values into a database.
it worked just fine if the fields are empty, however when I included a code to ensure only letters and white spaces are allowed in the first and last name fields it broke the validation process i.e. when I typed in any combinations of letters in the fields it displayed an error message saying "only letters and white spaces are required".
Secondly, when all fields are empty, the form displays the appropriate error message and does no submit the form to the database. However, when I type in a message in the textarea field with other fields empty, the form submits the data to the database as well as displays error messages for the other empty fields.
Any help to resolve these issues would be much appreciated.
Here is the code:
<?php
$fnameErr = $lnameErr = $emailErr = $amountErr = $phoneErr = $genderErr = $messageErr = $categoryErr = $countryErr = "";
$fname = $lname = $email = $amount = $phone = $gender = $message = $category = $country = "";
$ipaddress ="";
$defaultMessage = "Please type your message here.";
$formErrors = false;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//for first name
$name= $_POST["fname"];
if (empty($_POST["fname"])){
$fnameErr = "Please, enter your first name";
$formErrors = true;
}elseif(!preg_match("/^[a-zA-Z]*&/", $name)){
$fnameErr = "Only letters and white spaces are allowed in the first name field";
$formErrors = true;
}else{
$fname = $_POST["fname"];
$formErrors = false;
}
//Last Name match
// for last name
$name2= $_POST["lname"];
if (empty($_POST["lname"])){
$lnameErr = "Please, enter your last name";
$formErrors = true;
}elseif(!preg_match("/^[a-zA-Z]*&/", $name2)){
$lnameErr = "Only letters and white spaces are allowed in the Last name field";
$formErrors = true;
}else{
$lname = $_POST["lname"];
$formErrors = false;
}
// for email format
$emailf =($_POST["email"]);
if (empty($_POST["email"])) {
$emailErr = "Please, enter your email";
$formErrors = true;
}elseif (!filter_var($emailf, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
$formErrors = true;
}else {
$email = $_POST["email"];
$formErrors = false;
}
//for phone
if (empty($_POST["phone"])){
$phoneErr = "Please, enter your phone number";
$formErrors = true;
}else{
$phone = $_POST["phone"];
$formErrors = false;
}
// for amount
if (!isset($_POST["amount"])) {
$amountErr = "You must select an amount";
$formErrors = true;
}
else {
$amount = $_POST["amount"];
$formErrors = false;
}
// for gender
if (!isset($_POST["gender"])) {
$genderErr = "You must select your gender";
$formErrors = true;
}
else {
$gender = $_POST["gender"];
$formErrors = false;
}
// for country
if (empty($_POST["country"]) || $_POST["country"] == "Country") {
$countryErr = "Please, select your country";
$formErrors = true;
}
else {
$country = $_POST["country"];
$formErrors = false;
}
// for category
if (empty($_POST["category"]) || $_POST["category"] == "Category") {
$categoryErr = "Please, select a category";
$formErrors = true;
} else {
$category = $_POST["category"];
$formErrors = false;
}
// for message
if (empty($_POST["message"]) || $_POST["message"] == $defaultMessage){
$messageErr = "Please type your prayer request";
$formErrors = true;
}else{
$message = $_POST["message"];
$formErrors = false;
}
if (empty($formErrors) ) {
//connect to database
require_once("../../includes/connect_to_db.php");
// set time zone to uk
$timezone = date_default_timezone_set("Europe/london");
//setting values
$Timestamp = date('Y-m-d h:i:s');
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$gender = isset($_POST["gender"]) ? $_POST["gender"] : '';
$message = $_POST["message"];
$country = $_POST["country"];
$category = $_POST["category"];
//echo $gender . "value";
//var_dump(billingDate);
// var_dump($customer);
//Escape all string
$firstname = mysqli_real_escape_string($connection, $fname);
$lastname = mysqli_real_escape_string($connection, $lname);
$emailNew = mysqli_real_escape_string($connection, $email);
$phoneNew = mysqli_real_escape_string($connection, $phone);
$genderNew = mysqli_real_escape_string($connection, $gender);
$messageNew = mysqli_real_escape_string($connection, $message);
$countryNew = mysqli_real_escape_string($connection, $country);
$categoryNew = mysqli_real_escape_string($connection, $category);
//querying the database
$query = "INSERT into counselling ( ";
$query .= "Timestamp, FirstName, LastName, ";
$query .= "Email, PhoneNumber, Category, Country, Gender, Message";
$query .= ")";
$query .= "VALUES ('{$Timestamp}', '{$firstname}', '{$lastname}', ";
$query .= "'{$emailNew}', '{$phoneNew}', '{$categoryNew}', '{$countryNew}', '{$genderNew}', '{$messageNew}' ";
$query .= ")";
echo $query;
$result = mysqli_query($connection, $query) ;
//check for query error
if($result){
//query success redirect_to ("somepage.php");
//redirect_to("confirmation.php");
echo "Success";
} else {
die("Database query failed");
}
} // end of if
} // End of form submission conditional.
?>
Your need to refactor your code with proper logic.
<?php
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$errors = array();
if(trim($fname) == ''){
$errors['fname'] = "First name is required";
}
if(trim($lname) == ''){
$errors['lname'] = "Last name is required";
}
if(count( $errors) > 0){
//form invalid
}
else{
//form is valid
}

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();
}

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

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.

Categories