Related
html webpage screenshotphp code shown on button clickmySql database tableI need to store user login data. i am using phpMyAdmin. When I click on submit button, data is not stored. Instead the php code is shown. Both code files are given below. What I am doing wrong. Help me. I
am unable to store user data using phpmyadmin in xampp.
my html code
<html>
<head>
<title>Yahoo Signin And Signup Form</title>
</head>
<body>
<h2 style="color: midnightblue">yahoo!</h2>
<hr color="magenta">
<form method="post" action="connect.php" >
<fieldset style="background:#6495ED;">
<legend style="padding:20px 0; font-size:20px;">Signup:</legend>
<label for ="firstName">Enter First Name</label><br>
<input type="text" placeholder="First name" id="firstName" name ="firstName">
<br>
<label for ="lastName">Enter Last Name</label><br>
<input type="text" placeholder="Last name" id="lastName" name ="lastName">
<br>
<label for ="email">Enter Email</label><br>
<input type="text" placeholder="Email" id="email" name ="email"><br>
<label for ="password">Enter Password</label><br>
<input type="password" placeholder="Password" id="password" name ="password">
<br>
<label for ="number">Enter Mobile Number</label><br>
<input placeholder="03---" id="number" name ="number"><br>
<label for ="date">Enter Date of Birth</label><br>
<input type="text" placeholder="DD/MM/YY" id="date" name ="date"><br>
<label for ="gender">Enter Gender</label><br>
<input type="text" placeholder="Male/Female/Other" id="gender" name
="gender"><br>
<br><button style="background-color:orangered;border-
color:dodgerblue;color:lightyellow">Signup</button>
</fielsdet>
</form>
</body>
</html>
my connect.php
<?php
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
$number = $_POST['number'];
$date = $_POST['date'];
$gender = $_POST['gender'];
// Making Connection with database
$con = new mysqli('localhost','root','','phpdata');
if ($con -> connect_error) {
die('Connection failed :'.$conn -> connect_error);
}
else{
$stmt = $con->query("INSERT INTO signup(firstName, lastName, email, password,
number, date, gender)
values(?,?,?,?,?,?,?)");
$stmt->bind_param("ssssiss",$firstName, $lastName, $email, $password,
$number, $date, $gender);
$stmt->execute();
echo "Sign up successful";
$stmt->close();
$con->close();
}?>
Use prepare instead of query. All everything is ok.:
$stmt = $con->prepare("INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
values(?,?,?,?,?,?,?)");
And make button type as submit:
<br><button type="submit" style="background-color:orangered;border-color:dodgerblue;color:lightyellow">Signup</button>
here is the code, it works fine with me
<?php
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
$number = $_POST['number'];
$date = $_POST['date'];
$gender = $_POST['gender'];
// Making Connection with database
$con = new mysqli('localhost','root','','phpdata');
if ($con -> connect_error) {
die('Connection failed :'.$conn -> connect_error);
}
else{
$stmt = $con->query("INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
values("'.$firstName.'","'.$lastName.'","'.$email.'","'.$password.'","'.$number.'","'.$date.'","'.$gender.'")");
if ($con->query($stmt) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$con->close();
}//end of else of connection
?>
Add type in your submit button.
<button type='submit' style="background-color:orangered;border-color:dodgerblue;color:lightyellow">Signup</button>
and also your question marks and params ara not matching. it should be match. otherwise data won't store your db
correct that line also
The main problem is you are not loading code via apache server try to open http://localhost/signup.html instead of C:/xmapp/htdocs/connect.php
It seems you want to user PDO but your connection string not correct
<?php
$firstName = trim($_POST['firstName']);
$lastName = trim($_POST['lastName']);
$email = trim($_POST['email']);
$password = md5(trim($_POST['password']));
$number = trim($_POST['number']);
$date = trim($_POST['date']);
$gender = trim($_POST['gender']);
$con= new PDO("mysql:host=127.0.0.1;dbname=phpdata", 'root', 'root');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sqli = "INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
values(?,?,?,?,?,?,?)";
try {
$stmt= $con->prepare($sqli);
$stmt->bindParam(1,$firstName);
$stmt->bindParam(2,$lastName);
$stmt->bindParam(3,$email);
$stmt->bindParam(4,$password);
$stmt->bindParam(5,$number);
$stmt->bindParam(6,$date);
$stmt->bindParam(7,$gender);
$status = $stmt->execute();
echo "Sign up successful";
$stmt->close();
$con->close();
} catch(PDOException $e) {
echo "Error ".$e->getMessage();
}
?>
another problem is with your html form button type is missing
<button type="submit".... />
Here is the complete code after analyzing it for a lot of time. in your $stmt variable there was no query, it was empty. This code works fine just copy and paste it.
<?php
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
$number = $_POST['number'];
$date = $_POST['date'];
$gender = $_POST['gender'];
// Making Connection with database
$con = new mysqli('localhost','root','','abc');
if ($con -> connect_error) {
die('Connection failed :'.$conn -> connect_error);
}
else{
$sql = "INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
values('$firstName','$lastName','$email','$password','$number','$date','$gender')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
$con->close();
}//end of else of connection
?>
I am building a CRM for my wife and I to use for our business. I have created a page with several goals in mind:
Be able to create a new entry in the database.
Be able to view an existing entry in the database.
Be able to update an existing entry in the database.
I originally had several php files performing this stuff, but have now used the GOTO function to get the code to bounce around to the different parts I need run depending on what is happening all while staying on the same page.
My question is, other than it looking messy, is there a downfall to doing it this way? In the future I will be looking into other and cleaner ways to do it (suggestions are welcome), but this is working for me at the moment and I would like to move on with the project and start building the additional parts I require for the CRM. Think of this as a beta version if you will. If there is some huge drawback to what I have done already, Id rather address it now, but if this is at least mildly reasonable I will push forward.
Here is what I have:
<?php
// Include Connection Credentials
include("../../comm/com.php");
//Connection to Database
$link = mysqli_connect($servername, $username, $password, $dbname);
// Connection Error Check
if ($link->connect_errno) {
echo "Sorry, there seems to be a connection issue.";
exit;
}
// Define Empty Temporary Client ID
$new_client_id ="";
// Define Empty Success Message
$successful ="";
// Define Empty Error Messages
$firstnameErr ="";
$lastnameErr ="";
$addressErr ="";
$cityErr ="";
$stateErr ="" ;
$zipcodeErr ="";
$phoneErr ="";
$emailErr ="";
// CHECK FOR SEARCH PROCESS
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['searched'])) {
$client_id = $_POST['client_id'];
$buttontxt = "Update";
goto SearchReturnProcess;
}
}
// Retrieve Client ID
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['client_id'])) {
$buttontxt = "Create Client";
goto CreatNewClientProcess;
} else {
$client_id = $_POST['client_id'];
$buttontxt = "Update";
goto UpdateClientProcess;
}
}
// CONTINUE FOR NEW CLIENT
CreatNewClientProcess:
// Check For Missing Fields and report
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$firstnameErr = "First name is a required field - please make entry below";
goto FinishUpProcess;
}
if (empty($_POST["lastname"])) {
$lastnameErr = "Last name is a required field - please make entry below";
goto FinishUpProcess;
}
if (empty($_POST["email"])) {
$emailErr = "Email is a required field - please make entry below";
goto FinishUpProcess;
}
if (empty($_POST["phone"])) {
$phoneErr = "Phone is a required field - please make entry below";
goto FinishUpProcess;
}
if (empty($_POST["address"])) {
$addressErr = "Address is a required field - please make entry below";
goto FinishUpProcess;
}
if (empty($_POST["city"])) {
$cityErr = "City is a required field - please make entry below";
goto FinishUpProcess;
}
if (empty($_POST["state"])) {
$stateErr = "State/Province is a required field - please make entry below";
goto FinishUpProcess;
}
if (empty($_POST["zipcode"])) {
$zipcodeErr = "Postal code is a required field - please make entry below";
goto FinishUpProcess;
}
}
// Prepared Statement For Database Search
if ($stmt = $link->prepare("INSERT INTO client (firstname, lastname, address, city, state, zipcode, phone, email) VALUES (?,?,?,?,?,?,?,?)")){
// Bind Search Variable
$stmt->bind_param('ssssssss', $firstname, $lastname, $address, $city, $state, $zipcode, $phone, $email);
// Define Form Field Input
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$phone = $_POST['phone'];
$email = $_POST['email'];
// Execute the Statement
$stmt->execute();
}
// Close Statment
$stmt->close();
// Report Successful Entry
$successful = "Client Successfully Created!";
// Define New Client ID
$new_client_id = $link->insert_id;
// FINISH NEW CLIENT PROCESS
goto FinishUpProcess;
// CONTINUE FOR SEARCHED PROCESS
SearchReturnProcess:
// Prepared Statement For Database Search
$stmt = $link->prepare("SELECT firstname, lastname, address, city, state, zipcode, phone, email FROM client WHERE client_id=?");
// Bind Client ID into Statement
$stmt->bind_param('s', $client_id);
// Execute the Statement
$stmt->execute();
// Bind Variables to Prepared Statement
$stmt->bind_result($firstname, $lastname, $address, $city, $state, $zipcode, $phone, $email);
//fetch value
$stmt->fetch();
// Close Statment
$stmt->close();
// FINISH SEARCHED PROCESS
goto FinishUpProcess;
// CONTINUE FOR UPDATE CLIENT PROCESS
UpdateClientProcess:
// Prepared Statement For Database Search
if ($stmt = $link->prepare("UPDATE client SET firstname=?, lastname=?, address=?, city=?, state=?, zipcode=?, phone=?, email=? WHERE client_id=?")){
// Bind Search Variable
$stmt->bind_param('sssssssss', $firstname, $lastname, $address, $city, $state, $zipcode, $phone, $email, $client_id);
// Define Form Field Input
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$client_id = $_POST['client_id'];
// Execute the Statement
$stmt->execute();
}
// Close Statment
$stmt->close();
// Report Successful Update
$successful = "Client Updated Successfully!";
// FINISH UPDATE PROCESS
goto FinishUpProcess;
// CONTINUE FOR FINISHING UP PROCESS
FinishUpProcess:
// Disconnect from Database
mysqli_close($link)
?>
<!DOCTYPE html>
<html>
<head>
<title>Client Information</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<form id="contact" action="" method="post">
<h4>enter client info below</h4>
<font color="red"><?php echo $successful; ?></font>
<fieldset>
<input name="client_id" value="<?php if (empty($_POST['client_id'])) { echo $new_client_id; } else { echo $_POST['client_id']; } ?>" type="hidden">
</fieldset>
<fieldset>
<font color="red"><?php echo $firstnameErr; ?></font>
<input name="firstname" value="<?php if (isset($_POST['client_id'])) { echo $firstname; } else { echo $_POST['firstname']; } ?>" placeholder="First Name" type="text" tabindex="1" autofocus>
</fieldset>
<fieldset>
<font color="red"><?php echo $lastnameErr; ?></font>
<input name="lastname" value="<?php if (isset($_POST['client_id'])) { echo $lastname; } else { echo $_POST['lastname']; } ?>" placeholder="Last Name" type="text" tabindex="2">
</fieldset>
<fieldset>
<font color="red"><?php echo $emailErr; ?></font>
<input name="email" value="<?php if (isset($_POST['client_id'])) { echo $email; } else { echo $_POST['email']; } ?>" placeholder="Email Address" type="email" tabindex="3">
</fieldset>
<fieldset>
<input name="mailinglist" id="checkbox" type="checkbox" checked>
<label>add to the mailing list</label>
</fieldset>
<fieldset>
<font color="red"><?php echo $phoneErr; ?></font>
<input name="phone" value="<?php if (isset($_POST['client_id'])) { echo $phone; } else { echo $_POST['phone']; } ?>" placeholder="Phone Number" type="tel" tabindex="4">
</fieldset>
<fieldset>
<font color="red"><?php echo $addressErr; ?></font>
<input name="address" value="<?php if (isset($_POST['client_id'])) { echo $address; } else { echo $_POST['address']; } ?>" placeholder="Street Address" type="text" tabindex="5">
</fieldset>
<fieldset>
<font color="red"><?php echo $cityErr; ?></font>
<input name="city" value="<?php if (isset($_POST['client_id'])) { echo $city; } else { echo $_POST['city']; } ?>" placeholder="City" type="text" tabindex="6">
</fieldset>
<fieldset>
<font color="red"><?php echo $stateErr; ?></font>
<input name="state" value="<?php if (isset($_POST['client_id'])) { echo $state; } else { echo $_POST['state']; } ?>" placeholder="State/Province" type="text" tabindex="7">
</fieldset>
<fieldset>
<font color="red"><?php echo $zipcodeErr; ?></font>
<input name="zipcode" value="<?php if (isset($_POST['client_id'])) { echo $zipcode; } else { echo $_POST['zipcode']; } ?>" placeholder="Postal Code" type="text" tabindex="8">
</fieldset>
<fieldset>
<font color="red"><?php echo $countryErr; ?></font>
<input name="country" value="<?php if (isset($_POST['client_id'])) { echo $country; } else { echo $_POST['country']; } ?>" placeholder="Country" type="text" tabindex="9">
</fieldset>
<fieldset>
<input name="vegan" type="checkbox">
<label>Vegan or Vegitarian</label>
</fieldset>
<fieldset>
<input name="smoker" type="checkbox">
<label>Smoker</label>
</fieldset>
<fieldset>
<textarea name="client_notes" placeholder="general notes" tabindex="10"></textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" data-submit="...Sending"><?php echo $buttontxt; ?></button>
</fieldset>
</form>
</div>
</body>
</html>
I'm not sure I even knew that goto existed in PHP. I've used (and abused) my share of gotos over the years, but not lately. On to the fixes:
1 - Many of your gotos (e.g., SearchReturnProcess) can be replaced with function calls. Instead of making a chunk of code starting with a label (and using goto to get there), make a separate function with the same name function SearchReturnProcess() and put the code there.
2 - For the error processing, use if elseif:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$firstnameErr = "First name is a required field - please make entry below";
} elseif (empty($_POST["lastname"])) {
$lastnameErr = "Last name is a required field - please make entry below";
} elseif...
etc.
Then you can either make that set of statements end with an else followed by the block of "no error" code, or instead of a bunch of separate errors you can make one generic error variable (e.g., $fieldErr) and after the block have code like if ($fieldErr != '') to handle error display and simply display the errors in one location instead of next to each field.
Yes.
I won't preach about heresy and blasphemy but show you that most of your GOTOs are simply wrong.
UpdateClientProcess. That's quite strange an idea that you have to validate input for the creation only. It should be always the same for both create and update. So this one is useless and harmful
FinishUpProcess from validation routines. That's awful from the usability point of view. There was an old Chiniese torture when a victim's head was fixed under the dripping tap. Unharmful at first, it drove people crazy in time. So you are doing with your verifications. Why not to check ALL fields and then tell user at once, instead of showing them errors one by one?
FinishUpProcess from saving data. This violates the HTTP protocol rule says that after processing the POST request a server should issue a Location header redirecting a client using GET method. Otherwise if a client would refresh a page, the record will be duplicated.
It looks messy. You said that. It took me a hard time to navigate your code to review it due to its monotonous structure. Code padding was invented on purpose. In Python, for example, you are forced to use padding to distinguish subordinate code blocks.
A proper structure for this code would be like
$errors = [];
if ($_POST) {
if (empty($_POST["firstname"])) {
$errors['firstname'] = "First name is a required field - please make entry below";
}
// and so on
if (!$errors) {
if (empty($_POST['client_id'])) {
// go for insert
} else {
// go for update
}
header("Location: .");
exit;
}
$firstname = htmlspecialchars($_POST['firstname']);
// and so on
}
if (!$errors ) {
if (!empty($_GET['client_id'])) {
// search your data from a GET variable
} else {
// define empty variables
}
}
?>
<html goes here>
Hi I am using prepared statements for the first time. I have a form whose values, i am inserting in Mysql database using Mysqli prepared statements. But the problem is if user leaves an input box empty, Query doesn't insert row to the database.
Form
<form action="test.php" method="post" class="signupform">
<input type="text" Placeholder="Name" name="name" Required="required"/>
<br />
<input type="email" Placeholder="Email-id" name="email" Required="required"/>
<br />
<input type="password" Placeholder="Password" name="pass" Required="required"/>
<br />
<span>Male<input type="radio" name="sex" value="M" checked="checked"/> Female<input type="radio" name="sex" value="F"/></span>
<br />
<input type="text" Placeholder="City" name="city"/>
<br /><br />
<input type="submit" value="CREATE MY ACCOUNT" name="submit"/>
</form>
<?php
if(isset($_POST['submit'])){
include_once('includes/db.php');
$name=$_POST['name'];
$pass=$_POST['pass'];
$email=$_POST['email'];
$sex=$_POST['sex'];
$city = $_POST['city'];
if ($stmt = $mysqli->prepare("INSERT INTO login VALUES('',?,?,?,?,?,'')")) {
$stmt->bind_param("sssss", $name, $email, $pass, $sex, $city);
$stmt->execute();
if($stmt){
echo "result inserted";
}
}
}
?>
On using above form and query when i fill all the boxes of form it insert a new row for me. But if i leave an input box empty, It doesn't insert any row.
I also have seen a lot of questions which says that if i use variables like this
if(empty($_POST['city'])) { $city = null; } else { $city = $_POST['city']; }
then it will work and most of them are accepted answers. I am confused why this solution is not working for me ???
Any help is appreciated...Thanks
Your query is wrong:
if ($stmt = $mysqli->prepare("INSERT INTO login VALUES('',?,?,?,?,?,'')")) {
It should be something like:
if (!empty($name) || !empty($pass) || !empty($email))
{
$stmt = $mysqli->prepare("INSERT INTO login(`name`,`password`,`email`,`sex`,`city`) VALUES(?,?,?,?,?)");
$stmt->execute([$name, $pass, $email, $sex, $city]);
echo "result inserted";
} else {
echo 'You have not entered all of the fields.';
}
In this instance, if the variables are not empty then perform insert. Else if they are empty fire a echo stating the fields haven't been filled in.
If you are happy for the fields to be null simply change !empty() to empty() but as Fred -ii- stated above, ensure your database allows NULL within them fields.
Probably this is not one of the smartest way to do it, but hey, it will get the job done.
One of the things that you need to do before assigning a variable to an $_POST field, you need to check if that $_POST field isset and its not empty, then assign the value if not empty, Currently if someone leaves out a field in your form when you run the query you will probably get a notice of undefined.
This is what you can do.
<?php
if (isset($_POST['submit'])) {
include_once('includes/db.php');
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$name = " ";
}
if (!empty($_POST['pass'])) {
$pass = $_POST['pass'];
} else {
$pass = " ";
}
if (!empty($_POST['email'])) {
$email = $_POST['email'];
} else {
$email = " ";
}
if (isset($_POST['sex'])) {
$sex = $_POST['sex'];
} else {
$sex = " ";
}
if (!empty($_POST['city'])) {
$city = $_POST['city'];
} else {
$city = " ";
}
if ($stmt = $mysqli->prepare("INSERT INTO login VALUES(?,?,?,?,?)")) {
$stmt->bind_param("sssss", $name, $email, $pass, $sex, $city);
$stmt->execute();
if ($stmt) {
echo "result inserted";
} else {
echo "could not insert";
}
}
}
?>
There are other better ways to do this.
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'm creating a website as an activity and I'm not sure how to proceed. I have a database file (.db) that has Customer information (firstname, lastname, address, phone) and I'm wanting to create a form to input more data into those fields.
I've been given a function in a separate file called queryDb.php:
function addCustomer($fname, $lname, $address, $phone) {
$db = new MyDB();
if(!$db){
echo '<script type="text/javascript">alert("'.$db->lastErrorMsg().'");</script>';
} else {
//echo "Opened database successfully\n";
}
$sql ='INSERT INTO CUSTOMERS (FIRSTNAME, LASTNAME, ADDRESS, PHONE) VALUES ("'.$fname.'", "'.$lname.'", "'.$address.'", "'.$phone.'");';
$db->query($sql);
}
In my main php file I have this up the top:
<?php
require_once "queryDb.php";
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$address = $_POST["address"];
$phone = $_POST["phone"];
?>
and the form, I've only created it for two inputs, Address and phone to test it:
<form action="reviewsubmit.php" method="post">
Test Address
<input type="text" id="address" name="address" placeholder="test"> />
Test phone
<input type="text" id="phone" name="phone" placeholder="test"> />
<input type="submit" name="Submit" value="Submit" />
</form>
I'm not sure how I can call the function from the other file to use in this file. How can I do this?
Everything seems ok, call the function after this:
<?php
require_once "queryDb.php";
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$address = $_POST["address"];
$phone = $_POST["phone"];
addCustomer($firstname, $lastname, $address, $phone);
In your main php file, you should write the following:
if($_POST)
{
require_once "queryDb.php";
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$address = $_POST["address"];
$phone = $_POST["phone"];
$result = addCustomer($firstname, $lastname, $address, $phone);
//Some redirect here based on the result
}
Of course you need to make sure that your form's action (reviewsubmit.php) is correct (Your main php file must be reviewsubmit.php, otherwise change the action to be your desired file).
Also you must add firstname and lastname inputs to your form like the following:
Firstname
<input type="text" id="firstname" name="firstname" placeholder="Enter Firstname"> />
Lastname
<input type="text" id="firstname" name="firstname" placeholder="Enter Firstname"> />
you sould use two separate files, one with your form an the other with rour function. And make an ajax call to your function.