Today i tired pass from the mysql connection to PDO. And i met a problem.
require('config.php');
function GetAll($query, $params) {
global $db;
try {
$sth = $db->prepare($query);
}
catch (PDOException $e) {
return null;
}
try {
$sth->execute($params);
}
catch (PDOException $e) {
return null;
}
$result = $sth->fetchAll();
return $result;
}
if ($fetch = GetAll("SELECT `loggedip` FROM `ipcheck` WHERE `loggedip`=':ipcheck'", array(":ipcheck" => $iptocheck))) {
$resultx = $db->prepare("SELECT `failedattempts` FROM `ipcheck` WHERE `loggedip`='$iptocheck'");
$resultx->execute();
while ($rowx = $resultx->fetch()) {
;
}
$loginattempts_total = $rowx['failedattempts'];
echo "$loginattempts_total";
if ($loginattempts_total > $maxfailedattempt) {
header(sprintf("Location: %s", $forbidden_url));
exit;
}
}
this is my script. in PDO and his don't work. when my ip is banned should not see, but i see the page. PLEASE HELP ((
Related
Hi I get the "There is no active transaction" when I run my code below:
public function Login($username, $password)
{
try
{
$database = db_camagru();
$query = "SELECT id FROM users WHERE (username=:username OR email=:username) AND password=:password";
$database->exec($query);
$database->commit();
if ($query->rowCount() > 0)
{
$result = $query->fetch(PDO::FETCH_OBJ);
return $result->id;
}
else
{
return false;
}
}
catch (PDOException $e)
{
exit($e->getMessage() . "kwezi");
}
}
the error seems to be coming from my $database->commit(); line.
I make users online page using PHP - OOP - PDO
include_once '../database.php';
$db = new database();
$getRows = $db->getRows('select * from visitors_online');
$gr = $db->rowCount();
$online = '';
$getRow = $db->getRow('select * from user_online');
$gr2 = $db->rowCount();
if(!empty($gr2)) {
try {
while ($getR = $getRow){
$getRow = $db->getRow('select * from users where id = ?',[$getR['session']]);
echo ',   '.$getRow['username'].'   ';
}
} catch (PDOException $e) {
die('Error :'. $e->getMessage());
}
$total = $gr + $gr2;
The problems is:
* Not show any users except Admin, also I got this :
ONLINE
admin
Notice: Undefined index: session in /Applications/MAMP/htdocs/baws/admin/online.php on line 56
,
.Users = 0 ,Member = 2 , Register = 2
Who is online list
Here is the function from Database class
// Get row by id, username, or email etc..
public function getRow($query, $para = []){
try {
$this->stmt = $this->datab->prepare($query);
$this->stmt->execute($para);
return $this->stmt->fetch();
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
Any Help
Thanks
I tried to simplify a bit your code as I do not know your class details and it s messy.
The problem is you are not binding stuff properly neither fetching them properly too. Also, you are preparing the second query, each time you loop inside the query 1 results , that is useless. prepare both (withyour class or not) and just bind and execute.
$stmt1 = $db->prepare('select * from user_online where id= ?');
$result1 = getRows($stmt1, "1");
$gr1 = $db->rowCount();
if (!empty($gr1)) {
$stmt2 = $db->prepare('select * from users where id = ?');
foreach ($result1 as $key1 => $h1) {
$stmt2->bindParam(1, $h1['session'], PDO::PARAM_INT);
$stmt2->execute();
$result2 = $stmt2->fetchAll(PDO::FETCH_ASSOC);
if (count($result2) !== 0) {
foreach ($result2 as $key2 => $r2) {
echo ',   ' . $r2['username'] . '   ';
}
}
}
}
function getRow($query, $para) {
$stmt1->bindParam(1, $para, PDO::PARAM_INT);
try {
$stmt1->execute($para);
$result1 = $stmt1->fetchAll(PDO::FETCH_ASSOC);
return $result1;
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
Please find the database class here
class database {
public $isConn;
protected $datab;
private $stmt;
public function __construct() {
$this->connect();
}
// connect to database
private function connect(){
$host = 'localhost';
$db = 'baws';
$user = 'root';
$pass = 'root';
$option = [];
$this->isConn = TRUE;
try {
$this->datab = new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $user, $pass, $option);
$this->datab->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo '<h3>Not connected</h3>' . $e->getMessage();
}
}
// Disconnected from database
private function disconnect(){
$this->isConn = NULL;
$this->datab = FALSE;
}
//insert to database
public function insertRow($query, $para = []){
try {
$this->stmt = $this->datab->prepare($query);
$this->stmt->execute($para);
return TRUE;
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
//update row to database
public function updateRow($query, $para = []){
$this->insertRow($query, $para);
}
//Delete row from database
public function deleteRow($query, $para = []){
$this->insertRow($query, $para);
}
// Get row by id, username, or email etc..
public function getRow($query, $para = []){
try {
$this->stmt = $this->datab->prepare($query);
$this->stmt->execute($para);
return $this->stmt->fetch();
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
}
online.php Page
ob_start();
echo "ONLINE <br>";
include_once '../database.php';
$db = new database();
try {
$session=$_COOKIE['id'];
$time=time();
$time_check=$time-300; //SET TIME 10 Minute
$getRow = $db->getRow("SELECT * FROM user_online WHERE session = ?", [$session]);
$count =$db->rowCount($getRow);
if($count == '0'){
$insertRow = $db->insertRow("INSERT INTO user_online(session, time)VALUES(? , ?)",[$session, $time ]);
}
elseif($count != '0'){
$updateRow = $db->updateRow("UPDATE user_online SET time = ? WHERE session = ?", [$time, $session]);
}else{
$deleteRow = $db->deleteRow("DELETE FROM user_online WHERE time < ? ", [$time_check]);
}
} catch (PDOException $e) {
die('Error :'. $e->getMessage());
}
try {
$ip=$_SERVER['REMOTE_ADDR'];
$session=$ip;
$time=time();
$time_check=$time-300; //SET TIME 10 Minute
$deleteRow = $db->deleteRow("DELETE FROM visitors_online WHERE time < ? ", [$time_check]);
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
$getRows = $db->getRows('select * from visitors_online');
$gr = $db->rowCount();
$online = '';
$getRow = $db->getRow('select * from user_online');
$gr2 = $db->rowCount();
if(!empty($gr2)) {
try {
while ($getR = $getRow){
$getRow = $db->getRow('select * from users where id = ?',[$getR['session']]);
echo ',   '.$getRow['username'].'   ';
}
} catch (PDOException $e) {
die('Error :'. $e->getMessage());
}
$total = $gr + $gr2;
} //end
I am in the process of learning PDO and am trying to implement it in my current project. When I used mysqli, I could get detailed info about any error using mysqli_error($connection). I googled at what the comparable for PDO would be and found this post, and decided to implement it in my code. However, I am unable to get any error messages even when I know there is an obvious error in the sql statement.
Relevant code:
class Database {
public $connection;
function __construct() {
$this->open_database_connection();
}
public function open_database_connection() {
try {
$this->connection = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASSWORD);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->connection->setAttribute( PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $e) {
echo $e->getMessage();
die('Could not connect');
}
} // end of open_database_connection method
public function query($sql, $params = []) {
try {
$query = $this->connection->prepare($sql);
} catch (Exception $e) {
var_dump('mysql error: ' . $e->getMessage());
}
foreach($params as $key => $value) {
if ($key === ':limit') {
$query->bindValue($key, $value, PDO::PARAM_INT);
} else {
$query -> bindValue($key, $value);
}
}
try {
$query->execute();
} catch(Exception $e) {
echo 'Exception -> ';
var_dump($e->getMessage());
}
/*
DID NOT WORK:
if (!$query->execute()) {
print_r($query->errorinfo());
}*/
$result = $query->fetchAll(PDO::FETCH_ASSOC);
$this->confirm_query($result);
return $result;
} // end of query method
function confirm_query($query) {
if (!$query) {
die('mysql error: ');
}
}
When I run the code, I do get the "mysql error", but I do not get any details about it. What am I doing wrong?
Update: As requested, I am providing additional details below.
What I am trying to do is get the user's login detail to be verified. To that end, once the user inputs his credentials , this code runs:
if (isset($_POST['submit'])) {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
//check the database for the user
$user_found = User::verify_user($username, $password);
Relevant code from the User class:
public static function verify_user($username, $password) {
global $db;
$username = $db->escape_string($username);
$password = $db->escape_string($password);
$values = [ ":username" => $username,
":password" => $password,
":limit" => 1
];
$result_array = self::find_this_query("SELECT * FROM users WHERE username=:username AND password=:password LIMIT :limit", true, $values);
return !empty($result_array)? array_shift($result_array) : false;
}
public static function find_this_query($sql, $prepared = false, $params = []) {
global $db;
$the_object_array = array();
$result = $db->query($sql, $params);
$arr_length = count($result);
for ($i = 0; $i < $arr_length; $i++) {
$the_object_array[] = self::instantiation($result[$i]);
}
return $the_object_array;
}
public static function instantiation($the_record) {
$the_object =new self; //we need new self because $the_record corresponds to one user!
foreach($the_record as $the_attribute => $value) {
if ($the_object->has_the_attribute($the_attribute)) {
$the_object->$the_attribute = $value;
}
}
return $the_object;
}
public function has_the_attribute($attribute) {
$object_properties = get_object_vars($this);
return array_key_exists($attribute, $object_properties);
}
You have to use PDO::errorInfo():
(...)
public function query($sql, $params = []) {
try {
$query = $this->connection->prepare($sql);
if( !$query )
{
$error = $this->connection->errorInfo();
die( "mysql error: {$error[2]}" );
}
} catch (Exception $e) {
var_dump('mysql error: ' . $e->getMessage());
}
(...)
}
PDO::errorInfo returns an array:
Element 0: SQLSTATE error code (a five characters alphanumeric identifier defined in the ANSI SQL standard);
Element 1: Driver-specific error code;
Element 2: Driver-specific error message.
I have integrated google loing to my website. It's working fantastic. When someone logs in via google for the firs time, then a new entry is stored in the database.
But, when he logs in again..only the last login (a column on the table) should be updated...but instead, mysql adds a new row.
What am I doing wrong here?
public function trigger_registration_from_google($fname,$lname,$email)
{
global $conn;
try
{
if(useremailexists($email))
{
$date = date('Y-m-d');
//run update query
//user already exists, only update
try
{
$s = $conn->prepare("UPDATE users set last_login = :last_login where emailid = :email ");
$s->bindParam(':last_login',$date);
$s->bindParam(':email',$email);
$s->execute();
$s->closeCursor();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
else
{
//insert
//insert now..since he is a new user
$date = date('Y-m-d');
$v=1;
$r="google";
try
{
$s = $conn->prepare("INSERT INTO users(fname,lname,emailid,registeredby,registeredon,last_login,verified) values (:fname,:lname,:emailid,:registeredby,:registeredon,:last_login,:verified)");
$s->bindParam(':fname',$fname);
$s->bindParam(':lname',$lname);
$s->bindParam(':emailid',$email);
$s->bindParam(':registeredby',$r);
$s->bindParam(':registeredon',$date);
$s->bindParam(':last_login',$date);
$s->bindParam(':verified',$v);
$s->execute();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}//function
Edit
useremailexists
function useremailexists($email)
{
//check if the email exists
global $conn;
try
{
$s = $conn->prepare("SELECT * from users where emailid = :email");
$s->bindParam(':email',$email);
$s->execute();
if($s->rowCount() > 0)
{
return true;
}
else
{
return false;
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}//function
Validate if the function useremailexist return true or false , we can't help you without this piece of code.
Why would it not work to call the get_accounts() function at the end of the delete_account() function?
function get_accounts() {
require(ROOT_PATH . "inc/database.php");
try {
$results = $db->query("SELECT * FROM account");
} catch (Exception $e) {
echo ("ERROR: Data could not be retrieved from the database." . $e);
exit;
}
$accounts = $results->fetchall(PDO::FETCH_ASSOC);
return $accounts;
}
if(isset($_GET['action']) && ($_GET['action'] == 'delete_account')) {
require("config.php");
require("database.php");
$deleteAccount = $_POST['account'];
try {
$results = $db->prepare("DELETE FROM account WHERE account_id_PK = ?");
$results->bindValue(1, $deleteAccount);
$results->execute();
} catch(Exception $e) {
echo "ERROR: Data could not be removed from the database. " . $e;
exit;
}
echo($deleteAccount);
get_accounts();
};
Basically, I want to run the delete_accounts() function and at the end I would like to run the get_accounts() function, which will refresh the list of accounts on the page after the selected account has been deleted. I can't seem to call a function from within another function, no matter what I try.
Use the finally part of the try catch & remove the 'exit();'
if(isset($_GET['action']) && ($_GET['action'] == 'delete_account')) {
require("config.php");
require("database.php");
$deleteAccount = $_POST['account'];
try {
$results = $db->prepare("DELETE FROM account WHERE account_id_PK = ?");
$results->bindValue(1, $deleteAccount);
$results->execute();
} catch(Exception $e) {
echo "ERROR: Data could not be removed from the database. " . $e;
}finally{
get_accounts();
}
echo($deleteAccount);
}