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 am trying to insert into my table (courses) in my sql database. But when I run my code (by clicking submit) I get this error:
I am no longer getting an error, I get the message:
New course created successfully
But when I check the database, the course has not been added
This is my code:
<?php
if (isset($_POST['submit'])) {
try {
require "../config.php";
require "../common.php";
$connection = new PDO($dsn, $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO course (courseName, cDescription, programID, programYear, credit)
VALUES (:courseName, :cDescription, :programID, :programYear, :credit)";
$courseName = $_POST['courseName'];
$cDescription = $_POST['cDescription'];
$programID = $_POST['programID'];
$programYear = $_POST['programYear'];
$credit = $_POST['credit'];
$statement = $connection->prepare($sql);
$statement->bindParam(':courseName', $courseName, PDO::PARAM_STR);
$statement->bindParam(':cDescription', $cDescription, PDO::PARAM_STR);
$statement->bindParam(':programID', $programID, PDO::PARAM_STR);
$statement->bindParam(':programYear', $programYear, PDO::PARAM_STR);
$statement->bindParam(':credit', $credit, PDO::PARAM_STR);
$connection->exec($statement);
echo "New course created successfully";
} catch(PDOException $error) {
echo $statement. "<br>" . $error->getMessage();
}
}
?>
<?php include "templates/header.php"; ?>
<h2>Add a course</h2>
<form method="post">
<label for="courseName">Course Name:</label>
<input type="text" name="courseName" id="courseName" required>
<label for="cDescription">Course Description:</label>
<input type="text" name="cDescription" id="cDescription" size="40" required>
<label for="programID">Program ID:</label>
<input type="number" name="programID" id="programID" required>
<label for="programYear">Program Year:</label>
<input type="number" name="programYear" id="programYear" required>
<label for="credit">credit:</label>
<input type="number" name="credit" id="credit" required>
<input type="submit" name="submit" value="Submit">
</form>
Back to home
<?php include "templates/footer.php"; ?>
To try and see what was wrong, I tried simplifying this to, which works
<?php
if (isset($_POST['submit'])) {
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "courseselector";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO course (courseName, cDescription, programID, programYear, credit)
VALUES ('courseName', 'cDescription', 1, 4, 1)";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
<?php include "templates/header.php"; ?>
<h2>Add a course</h2>
<form method="post">
<input type="submit" name="submit" value="Submit">
</form>
Back to home
<?php include "templates/footer.php"; ?>
I was missing
$statement->execute();
Above
$connection->exec($statement);
<div class = "login">
<?php
$lusername=$_POST['lusername'];
$lpassword=$_POST['lpassword'];
$mysql = new mysqli("localhost", "root", null, "webdb");
$stmt = $mysql ->prepare("select username, password from webdb.user where username=?");
$stmt->bind_param("s", $lusername);
$stmt->execute();
$stmt->bind_result($u, $p);
$stmt->fetch();
$stmt->close();
$mysql->close();
if($lusername == $u && $lpassword == $p) {
echo "the log in is successful";
}
else {
echo "<b><font color='red'>Login unsuccessful. Please go back and try again </font></b>";
}
?>
<form action="sign in.php" method="post">
<div class = "details">
<br>
 <input type="text" name="lusername" placeholder="Username" required>
<br>
<br>
<br>
<input type="password" name="lpassword" placeholder ="Password" required>
</div>
<div class = "enter">
<br>
<br>
<input type="submit" name="submit" value="Enter">
</div>
I've been working on my login page for a day but I cannot seem to find the error in my codes. Currently, when I click on login, it automatically activates the if statement "the log in is successful" without even having to key in the username and password.
<div class = "login">
<?php
if(isset($_POST['submit'])){
$lusername=$_POST['lusername'];
$lpassword=$_POST['lpassword'];
$mysql = new mysqli("localhost", "root",'', "webdb");
$stmt = $mysql ->prepare("select username, password from webdb.user where username=?");
$stmt->bind_param("s", $lusername);
$stmt->execute();
$stmt->bind_result($u, $p);
$stmt->fetch();
$stmt->close();
$mysql->close();
if($lusername == $u && $lpassword == $p) {
echo "the log in is successful";
}
else {
echo "<b><font color='red'>Login unsuccessful. Please go back and try again </font></b>";
}
}
?>
<form action="sign in.php" method="post">
<div class = "details">
<br>
 <input type="text" name="lusername" placeholder="Username" required>
<br>
<br>
<br>
<input type="password" name="lpassword" placeholder ="Password" required>
</div>
<div class = "enter">
<br>
<br>
<input type="submit" name="submit" value="Enter">
</div>
try this as you are first checking the GET request, and it will always give the login successful, for that you need to check whether the submit button has been pressed, and remove the null from the database password as for blank password you keep '' and not null
1st : use isset to avoid undefined index error on page load for the first time .
if(isset($_POST['submit'])){ //all you php code here }
2nd : Don't save the password as plain text in database .Try to use password_hash() and password_verify()
3rd : On the error debugging mode. On top of page add these two lines
ini_set('display_errors','On'); ini_set('error_reporting', E_ALL);
1) Do no store password as a plain text use password_hash() to store it correclty. And use password_verify() to verify if the password is correct. Link: http://www.phptherightway.com/#password_hashing. I hope it is not a live app.
2)Use this to escape : htmlentities( $slusername, ENT_QUOTES | ENT_HTML5, $encoding = 'UTF-8' )
--------------------SOLUTION-------------------------------------------
The problem is that you don't submit the data with if ( $_SERVER['REQUEST_METHOD'] == "POST" ) and sign in.php should be sign_in.php. There is a space. AND REMOVE THE NULL on your mysqli database put ''.
2)In your your sign_in.php. Use this code.
<?php
/* Database connection start */
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=webdb", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
/*if submission button */
if ( $_SERVER['REQUEST_METHOD'] == "POST" ) {
/*There is no protection here*/
/*use $lusername=$htmlentities( $slusername, ENT_QUOTES |
ENT_HTML5, $encoding = 'UTF-8' );*/
$lusername=$_POST['lusername'];
$lpassword=$_POST['lpassword'];
/*Query*/
$query = 'SELECT password, username FROM user WHERE username
=:username';
$stmt = $conn->prepare($query);
$stmt -> bindParam(':username', $lusername);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->execute();
$stmt->CloseCursor();
/*Arranging query*/
function returnArray( $rows, $string )
{
foreach( $rows as $row )
{
return $row[ $string ];
}
}
/*Verification of the user*/
if( returnArray( $rows, 'password') == $lpassword)
{
echo "the log in is successful";
}
else
{
echo "<b><font color='red'>Login unsuccessful. Please
go back and try again </font></b>";
}
}
?>
In your login.php
<div class = "login">
<form action="sign_in.php" method="post">
<div class = "details">
<br>
 <input type="text" name="lusername"
placeholder="Username" required>
<br>
<br>
<br>
<input type="password" name="lpassword" placeholder
="Password" required>
</div>
<div class = "enter">
<br>
<br>
<input type="submit" name="submit" value="Enter">
</div>
</form>
</div>
I have this PHP that basically is being used for inserting an email and password into an SQL database:
<?php
error_reporting(E_ALL ^ E_STRICT);
require "database.php";
$message = '';
if (!empty($_POST["email"]) &&!empty($_POST["password"])):
//Enter the new user in the database
$sql = "INSERT INTO users (email, password) VALUES (:email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":email", $_POST['email']);
$stmt->bindParam(":password", password_hash($_POST['password'], PASSWORD_BCRYPT));
if ($stmt->execute() ):
$message = 'Successfully created a new user';
else:
$message = 'Sorry there must have been an issue whilst registering';
endif;
endif;
?>
Here is the form:
<div class="jumbotron" id="jumbotron-6">
<div class="container text-center">
<?php if (!empty($message)):
?>
<h3 id="h3message"><?= $message ?> </h3>
<?php endif; ?>
<form action="signup.php" method="POST">
<input type="text" placeholder="enter your email" name="email">
<input type="password" placeholder="and password" name="password">
<input type="password" placeholder="confirm password" name="confirm_password">
<input type="submit">
</form>
</div>
</div>
It doesn't insert into the database (all the fields, variables are correct i think - just email and password) and it comes back with the error message that I created that says 'Sorry there must have been an issue whilst registering'
Here is the database.php file
<?php
$server = 'localhost';
$username = "root";
$password = "";
$database = "auth";
try{
$conn = new PDO ("mysql:host={$server};dbname={$database};" , $username, $password);
}
catch (PDOException $e) {
die ( "Connection failed; " . $e->getMessage());
}
?>
Hash the password before you bind it:
$UserPWHash = password_hash($_POST['password'], PASSWORD_BCRYPT);
$stmt->bindParam(":password", $UserPWHash));
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>