How can I call this PDO function within another function using PHP? - 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

Related

How to iterate through data that are comming from database, when clicking a button

I am making a website to submit answers for a questionnaire.
Every question is created by an admin from the dashboard, and the goal is to make the page dynamic by fetching the questions and answers for those questions from database.
Basically this:
So the goal is when I click the answer of one of this buttons, to show up the next question (fetching the second question from the database also the three answers relating to that question and so on).
For the back-end developing I'm using pure PHP since I'm new to programming, and PDO for manipulating with data from database.
For managing with the data I am using Controllers, and for connecting with database I have made the connection on /core/Database.php
Any help is appreciated.. thanks for your time
Here is what i tried so far.
<?php
session_start();
require './controllers/UserController.php';
$user = new UserController;
$arr = $users=$user->getQuestions();
$index = 0;
$answ1 = $user->getAnswers();
$index = 0;
$_SESSION['answerOne'] = $_POST['question1'];
// $_SESSION['answerTwo'] = $_POST['question2'];
// $_SESSION['answerThree'] = $_POST['question3'];
// $_SESSION['answerFour'] = $_POST['question4'];
echo $_SESSION['answerOne'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="./styling/questionstyle.css">
<title>Question</title>
</head>
<body>
<div class="hero">
<div class="questionContainer">
<div class="header">
<img src="./assets/back.png" height="35%" class="backImage">
<h2 class="questionNumber">01/04</h2>
</div>
<progress max="100" value="10"></progress>
<h1 class="question">
<?php echo $arr[$index]['description'] ?>
</h1>
</div>
<div class="answerContainer">
<img src="./assets/shadow.png" width="100%">
<form action="" method="POST">
<button class="button" onclick="document.getElementById('q1').value ='a'"><h4 class="choice">a</h4><h4 class="answer"><?php echo $answ1[$index]['choice1']?></h4></button> <br>
<button class="button2" onclick="document.getElementById('q1').value ='b'"><h4 class="choice">b</h4><h4 class="answer"><?php echo $answ1[$index]['choice2']?></h4></button> <br>
<button class="button2"onclick="document.getElementById('q1').value ='c'" ><h4 class="choice">c</h4><h4 class="answer"><?php echo $answ1[$index]['choice3']?></h4></button>
<input type="hidden" id="q1" name="question1">
<input type="hidden" id="q2" name="question2">
<input type="hidden" id="q3" name="question3">
<input type="hidden" id="q4" name="question4">
<br>
</form>
</div>
</div>
</body>
</html>
<?php
include './core/Database.php';
?>
class UserController
{
protected $db;
public function __construct()
{
$this->db = new Database;
}
public function all()
{
$query = $this->db->pdo->query('SELECT * FROM user');
return $query->fetchAll();
}
public function store($request)
{
isset($request['is_admin']) ? $isAdmin = 1 : $isAdmin = 0;
$password = password_hash($request['password'], PASSWORD_DEFAULT);
$query = $this->db->pdo->prepare('INSERT INTO users (name, email, password, is_admin) VALUES (:name, :email, :password, :is_admin)');
$query->bindParam(':name', $request['fullName']);
$query->bindParam(':email', $request['email']);
$query->bindParam(':password', $password);
$query->bindParam(':is_admin', $isAdmin);
$query->execute();
return header('Location: ./index.php');
}
public function edit($id)
{
$query = $this->db->pdo->prepare('SELECT * FROM users WHERE id = :id');
$query->execute(['id' => $id]);
return $query->fetch();
}
public function update($id, $request)
{
isset($request['is_admin']) ? $isAdmin = 1 : $isAdmin = 0;
$query = $this->db->pdo->prepare('UPDATE users SET name = :name, email = :email, is_admin = :is_admin WHERE id = :id');
$query->execute([
'name' => $request['fullName'],
'email' => $request['email'],
'is_admin' => $isAdmin,
'id' => $id
]);
return header('Location: ./index.php');
}
public function destroy($id)
{
$query = $this->db->pdo->prepare('DELETE FROM users WHERE id = :id');
$query->execute(['id' => $id]);
return header('Location: ./index.php');
}
public function totalpa(){
$query= $this->db->pdo->query('SELECT count(*) FROM user');
$query->execute();
return $query->fetchColumn();
}
public function totalfemra(){
$query= $this->db->pdo->query("SELECT count(*) FROM user WHERE gender='F'");
$query->execute();
return $query->fetchColumn();
}
public function totalmeshkuj(){
$query=$this->db->pdo->query("SELECT count(*) from user WHERE gender ='M'");
$query->execute();
return $query->fetchColumn();
}
public function storeUser($req){
$query = $this->db->pdo->prepare('INSERT INTO user (city, gender, age) VALUES (:city, :gender, :age)');
$query->bindParam(':city', $_SESSION['cityID']);
$query->bindParam(':gender', $_SESSION['gender']);
$query->bindParam(':age', $_SESSION['age']);
$query->execute();
}
public function storeQuestion($req){
$query=$this->db->pdo->prepare('INSERT INTO question(description) VALUES(:description)');
$query->bindParam(':description',$_POST['pyetja']);
$query->execute();
}
public function storeAnswer($param){
$query=$this->db->pdo->prepare('INSERT into add_answer (q_id,choice1,choice2,choice3) VALUES(:q_id,:ch1,:ch2,:ch3)');
$query->bindParam(':q_id',$param);
$query->bindParam(':ch1', $_POST['choice1']);
$query->bindParam(':ch2',$_POST['choice2']);
$query->bindParam(':ch3',$_POST['choice3']);
$query->execute();
}
public function getLastInsertedId(){
$query=$this->db->pdo->prepare('SELECT MAX(qid) from question');
$query->execute();
return $query->fetchColumn();
}
public function getQuestions(){
$query= $this->db->pdo->query('SELECT * FROM question');
$query->execute();
return $query->fetchAll();
}
public function getAnswers(){
try{
$query =$this->db->pdo->query('SELECT * FROM add_answer a INNER JOIN question q ON a.q_id = q.qid');
$query -> execute();
return $query->fetchAll();
}catch(Exception $ex){
echo 'error';
}
}
}

PHP MySQL row editor showing in wrong order

Trying to make something so I can edit rows from database using a PHP form but when I click edit it shows in the wrong order.
I know I can't edit the top one because it's ID is 0 and i'll change that later on but the others are showing when editing they are Text, Name, Rank
But I want them to be Name, Rank, Text
You can try for yourself here:http://rumblegaming.co.uk/admin/home
<?php
/*
Allows the user to both create new records and edit existing records
*/
// connect to the database
include("connect.php");
// creates the new/edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($name = '', $rank ='', $text ='', $error = '', $id = '')
{ ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>
<?php if ($id != '') { echo "Edit Record"; } else { echo "New Record"; } ?>
</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<h1><?php if ($id != '') { echo "Edit Record"; } else { echo "New Record"; } ?></h1>
<?php if ($error != '') {
echo "<div style='padding:4px; border:1px solid red; color:red'>" . $error
. "</div>";
} ?>
<form action="" method="post">
<div>
<?php if ($id != '') { ?>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<p>ID: <?php echo $id; ?></p>
<?php } ?>
<strong>Name:</strong> <input type="text" name="name"
value="<?php echo $name; ?>"/><br/>
<strong>Rank:</strong> <input type="text" name="rank"
value="<?php echo $rank; ?>"/><br/>
<strong>Text:</strong> <input type="text" name="text"
value="<?php echo $text; ?>"/><br/>
<input type="submit" name="submit" value="Submit" />
</div>
</form>
</body>
</html>
<?php }
/*
EDIT RECORD
*/
// if the 'id' variable is set in the URL, we know that we need to edit a record
if (isset($_GET['id']))
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// make sure the 'id' in the URL is valid
if (is_numeric($_POST['id']))
{
// get variables from the URL/form
$id = $_POST['id'];
$name = htmlentities($_POST['name'], ENT_QUOTES);
$rank = htmlentities($_POST['rank'], ENT_QUOTES);
$text = htmlentities($_POST['text'], ENT_QUOTES);
// check that firstname and lastname are both not empty
if ($name == '' || $rank == '')
{
// if they are empty, show an error message and display the form
$error = 'ERROR: Please fill in all required fields!';
renderForm($name, $rank, $text, $error, $id);
}
else
{
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE Team SET name = ?, rank = ?, text = ? WHERE id=?"))
{
$stmt->bind_param("sssi", $name, $rank, $text, $id);
$stmt->execute();
$stmt->close();
}
// show an error message if the query has an error
else
{
echo "ERROR: could not prepare SQL statement.";
}
// redirect the user once the form is updated
header("Location: home");
}
}
// if the 'id' variable is not valid, show an error message
else
{
echo "Error!";
}
}
// if the form hasn't been submitted yet, get the info from the database and show the form
else
{
// make sure the 'id' value is valid
if (is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// get 'id' from URL
$id = $_GET['id'];
// get the recod from the database
if($stmt = $mysqli->prepare("SELECT * FROM Team WHERE id=?"))
{
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($id, $rank, $text, $name);
$stmt->fetch();
// show the form
renderForm($name, $rank, $text, NULL, $id);
$stmt->close();
}
// show an error if the query has an error
else
{
echo "Error: could not prepare SQL statement";
}
}
// if the 'id' value is not valid, redirect the user back to the view.php page
else
{
header("Location: home");
}
}
}
/*
NEW RECORD
*/
// if the 'id' variable is not set in the URL, we must be creating a new record
else
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// get the form data
$firstname = htmlentities($_POST['firstname'], ENT_QUOTES);
$lastname = htmlentities($_POST['lastname'], ENT_QUOTES);
// check that firstname and lastname are both not empty
if ($firstname == '' || $lastname == '')
{
// if they are empty, show an error message and display the form
$error = 'ERROR: Please fill in all required fields!';
renderForm($firstname, $lastname, $error);
}
else
{
// insert the new record into the database
if ($stmt = $mysqli->prepare("INSERT players (firstname, lastname) VALUES (?, ?)"))
{
$stmt->bind_param("ss", $firstname, $lastname);
$stmt->execute();
$stmt->close();
}
// show an error if the query has an error
else
{
echo "ERROR: Could not prepare SQL statement.";
}
// redirec the user
header("Location: view.php");
}
}
// if the form hasn't been submitted yet, show the form
else
{
renderForm();
}
}
// close the mysqli connection
$mysqli->close();
?>
You can simply re-arrange your select statement.
eg. instead of
if($stmt = $mysqli->prepare("SELECT * FROM Team WHERE id=?"));
use
if($stmt = $mysqli->prepare("SELECT Name, Rank, Text FROM Team WHERE id=?"));

Calling Method on Action Form PHP

I'm trying to make a login form using function, Im using class and function in different file. Here my code.
Login Form
<?php
require_once("controller/ED_Setting.php");
?>
<!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>Example Test</title>
</head>
<body>
<?php
if(isset($_REQUEST['failure']))
{
echo "User/Password Wrong";
}
?>
<form action=""<?php echo "/mvc/controller/login.php";?>"" method="post">
<label>Email:</label>
<input type="text" name="username" />
<br />
<label>Password:</label>
<input type="password" name="password" />
<br />
<input type="submit" name="cmdlogin" value="Login" />
</form>
</body>
</html>
And the login Function I Call
<?php
require_once("ED_Setting.php");
class login
{
function index()
{
$db = new ED_Setting();
$db->connect();
if(isset($_REQUEST['cmdlogin']))
{
$rs = $db->select("SELECT * FROM tbl_user where username = '".$_REQUEST['username']."' and password= '".($_REQUEST['password'])."'");
$res = $db->getResult();
if($res)
{
header('location: http://blup2h.rf.gd');
}
else
{
header('location: http://localhost/project/index.php?failure');
}
}
}
}
?>
And the Setting Connection is like this
<?php
class ED_Setting
{
private $db_host = "localhost"; // Change as required
private $db_user = "root"; // Change as required
private $db_pass = ""; // Change as required
private $db_name = "db_pembukuan"; // Change as required
private $con = false; // Check to see if the connection is active
private $result = array(); // Any results from a query will be stored here
// Function to make connection to database
public function connect(){
if(!$this->con){
$myconn = #mysqli_connect($this->db_host,$this->db_user,$this->db_pass,$this->db_name); // mysql_connect() with variables defined at the start of Database class
if($myconn){
return true;
}else{
array_push($this->result,mysqli_error());
return false; // Problem connecting return FALSE
}
}else{
return true; // Connection has already been made return TRUE
}
}
// Function to disconnect from the database
public function disconnect(){
// If there is a connection to the database
if($this->con){
// We have found a connection, try to close it
if(#mysql_close()){
// We have successfully closed the connection, set the connection variable to false
$this->con = false;
// Return true tjat we have closed the connection
return true;
}else{
// We could not close the connection, return false
return false;
}
}
}
public function select($sql){
$query = #mysqli_query($sql);
// $this->myQuery = $sql; // Pass back the SQL
if($query){
// If the query returns >= 1 assign the number of rows to numResults
$this->numResults = mysqli_num_rows($query);
// Loop through the query results by the number of rows returned
for($i = 0; $i < $this->numResults; $i++){
$r = mysqli_fetch_array($query);
$key = array_keys($r);
for($x = 0; $x < count($key); $x++){
// Sanitizes keys so only alphavalues are allowed
if(!is_int($key[$x])){
if(mysqli_num_rows($query) >= 1){
$this->result[$i][$key[$x]] = $r[$key[$x]];
}else{
$this->result = null;
}
}
}
}
return true; // Query was successful
}else{
array_push($this->result,mysqli_error());
return false; // No rows where returned
}
}
// Function to update and delete into the database
public function query($sql)
{
if($query = #mysql_query($sql)){
array_push($this->result,mysql_affected_rows());
return true;
}else{
array_push($this->result,mysql_error());
return false;
}
}
// Public function to return the data to the user
public function getResult(){
$val = $this->result;
$this->result = array();
return $val;
}
}
?>
But it did'nt work. Any answers please?
Probably the problem is "" using on form action attribute.
Use this line
<form action="<?php echo "/mvc/controller/login.php";?>" method="post">
Instead of
<form action=""<?php echo "/mvc/controller/login.php";?>"" method="post">

Having Problems with PHP Mysql Sessions

Recently, I have been having a problem with my sessions, and corresponding session variables.
The problem, is that, when I POST sessions1.php, the session variable seems to work, and gets carried over into sessions2.php.
But, when the link to go to sessions3.php is clicked, the session variable doesn't seem to be set, when in sessions3.php. Thus, returning code from the "else" block, within the "if/else" conditional.
Something similar seems to be happening when I use either a database, or /tmp file setup, for storing data.
In the database example, the session is written to the sessions table. However, when I click the link, going from sessions2.php, which takes me to sessions3.php, the session variable doesn't seem to be set. And, when I click the "logout" button, within sessions3.php, the link takes me back to sessions1.php, which is what is supposed to happen. However, when I check the database (or at least refresh the sessions table), the session is not removed, or destroyed, according to what should be happening in line with the SessionHandler class.
Furthermore, still with the database example: when I submit sessions1.php, and am taken to sessions2.php, the right session row is created within the sessions table. However, when I click on the link that takes me to sessions3.php, another row is created, within the sessions table: this time, without any data, in the data column.
On the other hand, in an test without a database, thus, resorting to using the file-system instead: after submitting sessions1.php, the file appears in the /tmp directory. However, on inspection, that file remains empty. Please, also bear in mind that, when using a simple file-system example, the "SessionHandler", and db connection, code is not present within the files.
Any possible solutions?.
I am using PHP7, Apache 2.4, and MySQL 5.6.27. And, I am wondering whether my config settings (php.ini, and/or httpd) may have anything to do with the problem (since, even without a database, the interactions between sessions2.php, and sessions3.php produce somewhat similar results (session variable not set, by the time I get to sessions3.php)).
THE CODE:
sessions1.php(below)
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Session Test</title>
</head>
<body>
<form method="post" action="sessions2.php">
<p>
<label for="name">Enter your first name: </label>
<input type="text" name="name" id="name">
</p>
<p>
<input type="submit" name="submit" value="Submit">
</p>
</form>
</body>
</html>
session2.php (below)
<?php
use SomeNamespace\Sessions\SessionHandler;
require_once('/databases/dbConnect.php');
require_once('/classes/Sessions/SessionHandler.php');
$handler = new SessionHandler($db);
session_set_save_handler($handler);
session_start();
if (isset($_POST['name'])) {
if (!empty($_POST['name'])) {
$_SESSION['name'] = htmlentities($_POST['name']);
} else {
$_SESSION['name'] = 'Nobody Here!';
}
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Session Test</title>
</head>
<body>
<p>Hello, <?php
if (isset($_SESSION['name'])) {
echo $_SESSION['name'];
} else {
echo 'stranger';
}
?>.</p>
<p>Go to page 3</p>
</body>
</html>
session3.php (below)
<?php
use SomeNamespace\Sessions\SessionHandler;
require_once('/databases/dbConnect.php');
require_once('/classes/Sessions/SessionHandler.php');
$handler = new SessionHandler($db);
session_set_save_handler($handler);
session_start();
if (isset($_POST['logout'])) {
$_SESSION = [];
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 86400, $params['path'],
$params['domain'], $params['secure'], $params['httponly']);
session_destroy();
header('Location: sessions1.php');
exit;
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Session Test</title>
</head>
<body>
<p>Hello<?php
if (isset($_SESSION['name'])) {
echo ' again, ' . $_SESSION['name'];
} else {
echo ', Nobody!';
}
?>.</p>
<form method="post" action="<?= $_SERVER['PHP_SELF']; ?>">
<p><input type="submit" name="logout" value="Log Out"></p>
</form>
</body>
</html>
SessionHandler.php (below) The session handler class.
namespace SomeNamespace\Sessions;
class SessionHandler implements \SessionHandlerInterface
{
protected $db;
protected $useTransactions;
protected $expiry;
protected $table_sess = 'sessions';
protected $col_sid = 'sessionID';
protected $col_expiry = 'expiry';
protected $col_data = 'data';
protected $unlockStatements = [];
protected $collectGarbage = false;
public function __construct(\PDO $db, $useTransactions = true)
{
$this->db = $db;
if ($this->db->getAttribute(\PDO::ATTR_ERRMODE) !== \PDO::ERRMODE_EXCEPTION) {
$this->db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
}
$this->useTransactions = $useTransactions;
$this->expiry = time() + (int) ini_get('session.gc_maxlifetime');
}
public function open($save_path, $name)
{
return true;
}
public function read($session_id)
{
try {
if ($this->useTransactions) {
$this->db->exec('SET TRANSACTION ISOLATION LEVEL READ COMMITTED');
$this->db->beginTransaction();
} else {
$this->unlockStatements[] = $this->getLock($session_id);
}
$sql = "SELECT $this->col_expiry, $this->col_data
FROM $this->table_sess WHERE $this->col_sid = :sessionID";
if ($this->useTransactions) {
$sql .= ' FOR UPDATE';
}
$selectStmt = $this->db->prepare($sql);
$selectStmt->bindParam(':sessionID', $session_id);
$selectStmt->execute();
$results = $selectStmt->fetch(\PDO::FETCH_ASSOC);
if ($results) {
if ($results[$this->col_expiry] < time()) {
return '';
}
return $results[$this->col_data];
}
if ($this->useTransactions) {
$this->initializeRecord($selectStmt);
}
return '';
} catch (\PDOException $e) {
if ($this->db->inTransaction()) {
$this->db->rollBack();
}
throw $e;
}
}
public function write($session_id, $data)
{
try {
$sql = "INSERT INTO $this->table_sess ($this->col_sid,
$this->col_expiry, $this->col_data)
VALUES (:sessionID, :expiry, :data)
ON DUPLICATE KEY UPDATE
$this->col_expiry = :expiry,
$this->col_data = :data";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':expiry', $this->expiry, \PDO::PARAM_INT);
$stmt->bindParam(':data', $data);
$stmt->bindParam(':sessionID', $session_id);
$stmt->execute();
return true;
} catch (\PDOException $e) {
if ($this->db->inTransaction()) {
$this->db->rollback();
}
throw $e;
}
}
public function close()
{
if ($this->db->inTransaction()) {
$this->db->commit();
} elseif ($this->unlockStatements) {
while ($unlockStmt = array_shift($this->unlockStatements)) {
$unlockStmt->execute();
}
}
if ($this->collectGarbage) {
$sql = "DELETE FROM $this->table_sess WHERE $this->col_expiry < :time";
$stmt = $this->db->prepare($sql);
$stmt->bindValue(':time', time(), \PDO::PARAM_INT);
$stmt->execute();
$this->collectGarbage = false;
}
return true;
}
public function destroy($session_id)
{
$sql = "DELETE FROM $this->table_sess WHERE $this->col_sid = :sessionID";
try {
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':sessionID', $session_id);
$stmt->execute();
} catch (\PDOException $e) {
if ($this->db->inTransaction()) {
$this->db->rollBack();
}
throw $e;
}
return true;
}
public function gc($maxlifetime)
{
$this->collectGarbage = true;
return true;
}
protected function getLock($session_id)
{
$stmt = $this->db->prepare('SELECT GET_LOCK(:key, 50)');
$stmt->bindValue(':key', $session_id);
$stmt->execute();
$releaseStmt = $this->db->prepare('DO RELEASE_LOCK(:key)');
$releaseStmt->bindValue(':key', $session_id);
return $releaseStmt;
}
protected function initializeRecord(\PDOStatement $selectStmt)
{
try {
$sql = "INSERT INTO $this->table_sess ($this->col_sid, $this->col_expiry, $this->col_data)
VALUES (:sessionID, :expiry, :data)";
$insertStmt = $this->db->prepare($sql);
$insertStmt->bindParam(':sessionID', $session_id);
$insertStmt->bindParam(':expiry', $this->expiry, \PDO::PARAM_INT);
$insertStmt->bindValue(':data', '');
$insertStmt->execute();
return '';
} catch (\PDOException $e) {
if (0 === strpos($e->getCode(), '23')) {
$selectStmt->execute();
$results = $selectStmt->fetch(\PDO::FETCH_ASSOC);
if ($results) {
return $results[$this->col_data];
}
return '';
}
if ($this->db->inTransaction()) {
$this->db->rollback();
}
throw $e;
}
}
}

Edit profile - PDO

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.

Categories