I have a table named 'Directors' in the database 'db2'.
I have an HTML form. I would like when I insert the values and hit submit button, to insert the content into the table in a new row (to INSERT INTO), after it makes some validations (you'll notice them in the script). I've tried to do it by myself, but it is always echoing me 'Fail';
This is my HTML form:
<form action="process.php" method="post" accept-charset="utf-8">
<input type="hidden" name="pages_edit_nonce" />
<div class="section-item page-title-section">
<label for="title">Full Name:</label><span class="help">*</span><div class="input-wrap"><input type="text" name="name" value="" /></div> </div>
<div class="section-item">
<label for="label">Phone:</label><span class="help">*Optionally</span><div class="input-wrap"><input type="text" name="phone" value="" /></div> </div>
<div class="section-item">
<label for="redirect">Е-mail:</label><span class="help">*</span><div class="input-wrap"><input type="text" name="email" value="" placeholder="" /></div> </div>
<div class="section-item">
<label for="redirect">School:</label><span class="help">*</span><div class="input-wrap"><input type="text" name="school" value="" placeholder="" /></div> </div>
<div class="section-item">
<label for="redirect">City:</label><span class="help">*</span><div class="input-wrap"><input type="text" name="city" value="" placeholder="" /></div> </div>
<div class="section-item">
<label for="redirect">Password:</label><span class="help">*</span><div class="input-wrap"><input type="password" name="password" value="" placeholder="" /></div> </div>
<div class="admin-bar">
<div class="admin-bar-inner">
<input type="submit" value="Submit" class="btn" />
</div>
</div>
</form>
This is my process.php file:
$server = "localhost";
$user = "****";
$pass = "****";
$conn = mysql_connect($server, $user, $pass);
$db = mysql_select_db("****", $conn);
session_start();
if(!$db) {
$_SESSION['ERRMSG'] = "<strong>Error:</strong> The access to the database is denied!";
header("Location: ../../admin/error/");
exit();
}
session_start();
function UniqueID() {
$UID = rand(); //Create unique ID
$check = mysql_query("SELECT * FROM `Directors` WHERE `UID` = '$UID'");
if(mysql_num_rows($check) > 0) { //Check if it exists
UniqueID(); //Redo the function
} else {
return $UID; //return the uniqueid
}
}
$UID = UniqueID(); //Unique ID
$email = $_POST['email'];
$password = $_POST['password'];
$name = $_POST['name'];
$phone = $_POST['phone'];
$school = $_POST['school'];
$city = $_POST['city'];
//Create INSERT query
$qry = "INSERT INTO `oclass`.`Directors`(`UID`,`Name`, `Phone`, `Email`, `SchoolGymnasium`, `City`, `Password`) VALUES('$UID','$name','$phone','$email','$school','$city','" . md5($password) . "')";
$result = mysql_query($qry);
//Check whether the query was successful or not
if($result) {
$_SESSION['SUCCMSGADDDIR'] = 'Sucessful.';
header("location: URL");
exit();
} else {
$_SESSION['ERRMSGADDDIR'] = 'Fail';
header("location: URL");
}
After changing the error session with mysql_error() it gave me the following error:
Fatal error: Can't use function return value in write context in ... on line 10;
Line 10 is:
mysql_error() = "<strong>Error:</strong> The access to the database is denied!";
I've removed the column named ID (which was Primary Key) and set UID column as Primary Key, and now is working. Thank you guys.
Firstly you must have never heard of SQL injection http://en.wikipedia.org/wiki/SQL_injection. Your current code is opening you up for attacks. You can't directly insert user input into the database like you're doing. Also mysql_* functions are deprecated. To help your code be safer and more update try something like this:
session_start();
$host = "localhost";
$user = "****";
$pass = "****";
$db = "****";
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("INSERT INTO `oclass`.`Directors`(`UID`,`Name`, `Phone`, `Email`, `SchoolGymnasium`, `City`, `Password`) VALUES (:uid, :name, :phone, :email, :school, :city, :password)");
$stmt->bindParam(':uid', uniqid());
$stmt->bindParam(':name', $_POST['name']);
$stmt->bindParam(':phone', $_POST['phone']);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':school', $_POST['school']);
$stmt->bindParam(':city', $_POST['city']);
$stmt->bindParam(':password', md5($_POST['password']));
$stmt->execute();
Related
I am using this code to add some data to my already existing sql database, but the can't seem to do so, it's also not giving any errors. I have tried everything that i could think of. This is a form which lets user input the data and then when user clicks submit it gives a success message in url but i get the success message but no data in my database.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Signup Form</title>
</head>
<body>
<form action="signup.php" method="POST">
<input type="text" name="firstname" placeholder="First Name">
<br>
<input type="text" name="lastname" placeholder="Last Name">
<br>
<input type="text" name="email" placeholder="E-mail">
<br>
<input type="text" name="uid" placeholder="User name">
<br>
<input type="password" name="pwd" placeholder="Password">
<br>
<button type="submit" name="submit">Sign up</button>
</form>
<?php
$sql = "SELECT * FROM users;" ;
$result = mysqli_query($conn,$sql); //connects the database to the query we just generated
$resultcheck = mysqli_num_rows($result); // it returns the number of rows in the query
if($resultcheck > 0){
//the if condition checks if there is any data inside $resultcheck
//The mysqli_fetch_assoc() function fetches a result row as an associative array.
while($row = mysqli_fetch_assoc($result)){
echo $row['user_uid'].'<br>';
}
}
?>
</body>
</html>
<?php
include_once 'dbh.php';
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
$sql = "INSERT INTO users (`user_firstname`, `user_firstname`, `user_email`, `user_uid`, `user_pwd` ) VALUES (\'$firstname\',\'$lastname\',\'$email\',\'$uid\', \'$pwd\');";
//require 'dbh.php';
mysqli_query('$conn','$sql');
/* if($result=$mysqli->query($sql)){
echo "<p>User successfully added to database</p>".'<br>';
}
else{
echo "Error enterting user into database!".mysql_error().'<br>';
} */
header("Location: index.php?signup=success");
?>
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "login_system"; // selecting the database
$conn = mysqli_connect($dbServername,$dbUsername,$dbPassword,$dbName );
//$mysqli = new mysqli('localhost','root',"",$dbName );
if(mysqli_connect_errno()){
printf("connection failed %s\n",mysqli_connect_error());
exit();
}
$mysqli->select_db("login_system");
?>
Please remove single quotes in $conn and $sql
mysqli_query($conn, $sql);
in your insert PHP file.
$sql = "INSERT INTO `users` (`user_firstname`, `user_lastname`, `user_email`, `user_uid`, `user_pwd` ) VALUES ('".$firstname."', '".$lastname ."', '".$email."', '".$uid."', '".$pwd."');";
$result=mysqli_query('$conn','$sql');
if($result)
{
echo "succsessfuly...";
}
else
{
echo "Not succsessfuly...";
}
Try this one:
<?php
include_once 'dbh.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> Signup Form </title>
</head>
<body>
<form action="signup.php" method="POST">
<input type="text" name="firstname" placeholder="First Name">
<br>
<input type="text" name="lastname" placeholder="Last Name">
<br>
<input type="text" name="email" placeholder="E-mail">
<br>
<input type="text" name="uid" placeholder="User name">
<br>
<input type="password" name="pwd" placeholder="Password">
<br>
<button type="submit" name="submit">Sign up</button>
</form>
<?php
$sql = "SELECT * FROM users; " ;
$result = $mysqli->query($sql); //connects the database to the query we just generated
$resultcheck = $result->num_rows; // it returns the number of rows in the query
if($resultcheck > 0){
while($row = $result->fetch_assoc()){
echo $row['user_uid'].'<br>';
}
}
?>
</body>
</html>
signup.php
<?php
include_once 'dbh.php';
$firstname = $mysqli->real_escape_string($_POST['firstname']);
$lastname = $mysqli->real_escape_string($_POST['lastname']);
$email = $mysqli->real_escape_string($_POST['email']);
$uid = $mysqli->real_escape_string($_POST['uid']);
$pwd = $mysqli->real_escape_string($_POST['pwd']);
$sql = "INSERT INTO users (`user_firstname`, `user_lastname`, `user_email`, `user_uid`, `user_pwd` ) VALUES ('$firstname','$lastname','$email','$uid', '$pwd');";
if($result=$mysqli->query($sql)){
echo "<p>User successfully added to database</p>".'<br>';
}
else{
echo "Error enterting user into database!".$mysqli->error.'<br>';
}
header("Location: index.php?signup=success");
dbh.php
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "login_system"; // selecting the database
$mysqli = new mysqli($dbServername,$dbUsername,$dbPassword,$dbName);
if($mysqli->connect_errno){
printf("connection failed %s\n",$mysqli->connect_error);
exit();
}
Please read this reference http://php.net/manual/en/book.mysqli.php
should be like this
$sql = "INSERT INTO users (firstname, lastname, email, uid, pwd ) VALUES ('$firstname','$lastname','$email','$uid', '$pwd')";
mysqli_query($conn,$sql);
I had a Freelancer work on a site for me and could not finish my project which should of been of ease to him and I need to get this fully running to be ready by morning.
This is my PHP code which I had to create in a hurry
<?php
$con = mysqli_connect('localhost','dbuser','password'
if(!$con)
{
echo 'Not Connected To Server';
}
if(!mysqli_select_db($con,'DBName'))
{
echo 'Database Not Selected';
}
$UserN = $_POST['UserN'];
$FullN = $_POST['FullN'];
$Adrs = $_POST['Adrs'];
$Email = $_POST['Email'];
$PhoneN = $_POST['PhoneN'];
$sql = "INSERT INTO UserIn (UserN, FullN, Adrs, Email, PhoneN) VALUES ('$UserN', '$FullN', '$Adrs', '$Email', '$PhoneN')";
if(!mysqli_query($con,$sql))
{
echo 'Not Inserted';
}
else
{
echo 'Inserted';
}
header("refresh:2; url=survey.html
?>
this is PHP
this is my Form
<div class="form-con">
<form actoin="insert.php" method="post">
<label>Username</label><br>
<input type="text" name="UserN" placeholder="Your Username" ><br>
<label>Full Name</label><br>
<input type="text" name="FullN" placeholder="Full Name"><br>
<label>Full Address</label><br>
<textarea type="text" rows="4" cols="50" name="Adrs" placeholder="Address"></textarea><br>
<label>Email Address</label><br>
<input type="email" name="Email" placeholder="Email Address"><br>
<label>Phone Number</label><br>
<input type="text" name="PhoneN" placeholder="Phone Number"><br>
<div class="btn">
<button type="submit">Submit</button>
</div>
</form>
</div>
Please help me I want to also secure the form with
Using MySQLi (for MySQL):
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
From here
https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1
please help.
New PHP
<?php
$dbh = new PDO("mysql:host=$host;dbame=$dbname",$user,$pass);
$UserN = mysqli_real_escape_string($con, $_POST['UserN']);
$FullN = mysqli_real_escape_string($con, $_POST['FullN']);
$Adrs = mysqli_real_escape_string($con, $_POST['Adrs']);
$Email = mysqli_real_escape_string($con, $_POST['Email']);
$PhoneN = mysqli_real_escape_string($con, $_POST['PhoneN']);
$stmt = $dbh->prepare("INSERT INTO UserIn (UserN, FullN, Adrs, Email, PhoneN) VALUES ('$UserN','$FullN','$Adrs','$Email','$PhoneN')"); //Insert query
$stmt->execute($UserN, $FullN, $Adrs, $Email, $PhoneN);
header("refresh:1; url=survey.html");
?>
You can do 2 things to secure from SQL-injection-
1) use $UserN = mysqli_real_escape_string($con, $_POST['UserN']); instead of
$UserN = $_POST['UserN'];
2) for connecting to MySql, use PDO like so-
$dbh = new PDO("mysql:host=$host;dbame=$dbname",$user,$pass);
Then the Insert query $sql = "INSERT INTO UserIn (UserN, FullN, Adrs, Email, PhoneN) VALUES ('$UserN', '$FullN', '$Adrs', '$Email', '$PhoneN')";
becomes-
$stmt = $dbh->prepare("INSERT INTO UserIn (UserN, FullN, Adrs, Email, PhoneN) VALUES (?,?,?,?,?)"); //Insert query
$stmt->execute($UserN, $FullN, $Adrs, $Email, $PhoneN);
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>
I need to create a sign up page that will store user name email passwords and put them in a database so that the user can then login and access a profile etc.
I have made a database database however nothing will go into it. I input one manually but anything I try to do from the webpage won't go to the database.
Code for the webpage: Signup is the page I want displayed and adduser is the code for adding the data to the database.
Signup:
<?php include '../view/header.php';
?>
<br>
<br>
<h1 class="light white-text text-lighten-3">Sign up!</h1>
<br>
<br>
<form class="form" id="signup" action="addUser.php" method="post">
<div class="form-group ">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter Your Email">
</div>
<br>
<div class="form-group ">
<input id="user_name" type="text" class="validate" name="user_name"required="required">
<label for="user_name">User Name</label>
</div>
<br>
<div class="form-group col s6">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Enter a Password">
</div>
<br>
<br>
<button type="submit" class="orange btn btn-primary">Submit</button>
</form>
<?php
include '../view/footer.php';
AddUser:
<script src="../js/materialize.js" type="text/javascript"></script>
<script src="../js/materialize.min.js" type="text/javascript"></script>
<script src="../js/init.js" type="text/javascript"></script>
<?php
$server = "localhost";
$username = 'root';
$Password ="";
$database = 'commish';
$con = mysqli_connect($server, $username, $Password, $database);
$email = filter_input(INPUT_POST, 'email');
$user_name = filter_input(INPUT_POST, 'user_name');
$password = filter_input(INPUT_POST, 'password');
new_user( $user_name, $password,$email, $con);
function new_user($user_name, $password, $email,$con)
{
global $con;
$query = "INSERT into users (user_name, password, email) VALUES (:user_name, :password, :email)";
$statement = $con->prepare($query);
$statement->bindValue(":user_name", $user_name);
$statement->bindValue(":password", $password);
$statement->bindValue(":email", $email);
$statement->execute();
echo 'Successfully created new user';
}
There's no bindValue() method in mysqli, PDO has. So here are the two approaches to solve your problem:
1)mysqli method:
Use bind_param() method to bind variables to your prepared statement. So your new_user() function should be like this:
function new_user($user_name, $password, $email,$con){
$query = "INSERT into users (user_name, password, email) VALUES (?, ?, ?)";
$statement = $con->prepare($query);
$statement->bind_param("sss", $user_name, $password, $email);
if($statement->execute()){
echo 'Successfully created new user';
}else{
// query failed
}
}
NOTE: Since you're passing the connection handler $con to this function, there's no need to use global $con;. Plus Globals are evil.
2)PDO method:
Keep your new_user() function as it is and change this line
$con = mysqli_connect($server, $username, $Password, $database);
to
$con = new PDO("mysql:host=$server;dbname=$database",$username,$Password);
Sidenote: Never store password as a plain readable text, always perform salted password hashing on raw password before inserting it into the table.
There's no bindValue() method in mysqli, you should use bind_param()
new_user function :
function new_user ($user_name, $password, $email)
{
global $con;
$stmt = $con->prepare("INSERT into users (user_name, password, email) VALUES (?,?,?)";
$stmt->bind_param("sss", $user_name, $password, $email);
$stmt->execute();
$stmt_error = $stmt->error;
$stmt->close();
if ($stmt_error)
echo 'Error on create new user: '.$stmt_error;
else
echo 'Successfully created a new user';
}