laravel decimal increment or + getting weird result - php

i'm trying to do when a user deposit, there is a deposit record, once admin approve, there is a transaction inserted, deposit record status update and increase user credit, but all the amount field is store as decimal(12,2)
here come the weird thing
user_credit = 1001.00
deposit_amount = 500.00
when user_credit + deposit_amount, the results is 501, what the ????
here is the transaction model approveDeposit() method
/**
*
* #param int $depositId
* #return boolean|array
*/
public function addDepositTransaction($depositId) {
$dp = null;
$user = null;
$t = null;
\DB::beginTransaction();
$errors = array();
//Select the deposit id
try {
$dp = new \Deposit();
$dp = $dp::find($depositId);
if (!$dp || !$dp->exists()) {
$errors[] = 'Deposit Id Not Found.';
\DB::rollback();
return $errors;
} else {
// if ($dp->status != 0) {
// $errors[] = 'This Deposit is already ' . $dp->getStatusText();
// \DB::rollback();
// return $errors;
// }
}
} catch(\Exception $ex) {
$errors[] = $ex->getMessage();
\DB::rollback();
return $errors;
}
//Select the user which taken from deposit
try {
$user = \User::find($dp->user_id);
} catch (\Exception $ex) {
$errors[] = $ex->getMessage();
\DB::rollback();
return $errors;
}
//Insert new transaction
try {
$t = new \Transactions();
$t->user_id = $dp->user_id;
$t->action = \Transactions::ACTION_DEPOSIT;
$t->credit = \Transactions::CREDIT_POINTS;
$t->credit_tag = \Transactions::CREDIT_TAG_POINTS;
$t->amount = $dp->deposit_amount;
$t->description_tag = 'deposit';
$t->description = 'User Deposit Accepted';
$t->related_one = $dp->id;
if ($t->save()) {
} else {
$errors = $t->errors()->all();
\DB::rollback();
return $errors;
}
} catch (\Exception $ex) {
$errors[] = $ex->getMessage();
\DB::rollback();
return $errors;
}
//Update the deposit status to 1(complete)
try {
$dp->status = 1;
if ($dp->save(\Deposit::getStatusRules())) {
} else {
$errors = $dp->errors()->all();
\DB::rollback();
return $errors;
}
} catch (\Exception $ex) {
$errors[] = $ex->getMessage();
\DB::rollback();
return $errors;
}
//Finally, update the user credits
try {
// $user->increment('points', (int)$dp->deposit_amount);
// (float)$user->points = (float)($user->points) + (float)($dp->deposit_amount);
dd($user->points + $dp->deposit_amount);
if ($user->save(\User::getPointsRules())) {
} else {
$errors = $user->errors()->all();
\DB::rollback();
return $errors;
}
} catch (\Exception $ex) {
$errors[] = $ex->getMessage();
\DB::rollback();
return $errors;
}
\DB::commit();
return true;
}
i try setting the variable type to both (int) (float) (string), also the result is wrong, i also tried the $model->increment('field', number), but the result become 2.00

Related

PDOexception :There is no active transaction

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.

Undefined index:session LOOP NOT WORKING php, pdo oop

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 ', &nbsp '.$getRow['username'].' &nbsp ';
}
} 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 ', &nbsp ' . $r2['username'] . ' &nbsp ';
}
}
}
}
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 ', &nbsp '.$getRow['username'].' &nbsp ';
}
} catch (PDOException $e) {
die('Error :'. $e->getMessage());
}
$total = $gr + $gr2;
} //end

Yii2 How to Execute two Statement using PDO? or other way

I want to CREATE DATABASE and in same database want to import data. But what i tried since getting no luck.
Action
public function actionRestore($id = null)
{
$list = $this->getFileList();
$file = $list[$id];
if(isset($file))
{
$transaction = Yii::$app->db->beginTransaction();
try{
$sql = 'DROP DATABASE IF EXISTS '.$this->getDbName().';CREATE DATABASE '.$this->getDbName();
$sqlFile = $this->path . basename($file);
Yii::$app->db->pdo->prepare($sql,$this->execSqlFile($sqlFile));
if(Yii::$app->db->pdo->exec())
{
$transaction->commit();
Yii::$app->session->setFlash('success', 'Backup Restored Successfully');
return $this->redirect(['index']);
}
$transaction->rollback();
}
catch(\Exception $e) {
$transaction->rollBack();
Yii::$app->session->setFlash('error', "Backup not Restored. <br>".$e->getMessage());
return $this->redirect(['index']);
}
}
}
I am not sure about execSqlFile() method :
public function execSqlFile($sqlFile)
{
$flag = false;
if (file_exists($sqlFile))
{
$sqlArray = file_get_contents($sqlFile);
$cmd = Yii::$app->db->createCommand($sqlArray);
try {
$cmd->execute();
$flag = true;
}
catch(Exception $e)
{
$flag = false;
throw new \yii\db\Exception($e->getMessage());
}
}
return $flag;
}
1) getDbName() gets database name.
1) getFileList() gets file to be executed in execSqlFile().
I am not getting any error or message of success or failure.
I want to combine both into one preparedStatement, but don't know what i am missing here.
I found the solution i need to use shell_exec:
public function execSqlFile($sqlFile)
{
if (file_exists($sqlFile))
{
$database=array();
$db=Yii::$app->db;
$database=explode(";",$db->dsn);
$dbname=explode("=",$database['1']);
$output = shell_exec('mysql -u '.$db->username.' -p'.$db->password.' '. $dbname['1'] .'< '.$sqlFile);
}
return $output;
}
Don't use PDO object directly. You loose abstractions. I would just execute two commands like this:
public function actionRestore($id = null)
{
if($id !== null && $this->restoreDatabase($id)) {
Yii::$app->session->setFlash('success', 'Backup Restored Successfully');
} else {
Yii::$app->session->setFlash('error', "Backup not Restored. <br>" . $e->getMessage());
}
return $this->redirect(['index']);
}
private function restoreDatabase($id)
{
$list = $this->getFileList();
$file = $list[$id];
if (isset($file)) {
$transaction = Yii::$app->db->beginTransaction();
try {
Yii::$app->db->createCommand('DROP DATABASE IF EXISTS ' . $this->getDbName() . '; CREATE DATABASE ' . $this->getDbName())->execute();
$sqlFile = $this->path . basename($file);
$this->execSqlFile($sqlFile);
$transaction->commit();
return true;
} catch (\Exception $e) {
$transaction->rollBack();
Yii::error($e->getMessage()); //Probably throw exception?
return false;
}
}
}
private function execSqlFile($sqlFile)
{
if (!file_exists($sqlFile)) {
return false;
}
$sql = file_get_contents($sqlFile);
$command = Yii::$app->db->createCommand($sql);
try {
$command->execute();
return true;
} catch (Exception $e) {
throw new \yii\db\Exception($e->getMessage());
}
}

Mysql adds new row instead of updating it

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.

How to correctly return and display string value if function does not return true?

I am attempting to write a method that checks whether a user exists and also does some validation.
This is the code so far:
public function checkUsername(){
if((strlen($_POST['register-username']) > 2) && (strlen($_POST['register-username']) < 16)){
$stmt = $this->dbh->prepare("SELECT username FROM adrenaline_junkies_uk_users WHERE username = ?");
$stmt->bindParam(1, $this->post_data['register_username'], PDO::PARAM_STR);
$stmt->execute();
if($stmt->rowCount() != 0){
return TRUE;
}else{
return $this->error .= '<span style="color:red;">Username already exists.</span>';
}
}else{
return $this->error .= '<span style="color:red;">Username must be between 3 and 15 characters.</span>';
}
}
This is how Im attempting to call it:
if( isset($_POST['register-submit'])){
$error = '';
$register = new register($_POST, $dbh);
if(!$error .= $register->checkUsername()){
//continue
}else{
$error .= $register->checkUsername();
}
}
To test it I don't enter anything in the input field to get the first error to be returned and echo it out correctly on the webpage. But nothing is displaying.
Is this the correct way of doing this? Sorry I'm not very familiar with using methods in classes. I assume I'm doing something wrong in the initial if statement in the calling program and should I be running that method twice like I do?
Use Exceptions. Like:
public function checkUsername(){
if((strlen($_POST['register-username']) > 2) && (strlen($_POST['register-username']) < 16)){
$stmt = $this->dbh->prepare("SELECT username FROM adrenaline_junkies_uk_users WHERE username = ?");
$stmt->bindParam(1, $this->post_data['register_username'], PDO::PARAM_STR);
$stmt->execute();
if($stmt->rowCount() != 0){
return TRUE;
}else{
throw new Exception("Username already exists.");
}
}else{
throw new Exception("Username must be between 3 and 15 characters.");
}
}
and
if( isset($_POST['register-submit'])){
$error = '';
$register = new register($_POST, $dbh);
try {
if($register->checkUsername()){
//continue
}
} catch ($e) {
$error .= '<span style="color:red;">' . $e->getMessage() . '</span>';
}
}
You can do subclassing like:
class UsernameException extends Exception {}
try {
throw new UsernameException("Your username is too awesome");
} catch (UsernameException $e) {
exit($e->getMessage());
} catch (SomeOtherException $e) {
exit("500");
} catch (Exception $e) {
exit("que?");
}

Categories