Edit profile - PDO - php

I'm trying to include in my script the page to change the details of the user profile. I did it this way, in the class user.php I included this:
// Update profile
public function update($email,$gender,$location) {
try {
$stmt = $this->_db->prepare('UPDATE members SET email = ?, gender = ?, location = ? WHERE memberID = ? ');
$stmt->execute(array($email,$gender,$location,$_SESSION['memberID']));
return $stmt->fetch();
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
}
While, for example, the page account.php I did it this way:
if (isset($_POST['submit'])) {
// new data
$email = $_POST['email'];
$gender = $_POST['gender'];
$location = $_POST['location'];
$id = $_SESSION['memberID'];
// query
if ($user->update($email,$gender,$location,$id)); {
redirect('account.php');
}
}
And,
<form action="account.php" method="POST">
Email<br>
<input type="text" name="email" value="<?php echo $_SESSION['email'] ?>" /><br>
Gender<br>
<input type="text" name="gender" value="<?php echo $_SESSION['gender'] ?>" /><br>
Location<br>
<input type="text" name="location" value="<?php echo $_SESSION['location'] ?>" /><br>
<input type="submit" name="submit" value="Save" />
</form>
Use a connection in PDO from how it is understood, however, I have tried many options but always with poor results.

in your class the method:
public function update($email,$gender,$location);
It's not accepting the $id like parameter.
So the solution can be:
a. Use the id of the object and not use the $_SESSION['memberID'].
public function update($email,$gender,$location) {
try {
$stmt = $this->_db->prepare('UPDATE members SET email = ?, gender = ?, location = ? WHERE memberID = ?');
$stmt->execute(array($email,$gender,$location,$this->id);
return true;
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
return false;
}
b. Receive the id in the function and use it. If this is the case it's better to use this like a static method.
public static function update($email,$gender,$location,$id) {
try {
$stmt = $this->_db->prepare('UPDATE members SET email = ?, gender = ?, location = ? WHERE memberID = ?');
$stmt->execute(array($email,$gender,$location,$id);
return true;
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
return false;
}
So call it, depending of the strategy used. Also don't do echo in the method of the class model, just asign to a error message property and let the caller do the output.
Hope it helps.

Related

Array ( [0] => HY000 [1] => 1364 [2] => Field 'access_code' doesn't have a default value )

When I try registering a new user I keep getting the above error and when I set the field to null or delete it, the form doesn't run. Here are the codes:
The user.php has the User Class with the Function to create new user as displayed below:
<?php
// 'user' object
/**
* It is used for user object operations like creating a user deleting a user and more
*/
class User{
// database connection and table name
private $conn;
private $table_name = "users";
// object properties
public $id;
public $firstname;
public $lastname;
public $email;
public $contact_number;
public $address;
public $password;
public $access_level;
public $access_code;
public $status;
public $created;
public $modified;
// constructor
public function __construct($db){
$this->conn = $db;
}
// check if given email exist in the database
function emailExists(){
// query to check if email exists
$query = "SELECT id, firstname, lastname, access_level, password, status
FROM " . $this->table_name . "
WHERE email = ?
LIMIT 0,1";
// prepare the query
$stmt = $this->conn->prepare( $query );
// sanitize
$this->email=htmlspecialchars(strip_tags($this->email));
// bind given email value
$stmt->bindParam(1, $this->email);
// execute the query
$stmt->execute();
// get number of rows
$num = $stmt->rowCount();
// if email exists, assign values to object properties for easy access and use for php sessions
if($num>0){
// get record details / values
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// assign values to object properties
$this->id = $row['id'];
$this->firstname = $row['firstname'];
$this->lastname = $row['lastname'];
$this->access_level = $row['access_level'];
$this->password = $row['password'];
$this->status = $row['status'];
// return true because email exists in the database
return true;
}
// return false if email does not exist in the database
return false;
}
// create new user record
function create(){
// to get time stamp for 'created' field
$this->created=date('Y-m-d H:i:s');
// insert query
$query = "INSERT INTO
" . $this->table_name . "
SET
firstname = :firstname,
lastname = :lastname,
email = :email,
contact_number = :contact_number,
address = :address,
password = :password,
access_level = :access_level,
status = :status,
created = :created";
// prepare the query
$stmt = $this->conn->prepare($query);
// sanitize
$this->firstname=htmlspecialchars(strip_tags($this->firstname));
$this->lastname=htmlspecialchars(strip_tags($this->lastname));
$this->email=htmlspecialchars(strip_tags($this->email));
$this->contact_number=htmlspecialchars(strip_tags($this->contact_number));
$this->address=htmlspecialchars(strip_tags($this->address));
$this->password=htmlspecialchars(strip_tags($this->password));
$this->access_level=htmlspecialchars(strip_tags($this->access_level));
$this->status=htmlspecialchars(strip_tags($this->status));
// bind the values
$stmt->bindParam(':firstname', $this->firstname);
$stmt->bindParam(':lastname', $this->lastname);
$stmt->bindParam(':email', $this->email);
$stmt->bindParam(':contact_number', $this->contact_number);
$stmt->bindParam(':address', $this->address);
// hash the password before saving to database
$password_hash = password_hash($this->password, PASSWORD_BCRYPT);
$stmt->bindParam(':password', $password_hash);
$stmt->bindParam(':access_level', $this->access_level);
$stmt->bindParam(':status', $this->status);
$stmt->bindParam(':created', $this->created);
// execute the query, also check if query was successful
if($stmt->execute()){
return true;
}else{
$this->showError($stmt);
return false;
}
}
// read all user records
function readAll($from_record_num, $records_per_page){
// query to read all user records, with limit clause for pagination
$query = "SELECT
id,
firstname,
lastname,
email,
contact_number,
access_level,
created
FROM " . $this->table_name . "
ORDER BY id DESC
LIMIT ?, ?";
// prepare query statement
$stmt = $this->conn->prepare( $query );
// bind limit clause variables
$stmt->bindParam(1, $from_record_num, PDO::PARAM_INT);
$stmt->bindParam(2, $records_per_page, PDO::PARAM_INT);
// execute query
$stmt->execute();
// return values
return $stmt;
}
// used for paging users
public function countAll(){
// query to select all user records
$query = "SELECT id FROM " . $this->table_name . "";
// prepare query statement
$stmt = $this->conn->prepare($query);
// execute query
$stmt->execute();
// get number of rows
$num = $stmt->rowCount();
// return row count
return $num;
}
public function showError($stmt){
echo "<pre>";
print_r($stmt->errorInfo());
echo "</pre>";
}
}
My register.php is:
<?php
// core configuration
include_once "config/core.php";
// set page title
$page_title = "Register";
// include login checker
include_once "login_checker.php";
// include classes
include_once 'config/database.php';
include_once 'objects/user.php';
include_once "libs/php/utils.php";
// include page header HTML
include_once "layout_head.php";
echo "<div class='col-md-12'>";
// registration form HTML will be here
// code when form was submitted will be here
// if form was posted
if($_POST){
// get database connection
$database = new Database();
$db = $database->getConnection();
// initialize objects
$user = new User($db);
$utils = new Utils();
// set user email to detect if it already exists
$user->email=$_POST['email'];
// check if email already exists
if($user->emailExists()){
echo "<div class='alert alert-danger'>";
echo "The email you specified is already registered. Please try again or <a href='{$home_url}login'>login.</a>";
echo "</div>";
}
else{
// create user will be here
// set values to object properties
$user->firstname=$_POST['firstname'];
$user->lastname=$_POST['lastname'];
$user->contact_number=$_POST['contact_number'];
$user->address=$_POST['address'];
$user->password=$_POST['password'];
$user->access_level='Customer';
$user->status=1;
// create the user
if($user->create()){
echo "<div class='alert alert-info'>";
echo "Successfully registered. <a href='{$home_url}login'>Please login</a>.";
echo "</div>";
// empty posted values
$_POST=array();
}else{
echo "<div class='alert alert-danger' role='alert'>Unable to register. Please try again.</div>";
}
}
}
//Registration form
?>
<form action='register.php' method='post' id='register'>
<table class='table table-responsive'>
<tr>
<td class='width-30-percent'>Firstname</td>
<td><input type='text' name='firstname' class='form-control' required value="<?php echo isset($_POST['firstname']) ? htmlspecialchars($_POST['firstname'], ENT_QUOTES) : ""; ?>" /></td>
</tr>
<tr>
<td>Lastname</td>
<td><input type='text' name='lastname' class='form-control' required value="<?php echo isset($_POST['lastname']) ? htmlspecialchars($_POST['lastname'], ENT_QUOTES) : ""; ?>" /></td>
</tr>
<tr>
<td>Contact Number</td>
<td><input type='text' name='contact_number' class='form-control' required value="<?php echo isset($_POST['contact_number']) ? htmlspecialchars($_POST['contact_number'], ENT_QUOTES) : ""; ?>" /></td>
</tr>
<tr>
<td>Address</td>
<td><textarea name='address' class='form-control' required><?php echo isset($_POST['address']) ? htmlspecialchars($_POST['address'], ENT_QUOTES) : ""; ?></textarea></td>
</tr>
<tr>
<td>Email</td>
<td><input type='email' name='email' class='form-control' required value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email'], ENT_QUOTES) : ""; ?>" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type='password' name='password' class='form-control' required id='passwordInput'></td>
</tr>
<tr>
<td></td>
<td>
<button type="submit" class="btn btn-primary">
<span class="glyphicon glyphicon-plus"></span> Register
</button>
</td>
</tr>
</table>
</form>
<?php
echo "</div>";
// include page footer HTML
include_once "layout_foot.php";
?>
What do I need to do, please? If I have left something out in asking the question, please tell me.

My function doesn't post in the database

So I tried coding a function that allows the user to post a mood, chosen by a slider. I succeeded in connecting the color with an ID, then I tried making a post function. However Nothing happens.
this is where i call the functions.
if (isset($_POST['ready'])) {
$mood = new Post();
$moodColor = $_POST['mood'];
$statementMood = $mood->getMood($moodColor); //connects the color with an ID
while ($row = $statementMood->fetch(PDO::FETCH_ASSOC)) {
$moodID = $row['moodID'];
}
$moodID = $_GET['moodID'];
$userID = $currentUser['userID'];
$statementPost = $mood->postMood(); //put the emotion in the database.
//header('location: home.php');
}
these are the two functions.
public function getMood($moodColor){
$conn = db::getInstance();
$statementMood = $conn->prepare("SELECT * FROM moods WHERE color = :cMood");
$statementMood->bindParam(":cMood", $moodColor);
$statementMood->execute();
return $statementMood;
}
public function postMood(){
$conn = db::getInstance();
$statementPost = $conn->prepare("INSERT INTO postsmoodi (userID, moodID) VALUES (:userID, :moodID)");
$statementPost ->bindValue(':userID', $this->userID);
$statementPost->bindValue(':moodID', $this->moodID);
return $statementPost->execute();
}
this is the form where the button to post is.
<form class="input" action="mood.php" method="get">
<input id="hiddenValue" type="hidden" class="data" name="mood" value="">
<button class="moodReady" type="submit" name="ready">Ready</button>
</form>
Use $_GET instead of $_POST, as your form uses method="get"
if (isset($_GET['ready'])) {
$mood = new Post();
$moodColor = $_POST['mood'];
$statementMood = $mood->getMood($moodColor); //connects the color with an ID
while ($row = $statementMood->fetch(PDO::FETCH_ASSOC)) {
$moodID = $row['moodID'];
}
$moodID = $_GET['moodID'];
$userID = $currentUser['userID'];
$statementPost = $mood->postMood(); //put the emotion in the database.
//header('location: home.php');
}

trouble in inserting record to database using PHP mysqli oops [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am using PHP mysqli to access and insert record to database and also prepared statements but somewhere there is an error i couldn't figure out.. pointing out the mistake will be very much helpful
mailer.php
<?php
class Submit {
const DB = 'localhost',
USER = 'test',
PASS = '123456',
DB_NAME = 'testing';
private $mysql;
public function __construct() {
$this->mysql = new mysqli(self::DB , self::USER , self::PASS , self::DB_NAME);
if ($this->mysql->connect_errno) {
echo "Error: " . $this->mysql->connect_error;
echo "<br>";
echo "Error code: " . $this->mysql->connect_errno;
}
}
public function addRecord($record) {
$status = false;
$query = "INSERT INTO mytable (name,message) VALUES (?,?)";
$stmt = $this->mysql->prepare($query);
if ( $stmt ) {
$stmt->bind_param('ss', $record->name , $record->message);
if ($stmt->execute()) {
$status = ($stmt->affected_rows == 1) ? true : false;
$stmt->fetch_object();
$stmt->close();
}
}
return $status;
}
}
$submit = new Submit();
$result = null;
if (isset($_POST['submit']) ) {
$name = isset($_POST['name']) ? trim($_POST['name']) : '';
$message = isset($_POST['message']) ? trim($_POST['message']) : '';
$result = $submit->addRecord($name,$message);
if ($result) {
echo "Message Saved";
}
}
Also i am using ajax call from an external file containing a form and scripts within that
index.php
<!DOCTYPE html>
<html>
<head>
<title>Contact Form | PHP, AJAX and MySQL</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<br /><br />
<div class="container" style="width:500px;">
<form id="submit_form">
<label for="name">Name</label>
<input type="text" name="name" id="name" class="form-control" />
<br />
<label for="message">Message</label>
<textarea name="message" id="message" class="form-control"></textarea>
<br />
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
<span id="error_message" class="text-danger"></span>
<span id="success_message" class="text-success"></span>
</form>
</div>
</body>
</html>
<script>
jQuery(function($){
$('form#submit_form').submit(function(e){
e.preventDefault();
var name = $(this).find('#name').val(),
message = $(this).find('#message').val();
if(name == '' || message == '') {
$('#error_message').html("All Fields are required");
}
else {
$('#error_message').html('');
$.ajax({
url:"mailer.php",
method:"POST",
data:{
name: name,
message: message
},
success:function(data){
$("form").trigger("reset");
$('#success_message').fadeIn().html(data).fadeOut(3000);
}
});
}
});
});
</script>
You are giving 2 parameters to your addRecord() method, but it expects only 1. But, it seems it expects an object which you are not initializing so I adjusted it, so it takes the two parameters you are giving it.
public function addRecord($name, $message) {
$status = false;
$query = "INSERT INTO mytable (name,message) VALUES (?,?)";
$stmt = $this->mysql->prepare($query);
if ( $stmt ) {
$stmt->bind_param('ss', $name , $message);
if ($stmt->execute()) {
$status = $stmt->affected_rows === 1;
}
}
return $status;
}
Also I removed some unnecessary steps in the method:
$status = ($stmt->affected_rows == 1) ? true : false;
$status = $stmt->affected_rows === 1;
The comparison itself will return a boolean, so no need to use an explicit structure.
$stmt->fetch_object();
$stmt->close();
Fetching the object without ever using it is a waste.
When leaving the scope of the method, the garbage collector will unset the stmt.
Code to test the function:
class Submit {
const DB = 'localhost',
USER = 'test',
PASS = '123456',
DB_NAME = 'testing';
private $mysql;
public function __construct() {
$this->mysql = new mysqli(self::DB , self::USER , self::PASS , self::DB_NAME);
if ($this->mysql->connect_errno) {
echo "Error: " . $this->mysql->connect_error;
echo "<br>";
echo "Error code: " . $this->mysql->connect_errno;
}
}
public function addRecord($name, $message) {
$status = false;
$query = "INSERT INTO mytable (name,message) VALUES (?,?)";
$stmt = $this->mysql->prepare($query);
if ( $stmt ) {
$stmt->bind_param('ss', $name , $message);
if ($stmt->execute()) {
$status = $stmt->affected_rows === 1;
}
}
return $status;
}
}
$submit = new Submit();
$result = null;
$name = "dsfdsf";
$message = "message";
$result = $submit->addRecord($name,$message);
var_dump($result); // bool(true)

How can I call this PDO function within another function using PHP?

When I try to call the function "getAverage" within "storeRating", I get a HTML 500 server error. If I comment out that function, everything works perfectly. How can I call function "getAverage" withing function "storeRating"? Even if I leave that function uncommented, the code still checks for a duplicate rating and posts the new rating to the "rating" table. Please look at my code at the getAverage function. I need to be able to update the rating in the "products" table with the average.
Here are my PHP classes.
DB Functions:
<?php
class DB_TestFunctions {
private $conn;
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$db = new Db_Connect();
$this->conn = $db->connect();
}
// destructor
function __destruct() {
}
// Storing new rating
public function storeRating($pid, $userid, $ratingpnt) {
$stmt = $this->conn->prepare("INSERT INTO rating(ProductID,UserID,prod_rating) VALUES(?, ?, ?)");
$stmt->bind_param("sss", $pid, $userid, $ratingpnt);
$result = $stmt->execute();
$stmt->close();
getAverage($pid);
// check for successful store
/* if ($result) {
$stmt = $this->conn->prepare("SELECT * FROM products WHERE pid = ?");
$stmt->bind_param("s", $pid);
$stmt->execute();
$rating = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $rating;
} else {
return false;
} */
}
/**
* Check if rating exists
*/
public function checkDuplicate($pid, $userid) {
$stmt = $this->conn->prepare("SELECT prod_rating from rating WHERE ProductID = ? AND UserID = ?");
$stmt->bind_param("ss", $pid, $userid);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
// user existed
$stmt->close();
return true;
} else {
// user not existed
$stmt->close();
return false;
}
}
public function getAverage($pid){
$stmt = $this->conn->prepare("UPDATE products SET prod_rating = (SELECT AVG(prod_rating) FROM rating WHERE ProductID = ?) WHERE pid = ?");
$stmt->bind_param("s", $pid);
$stmt->execute();
$stmt->close();
}
public function getNewRating($pid){
$stmt = $this->conn->prepare("SELECT * FROM products WHERE pid = ?");
$stmt->bind_param("s", $pid);
$stmt->execute();
$rating = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $rating;
}
}
?>
postRate
<?php
require_once 'include/DB_TestFunctions.php';
$db = new DB_TestFunctions();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['pid']) && isset($_POST['userid']) && isset($_POST['rating'])) {
// receiving the post params
$pid = $_POST['pid'];
$userid = $_POST['userid'];
$rating = $_POST['rating'];
// check if user already rated product
if ($db->checkDuplicate($pid, $userid)) {
// user already rated this product
$response["error"] = TRUE;
$response["error_msg"] = "Rating already exists." ;
echo json_encode($response);
} else {
$db->storeRating($pid, $userid, $rating);
// get new rating
$rating = $db->getNewRating($pid);
if ($rating) {
// Rating successful
$response["error"] = FALSE;
$response["prod_rating"] = $rating["prod_rating"];
echo json_encode($response);
} else {
// Rating failed
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in posting rating!";
echo json_encode($response);
}
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameters (pid, userid or rating) are missing!";
echo json_encode($response);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test Post Rating</title>
</head>
<body>
<h1>Add Comment</h1>
<form action="postRate.php" method="post">
Product ID:<br />
<input type="text" name="pid" placeholder="Product ID" />
<br /><br />
Userid:<br />
<input type="text" name="userid" placeholder="Username" />
<br /><br />
Rating:<br />
<input type="text" name="rating" placeholder="rating" />
<br /><br />
<input type="submit" value="Rate" />
</form>
</body>
</html>
The problem is that you are calling getAverage() that is a method of yor class.
So you need to $this, that is a reference to the current object, in order to call that function from your object.
Changing your code to :
$this->getAverage()
will solve your problem.
You need to call $this->getAverage()
Probably you should have a look at the PHP manual

set session variable with fetch array PDO, not working

Coding, as I've been learning, is about little details, and I'm missing something because I have the following code:
public function login() {
if ($_POST) {
$logdb = new PDO('mysql:host=localhost;dbname=kiko', 'kiko', 'pass');
$logdb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $logdb->prepare("SELECT * FROM usreg WHERE email=:email AND password=:pass");
$stmt->bindParam(":email", $_POST['email']);
$stmt->bindParam(":pass", $_POST['password']);
$stmt->execute();
$loged = $stmt->fetch();
$atributes = $stmt->fetch(PDO::FETCH_ASSOC);
if ($loged) {
session_start();
$_SESSION["loggedIn"] = true;
$_SESSION["id"] = $atributes->id;
$_SESSION["email"] = $_POST['email'];
$_SESSION["group"] = $atributes->group;
$_SESSION["firstname"] = $atributes->firstname;
$_SESSION["lastname"] = $atributes->lastname;
$_SESSION["phone"] = $atributes->phone;
$_SESSION["mobile"] = $atributes->mobile;
$_SESSION["adress"] = $atributes->adress;
$_SESSION["city"] = $atributes->city;
$_SESSION["country"] = $atributes->country;
} else {
echo 'wrong login try again';
}
} else {
echo '<form name="login" action="" method="POST">
Email: <br />
<input type="text" name="email"/><br />
Password: <br />
<input type="password" name="password"/><br />
<button type="submit">Login</button>
Register</form>';
}
}
and everything works well except the part where I'm registering globals. What I'm trying to do is set the global session the details from the fetch array atributes, I tried with:
$atributes = $stmt->fetch(PDO::FETCH_OBJ);
but the result is the same, and I changed the email from array to POST and it works because when I do:
echo $_SESSION['email'];
It works, but the fetch is not passing the details to the other session globals. What should I put in there to sucess what I'm trying to do can you guys help me? Do I need another kind of prepared statement? Is it missing results because I'm making the WHERE clause?
Why are you fetching twice? Once for $loged and another for $atributes
I assume the username/password combination will be unique, so you'll only get one result from your SQL query. That means when you call fetch again, you'll get nothing.
Perhaps you want:
//$loged = $stmt->fetch();
$atributes = $stmt->fetch(PDO::FETCH_OBJ);
if ($atributes) {
session_start();
$_SESSION["loggedIn"] = true;
$_SESSION["id"] = $atributes->id;
Also, make sure you use password_verify when dealing with passwords!

Categories