I am trying to add products through PHP inside PHP MySQL but somehow the code is not inserting the data inside the database while running without any errors. I am not sure if there's any mistake in the PHP or in the PHP MySQL. I hope I'll get some answers here. Here's my code:
HTML
<div id="content">
<form method="GET" action="" enctype="multipart/form-data">
<input type="text" name="productName" value="" placeholder="Product Name">
<input type="text" name="quantity" placeholder="Quantity">
<input type="text" name="regularPrice" placeholder="Regular Price">
<input type="text" name="discountedPrice" placeholder="discountedPrice">
<input type="file" name="uploadfile" value="" />
<input type="text" name="category" placeholder="Category">
<div>
<button type="submit" name="productImage">Add Product</button>
</div>
</form>
</div>
PHP CODE:
<?php
error_reporting(0);
?>
<?php
$msg = "";
// If upload button is clicked ...
if (isset($_GET['productImage']))
{
$productName = $_GET['productName'];
$quantity = $_GET['quantity'];
$regPrice = $_GET['regularPrice'];
$discPrice = $_GET['discountedPrice'];
$productImage = $_FILES["uploadfile"]["name"];
$tempname = $_FILES["uploadfile"]["tmp_name"];
$category = $_GET['category'];
$folder = "asset/images/products/".$productImage;
$host = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbname = "kewalsmart";
// Creating Connection
$conn = new mysqli($host, $dbUsername, $dbPassword, $dbname);
if(mysqli_connect_error())
{
die('Connection Error('. mysql_connect_errno().')'. mysqli_connect_error());
}
else
{
$SELECT = "SELECT email From products Where product_name = ? Limit 1";
// Get all the submitted data from the form
$INSERT = "INSERT INTO products (product_name, quantity, regular_price, discounted_price, product_image, category) VALUES ('$productName, $quantity, $regPrice, $discPrice, $productImage, $category')";
// Prepare Statement
$stmt = $conn->prepare($SELECT);
$stmt->bind_param("s", $productName);
$stmt->execute();
$stmt->bind_result($productName);
$stmt->store_result();
$rnum = $stmt->num_rows;
if($rnum==0)
{
$stmt->close();
$stmt = $conn->prepare($INSERT);
$stmt->bind_param("ssiiss", $productName, $quantity, $regPrice, $discPrice, $productImage, $category);
$stmt->execute();
?>
<script type="text/javascript">
window.alert("Product Added Successfully");
window.location.href = "index.html";
</script>
<?php
}
else
{
?>
<script>
window.alert("Something's Wrong");
setTimeout(function(){ window.location.href = "./"; }, 2000);
</script>
<?php
}
// Now let's move the uploaded image into the folder: image
if (move_uploaded_file($tempname, $folder))
{
$msg = "Image uploaded successfully";
}
else
{
$msg = "Failed to upload image";
}
$stmt->close();
$conn->close();
}
}
?>
Thank you in advance!
I'm trying to figure out how to upload a file into the database where that form contains multiple textfields. I uploaded a BLOB field into the database. So as I try to search the field using the ID number, it will retrieve me the values associated with it. Which works fine, so I added the function of being able to upload a file into that specific id number. I get all sorts of errors and I would like to have an assistance with it. Anyone care to help out? Here are the codes:
<?php
$host = "localhost";
$user = "root";
$password ="";
$database = "ntmadb";
$id = "";
$firstname = "";
$lastname = "";
$username = "";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// connect to mysql database
try{
$connect = mysqli_connect($host, $user, $password, $database);
} catch (mysqli_sql_exception $ex) {
echo 'Error';
}
// get values from the form
function getPosts()
{
$posts = array();
$posts[0] = $_POST['id'];
$posts[1] = $_POST['firstname'];
$posts[2] = $_POST['lastname'];
$posts[3] = $_POST['username'];
return $posts;
}
// Search
if(isset($_POST['search']))
{
$data = getPosts();
$search_Query = "SELECT * FROM members WHERE id = $data[0]";
$search_Result = mysqli_query($connect, $search_Query);
if($search_Result)
{
if(mysqli_num_rows($search_Result))
{
while($row = mysqli_fetch_array($search_Result))
{
$id = $row['id'];
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$username = $row['username'];
}
}else{
echo 'No Data For This Id';
}
}else{
echo 'Result Error';
}
}
// Edit
if(isset($_POST['update']))
{
$data = getPosts();
$update_Query = "UPDATE `members` SET `firstname`='$data[1]',`lastname`='$data[2]',`username`='$data[3]' WHERE `id` = $data[0]";
try{
$update_Result = mysqli_query($connect, $update_Query);
if($update_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Updated';
}else{
echo 'Data Not Updated';
}
}
} catch (Exception $ex) {
echo 'Error Update '.$ex->getMessage();
}
}
<!--UPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOAD -->
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', '', 'ntmadb');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
// Create the SQL query
$query = "
INSERT INTO `members` (
`data`
)
VALUES (
'{$data}' NOW()
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
?>
and here is the html file:
<!DOCTYPE Html>
<html>
<head>
<title>PHP INSERT UPDATE DELETE SEARCH</title>
</head>
<body>
<form action="index4.php" method="post" enctype="multipart/form-data" >
<input type="number" name="id" placeholder="Id" value="<?php echo $id;?>"><br><br>
<input type="text" name="firstname" placeholder="First Name" value="<?php echo $firstname;?>"><br><br>
<input type="text" name="lastname" placeholder="Last Name" value="<?php echo $lastname;?>"><br><br>
<input type="text" name="username" placeholder="User Name" value="<?php echo $username;?>"><br><br>
<div>
<p>
<!-- Input For Edit Values -->
<input type="submit" name="update" value="Update">
<!-- Input For Find Values With The given ID -->
<input type="submit" name="search" value="Find">
</p>
<p>
<input type="file" name="uploaded_file">
<br>
<input type="submit" value="Upload file">
</p>
</div>
</form>
</body>
</html>
Thanks to anyone who can provide me with help. :)
Yahallo! I have a problem in searching the user in the database and displaying them into the textfields. I have set everything to query and search the user by typing the lastname but it gives me an error
Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1' .
<?php
$host = "localhost";
$user = "root";
$password ="";
$database = "ntmadb";
$id = "";
$firstname = "";
$lastname = "";
$username = "";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// connect to mysql database
try{
$connect = mysqli_connect($host, $user, $password, $database);
} catch (mysqli_sql_exception $ex) {
echo 'Error';
}
// get values from the form
function getPosts()
{
$posts = array();
$posts[0] = $_POST['id'];
$posts[1] = $_POST['firstname'];
$posts[2] = $_POST['lastname'];
$posts[3] = $_POST['username'];
return $posts;
}
// Search
if(isset($_POST['search']))
{
$data = getPosts();
$search_Query = "SELECT * FROM members WHERE lastname = $data[2]";
$search_Result = mysqli_query($connect, $search_Query);
if($search_Result)
{
if(mysqli_num_rows($search_Result))
{
while($row = mysqli_fetch_array($search_Result))
{
$id = $row['id'];
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$username = $row['username'];
}
}else{
echo 'No Data For This Id';
}
}else{
echo 'Result Error';
}
}
?>
<!DOCTYPE Html>
<html>
<head>
<title>PHP INSERT UPDATE DELETE SEARCH</title>
</head>
<body>
<form action="index44.php" method="post">
<input type="text" name="id" placeholder="Id" value="<?php echo $lastname;?>"><br><br>
<input type="text" name="firstname" placeholder="First Name" value="<?php echo $firstname;?>"><br><br>
<input type="text" name="lastname" placeholder="Last Name" value="<?php echo $lastname;?>"><br><br>
<input type="text" name="username" placeholder="User Name" value="<?php echo $username;?>"><br><br>
<div>
<!-- Input For Edit Values -->
<input type="submit" name="update" value="Update">
<!-- Input For Find Values With The given ID -->
<input type="submit" name="search" value="Find">
</div>
</form>
</body>
</html>
Can someone assist in fixing it? Thank you!
Try below query.
$search_Query = "SELECT * FROM members WHERE lastname = '".$data[2]."'";
Try this:
$temp_lastname = $data[2];
$search_Query = "SELECT * FROM `members` WHERE `lastname` = '$temp_lastname'";
I want to delete data from database if the same exists in database, but my coding is not working. if user input data is not matching then a error warning should be display.
HTML
<form action="" method="POST">
<input type="number" name="student_id_delete" placeholder="Enter Student ID"/>
<input type="submit" name="sub_delete" value="Delete"/>
</form>
PHP
define('HOST','localhost');
define('USER','root');
define('PASSWORD_HOST','');
define('DATABASE','ubhs');
if(defined('HOST') && defined('USER') && defined('PASSWORD_HOST') && defined('DATABASE')){
$conn = mysqli_connect(HOST, USER, PASSWORD_HOST, DATABASE);
}else{
die(connection_failed.mysqli_connection_error());
}
$userinput = true;
$student_id_delete = $_POST['student_id_delete'];
if(isset($_POST['sub_delete'])){
if(empty($student_id_delete)){
$userErr1 = "Please enter student ID to be deleted";
$userinput = false;
}
$sql = "SELECT FROM student_info WHERE id=$student_id_delete";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result)<0){
echo "student could not be found in database";
$userinput = false;
}
if($userinput==true){
$sql = "DELETE FROM student_info WHERE id=$student_id_delete";
if(mysqli_query($conn,$sql)){
echo "Success";
}else{
echo "Couldn't deleted";
}
}
}
Try below snippet :
HTML code :
<form action="" method="POST">
<input type="number" name="student_id_delete" placeholder="Enter Student ID"/>
<input type="submit" name="sub_delete" value="Delete"/>
</form>
PHP code :
<?php
define('HOST','localhost');
define('USER','root');
define('PASSWORD_HOST','');
define('DATABASE','ubhs');
if(defined('HOST') && defined('USER') && defined('PASSWORD_HOST') && defined('DATABASE'))
{
$conn = mysqli_connect(HOST, USER, PASSWORD_HOST, DATABASE);
}
else
{
die(connection_failed.mysqli_connection_error());
}
$userinput = true;
$student_id_delete = $_POST['student_id_delete'];
if(isset($_POST['sub_delete']))
{
if(empty($student_id_delete))
{
$userErr1 = "Please enter student ID to be deleted";
$userinput = false;
}
if($userinput==true)
{
$sql = "DELETE FROM student_info WHERE id=".mysqli_real_escape_string($student_id_delete); // sql injection prevention.
mysqli_query($conn,$sql);
echo "Records deleted: ".mysqli_affected_rows($conn);
}
}
?>
OUTPUT :
Records deleted: 1
Records deleted: 0
i am using below code for customer Registration & Login , it's working fine.
db connection
<?php
class Database
{
private $host = "localhost";
private $db_name = "dbname";
private $username = "root";
private $password = "helpme";
public $conn;
public function dbConnection()
{
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
?>
register
<?php
session_start();
require_once 'class.user.php';
$reg_user = new USER();
if($reg_user->is_logged_in()!="")
{
$reg_user->redirect('home.php');
}
if(isset($_POST['btn-signup']))
{
$uname = trim($_POST['txtuname']);
$email = trim($_POST['txtemail']);
$upass = trim($_POST['txtpass']);
$cpass = trim($_POST['txtcpass']);
$phone = trim($_POST['phone']);
$street_address = trim($_POST['street_address']);
$street_address_2 = trim($_POST['street_address_2']);
$city = trim($_POST['city']);
$state = trim($_POST['state']);
$zip_code = trim($_POST['zip_code']);
$country = trim($_POST['country']);
$code = md5(uniqid(rand()));
$stmt = $reg_user->runQuery("SELECT * FROM tbl_users WHERE userEmail=:email_id");
$stmt->execute(array(":email_id"=>$email));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
$msg = "
<div class='alert alert-error'>
<button class='close' data-dismiss='alert'>×</button>
<strong>Sorry !</strong> email allready exists , Please Try another one
</div>
";
}
if($upass != $cpass){
$msg = "passwords doesn't match";
}
else
{
if($reg_user->register($uname,$email,$upass, $code, $phone, $street_address, $street_address_2 , $city , $state , $zip_code , $country ))
{
$id = $reg_user->lasdID();
$key = base64_encode($id);
$id = $key;
$message = "
Hello $uname,
<br /><br />
Welcome to designer!<br/>
To complete your registration please , just click following link<br/>
<br /><br />
<a href='http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]'.'verify.php?id=$id&code=$code'>Click HERE to Activate :)</a>
<br /><br />
Thanks,";
$subject = "Confirm Registration";
$reg_user->send_mail($email,$message,$subject);
$msg = "
<div class='alert alert-success'>
<button class='close' data-dismiss='alert'>×</button>
<strong>Success!</strong> We've sent an email to $email.
Please click on the confirmation link in the email to create your account.
</div>
";
}
else
{
echo "sorry , Query could no execute...";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body id="login">
<div class="container">
<?php if(isset($msg)) echo $msg; ?>
<form class="form-signin" method="post">
<h2 class="form-signin-heading">Sign Up</h2><hr />
<input type="text" class="input-block-level" placeholder="Username" name="txtuname" required />
<input type="email" class="input-block-level" placeholder="Email address" name="txtemail" required />
<input id="pass1" type="password" class="input-block-level" placeholder="Password" name="txtpass" required />
<input id="pass2" type="password" class="input-block-level" placeholder="confirm Password" name="txtcpass" required />
<input type="text" class="input-block-level" placeholder="Telephone" name="phone" />
<input type="text" class="input-block-level" placeholder="Street Address" name="street_address" />
<input type="text" class="input-block-level" placeholder="Stree Address 2" name="street_address_2" />
<input type="text" class="input-block-level" placeholder="city" name="city" />
<input type="text" class="input-block-level" placeholder="state" name="state" />
<input type="text" class="input-block-level" placeholder="zip code" name="zip_code" />
<input type="text" class="input-block-level" placeholder="country" name="country" />
<hr />
<input class="btn btn-large btn-primary" name="btn-signup" type="submit" id="btnSubmit" value="Sign Up" onclick="return comparePasswords()" />
Sign In
</form>
</div> <!-- /container -->
<script src="vendors/jquery-1.9.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
class.user.php
<?php
require_once 'dbconfig.php';
class USER
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
public function lasdID()
{
$stmt = $this->conn->lastInsertId();
return $stmt;
}
public function register($uname,$email,$upass, $code, $phone, $street_address, $street_address_2 , $city , $state , $zip_code , $country)
{
try
{
$password = md5($upass);
$stmt = $this->conn->prepare("INSERT INTO tbl_users(userName,userEmail,userPass, tokenCode, phone, street_address, street_address_2 , city , state , zip_code , country)
VALUES(:user_name, :user_mail, :user_pass, :active_code, :phone , :street_address, :street_address_2 , :city , :state , :zip_code , :country)");
$stmt->bindparam(":user_name",$uname);
$stmt->bindparam(":user_mail",$email);
$stmt->bindparam(":user_pass",$password);
$stmt->bindparam(":active_code",$code);
$stmt->bindparam(":phone",$phone);
$stmt->bindparam(":street_address",$street_address);
$stmt->bindparam(":street_address_2",$street_address_2);
$stmt->bindparam(":city",$city);
$stmt->bindparam(":state",$state);
$stmt->bindparam(":zip_code",$zip_code);
$stmt->bindparam(":country",$country);
$stmt->execute();
return $stmt;
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
public function login($email,$upass)
{
try
{
$stmt = $this->conn->prepare("SELECT * FROM tbl_users WHERE userEmail=:email_id");
$stmt->execute(array(":email_id"=>$email));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
if($userRow['userStatus']=="Y")
{
if($userRow['userPass']==md5($upass))
{
$_SESSION['userSession'] = $userRow['userID'];
return true;
}
else
{
header("Location: index.php?error");
exit;
}
}
else
{
header("Location: index.php?inactive");
exit;
}
}
else
{
header("Location: index.php?error");
exit;
}
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
public function is_logged_in()
{
if(isset($_SESSION['userSession']))
{
return true;
}
}
public function redirect($url)
{
header("Location: $url");
}
}
home.php [ customer will redirect to this home/profile page after login]
<?php
//Initializing variable
session_start();
require_once 'class.user.php';
$user_home = new USER();
if(!$user_home->is_logged_in())
{
$user_home->redirect('index.php');
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
in registration page we have name, email, city, zip....etc.
i need to provide an option for customer to update those fields in profile page.
once customer login, he will be redirect to profile/home page, in that page
I want to display all form fields and provide a "edit" button and once he click on that button, he should be able to update the values of name, email....etc.
i tried by adding below code, but not working for me.
class.user.php
public function update($uname,$email,$phone) {
try {
$stmt = $this->_db->prepare('UPDATE tbl_users SET userName = ?, userEmail = ?, phone = ? WHERE userID = ? ');
$stmt->execute(array($uname,$email,$phone,$_SESSION['userID']));
return $stmt->fetch();
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
}
home or profile [home.php ]
$FORM['uname'] = "";
$FORM['txtuname'] = "";
if (isset($_POST['submit'])) {
// new data
$uname = $_POST['txtuname'];
$email = $_POST['txtemail'];
$phone = $_POST['phone'];
$uid = (isset($_GET['userID']) ? intval($_GET['userID']) : -1);
// query
if ($uid->update($uname,$email,$phone,$userID)); {
redirect('home.php');
}
}
<form action="home.php" method="POST">
Name<br>
<input type="text" name="txtuname" value="<?php echo $_SESSION['txtuname'] ?>" /><br>
Email<br>
<input type="text" name="txtemail" value="<?php echo $_SESSION['email'] ?>" /><br>
Phone<br>
<input type="text" name="phone" value="<?php echo $_SESSION['phone'] ?>" /><br>
<input type="submit" name="submit" value="Save" />
</form>
its giving error : Fatal error: Call to a member function update() on a non-object in line
if ($uid->update($uname,$email,$phone,$userID)); {
$uid is not an user object, so you can not call update on it.
You should first retrieve the user object identified by its id from the database und then call update on it.
Additionally, you've got an error in class.user.php:
$stmt = $this->_db->prepare('UPDATE tbl_users SET userName = ?, userEmail = ?, phone = ? WHERE userID = ? ');
should be:
$stmt = $this->conn->prepare('UPDATE tbl_users SET userName = ?, userEmail = ?, phone = ? WHERE userID = ? ');
then in home.php you could do something like this:
$user_home = new USER();
// query
if ($user_home->update($uname,$email,$phone,$uid)); {
$user_home->redirect('home.php');
}
Another issue is, that you assign the users id to $_SESSION['userSession'] so you have to change your update function in your class.user.php:
public function update($uname,$email,$phone) {
try {
$stmt = $this->conn->prepare('UPDATE tbl_users SET userName = ?, userEmail = ?, phone = ? WHERE userID = ? ');
$stmt->execute(array($uname,$email,$phone,$_SESSION['userSession']));
return $stmt->fetch();
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
}
And finally (because you are currently not saving the users email etc. in the session) the form on the bottom of home.php should look rather like this (now including an edit button):
<script>function toggle() { var can = document.getElementsByName("submit"); for (i = 0; i < can.length; i++) { can[i].style.display = can[i].style.display === 'none' ? 'block' : 'none'; }}</script>
<form action="home.php" method="POST">
Name<br>
<input type="text" name="txtuname" value="<?php echo $row['userName'] ?>" /><br>
Email<br>
<input type="text" name="txtemail" value="<?php echo $row['userEmail'] ?>" /><br>
Phone<br>
<input type="text" name="phone" value="<?php echo $row['phone'] ?>" /><br>
<input id="sub" type="submit" name="submit" value="Save" style="display:none" />
</form>
<button name="submit" onclick="toggle()">Edit</button>
</html>
Based on your code, $uid is an integer, either -1 or the userID GET parameter.
Probably you wanted something like
$user_home->update( ..., $uid );
instead, assuming $user_home = new USER(); is missing. Or maybe any other instance of USER has to be created
$another = new USER();
...
$another->update( ..., $uid );
Why are you storing all your user info in a Session. User id or user name should be passed in a get variable. You then validate it that it exist if it doesn't no need to keep going kill the script. Redirect to error page or something. Also user should only be allowed to edit if user_id from the session equals get user_id, that means that user visiting current page. Is the owner so he can modify it. The value in your form should be the results from the database. Also you have no email or text input validation. Like a check that makes sure its a real email. A check to make sure text is only letters and numbers when form is submitted.
As far as your error, Where did you declare your object? I don't see it.
it has to be something like this.
$user_home = new USER();
then you can call update like so
$uid = $user_home->update($uname,$email,$phone,$userID);
you have an error here
public function update($uname,$email,$phone) { try { $stmt = $this->_db->prepare('UPDATE tbl_users SET userName = ?, userEmail = ?, phone = ? WHERE userID = ? '); $stmt->execute(array($uname,$email,$phone,$_SESSION['userID'])); return $stmt->fetch(); } catch(PDOException $e) { echo '<p class="bg-danger">'.$e->getMessage().'</p>'; } }
remove the _ from db like this
$stmt = $this->db->prepare('UPDATE tbl_users SET userName = ?, userEmail = ?, phone = ? WHERE userID = ? '
I think i have a quick workaround for your problem, based on the example you have provided and the fact that you might not need to re-write too much code. This is your home.php page
<?php
//Initializing variable
session_start();
require_once 'class.user.php';
$user_home = new USER();
if(!$user_home->is_logged_in())
{
$user_home->redirect('index.php');
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
Rewrite it like this
<?php
//Initializing variable
session_start();
require_once 'class.user.php';
$user_home = new USER();
// Fetch user from database based on user id
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// $row will provide the old values stored in database if you want them to be displayed as initial values inside your input fields
if(!$user_home->is_logged_in())
{
$user_home->redirect('index.php');
} else {
// adding this here ensures that the $user_home object exists
require_once("profile.php");
}
?>
Then your profile.php page can be like this simple example.
if (isset($_POST['submit'])) {
// new data
$uname = $_POST['txtuname'];
$email = $_POST['txtemail'];
$phone = $_POST['phone'];
$userID= $row['userID'];
// query
$user_home->update($uname,$email,$phone,$userID));
}
<form action="" method="POST">
Name<br>
<input type="text" name="txtuname" value="<?php echo $row['userName'] ?>" /><br>
Email<br>
<input type="text" name="txtemail" value="<?php echo $row['userEmail'] ?>" /><br>
Phone<br>
<input type="text" name="phone" value="<?php echo $row['userPhone'] ?>" /><br>
<input type="submit" name="submit" value="Save" />
</form>