php pdo cant excute alter statment - php

public function
updateOrderno($neworderid){
$updateData = array($neworderid);
$stmt = $this->pdo->prepare("ALTER TABLE `order` AUTO_INCREMENT=?");
try {
if ($stmt->execute($updateData)){
return true;
}else{
return false;
}
} catch (PDOException $e){
return false;
}
}
Here is my code , I call this with $post data and then
it keep retruning false when I execute the alter statement any help?

Related

Check Function without execute it

i'm training SOLID/Architectures and trying to make an INSERT on my code, but its insert four times on DB. There's any error on my logic? I'm following Repositories/Service Pattern.
i think my service is executing two times, but i cant find the reason.
Repositorie Code
public function inserirEstoque($dadosPost)
{
if (empty($dadosPost)) {
return false;
}
$pdo = $this->dbConnection->conectar();
$sql = $pdo->prepare('INSERT INTO estoque (nomeProduto, descriptions, price, quantity)
VALUES (:nome, :descriptions, :price, :quantity)');
$sql->bindValue(':nome', $dadosPost['nomeProduto']);
$sql->bindValue(':descriptions', $dadosPost['descriptions']);
$sql->bindValue(':price', $dadosPost['price']);
$sql->bindValue(':quantity', $dadosPost['quantity']);
$res = $sql->execute();
if($res == false)
{
return false;
}
return $res;
}
Service
public function insertEstoque()
{
$db = new MySQL();
$insert = new EstoqueRepositories($db);
if(!empty($insert->inserirEstoque($_POST))){
return $insert->inserirEstoque($_POST);
} else {
return false;
}
}
Controller
public function insert()
{
$insert = new EstoqueService();
$insert->insertEstoque();
header('Location: ../../index.php');
}
It's executing twice because of this
if(!empty($insert->inserirEstoque($_POST))){
return $insert->inserirEstoque($_POST);
} else {
return false;
}
if you wanna check if the POST data is empty just remove where it inserts the data then it should just insert it 1 time
if(!empty($_POST["whatevername"])){
return $insert->inserirEstoque($_POST);
} else {
return false;
}
As an addition to Reed's answer, if you just want to check the result of a function call before carrying on, assign the result to a variable and use that variable.
$res = $insert->inserirEstoque($_POST)
if(!empty($res)){
return $res;
} else {
return false;
}

There is no active transaction'

having problems with this function wipe_data
this wipe_data function my DB cleanup and admin data inserting
but this function shows error:
There is no active transaction
This is my code:
function wipe_data() {
DB::beginTransaction();
$adminData = User::where('role', 'admin')->first();
try {
User::truncate();
User_details::truncate();
User_kyc::truncate();
Token::truncate();`enter code here`
$auto_id = date('Y');
DB::statement("ALTER TABLE ls_users AUTO_INCREMENT = $auto_id");
$admin = new User();
$admin->username = $adminData->username;
$admin->email = $adminData->email;
$admin->password = $adminData->password;
$admin->role = $adminData->role;
$admin->save();
$user_id = User::where('role', 'admin')->value('id');
DB::commit();
} catch (\Exception $ex) {
DB::rollback();
return false;
}
return true;
}
There are some statements that caused implicit commit, including the ALTER TABLE statement you are using.
Therefore, your statement has already been committed before you called DB::commit(), hence an error occurred.

How can I use db transaction in laravel?

I try this :
public function destroy($id)
{
DB::beginTransaction();
try {
$product = $this->product_repository->find($id);
$result = $product->categories()->detach();
if($result) {
list($status,$instance) = $this->product_repository->delete($id);
}
DB::commit();
return ['status'=>true,'data'=>$status];
} catch (\Exception $e) {
DB::rollback();
return ['status'=>false, 'message'=>$e->getMessage()];
}
}
If the code executed, $this->product_repository->delete($id) not work / not success delete.
But this : $product->categories()->detach();, it works / success deleted.
How to if delete product failed, delete category also failed?
You can't add return statement inside transaction that halts entire process and DB::rollback() is executed.
To switch the return, You can define a boolean variable and make false while you catch exception.
Like this:
public function destroy($id)
{
$success = true;
DB::beginTransaction();
try{
// Your Code
$product = $this->product_repository->find($id);
$result = $product->categories()->detach();
if($result) {
list($status,$instance) = $this->product_repository->delete($id);
}
DB::commit();
}catch(\Exception $e){
DB::rollback();
$success = false;
}
if($success){
// Return data for successful delete
}
else{
// Return data for unsuccessful delete
}
}
Hope you understand.
You can use it like this:
$returnResult = [];
DB::beginTransaction();
try {
...
DB::commit();
$returnResult['status'] = true;
$returnResult['data'] = $status;
} catch (...) {
...
DB::rollback();
$returnResult['status'] = true;
$returnResult['message'] = $e->getMessage();
}
return $returnResult;

PDO PHP Update Script not working

I've searched on stackoverflow and other sources but I cant seem to find the issue that is preventing my PHP script from working.
Look at the echo_sql. It produces a healthy update statement which when run updates the database with no problem. Here is a sample:
update waste set waste_name=1 where id =82;
However, when the script is run, it does not apply changes to the database. Here is the script:
if ($_SERVER['REQUEST_METHOD'] == "POST") {
try {
$waste_id = $_POST['waste_id'];
$sql = new db;
$sql->beginTransaction();
$waste_name = $_POST['waste_name'];
$sql->query("update waste set waste_name=:waste_name where id =:waste_id;");
$echo_sql = "update waste set waste_name=$waste_name where id =$waste_id;";
echo $echo_sql;
$sql->bind(':waste_name', $waste_name);
$sql->execute();
$sql->endTransaction();
} catch (Exception $e) {
$sql->rollBack();
echo "Failed: " . $e->getMessage();
}
}
Additional details:
errorCode() = 00000
DB Class:
class db
{
private $stmt;
private $dbc;
public function __construct()
{
$u = "root";
$p = "";
try {
$this->dbc = new PDO('mysql:host=127.0.0.1;dbname=wimsdb', $u, $p);
$this->dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
$e->getMessage();
}
}
public function bind($param, $value, $type = NULL)
{
$this->stmt->bindParam($param, $value, $type);
}
public function beginTransaction()
{
return $this->dbc->beginTransaction();
}
public function rollBack()
{
return $this->dbc->rollBack();
}
public function endTransaction()
{
return $this->dbc->commit();
}
public function cancelTransaction()
{
return $this->dbc->rollBack();
}
public function execute()
{
try {
return $this->stmt->execute();
} catch (PDOException $e) {
return $e->errorInfo;
}
}
public function errorCode()
{
return $this->stmt->errorCode();
}
public function query($query)
{
$this->stmt = $this->dbc->prepare($query);
}
}
Please offer your suggestions on how this could be resolved.
You need to bind the :waste_id too:
$waste_id = $_POST['waste_id'];
$sql = new db;
$sql->beginTransaction();
$waste_name = $_POST['waste_name'];
$sql->query("update waste set waste_name=:waste_name where id =:waste_id;");
$sql->bind(':waste_name', $waste_name);
$sql->bind(':waste_id', $waste_id);
Any time you have an issue like this your error checking should return a meaningful message letting you know where the error is and likely what the error is. You should be able to check your error logs for details and/or output them to your screen during testing.
Add waste_id. To avoid missing parameters, I like putting the parameteers into the execute method. The bind method could be defined anywhere in the code so I had to look through your code and make sure waste_id binding wasn't defined somewhere else. When it's in the execute method, you can quickly see all parameters being defined there...it's also a tad more concise...but both have their uses.
if ($_SERVER['REQUEST_METHOD'] == "POST") {
try {
$waste_id = $_POST['waste_id'];
$sql = new db;
$sql->beginTransaction();
$waste_name = $_POST['waste_name'];
$sql->query("update waste set waste_name=:waste_name where id =:waste_id;");
$echo_sql = "update waste set waste_name=$waste_name where id =$waste_id;";
echo $echo_sql;
//just because I like this syntax for being concise and clear :)
$sql->execute(array(
'waste_id' => $waste_id,
'waste_name' => $waste_name
));
$sql->endTransaction();
} catch (Exception $e) {
$sql->rollBack();
echo "Failed: " . $e->getMessage();
}

PDO update query returns false even though it updates fine

I am trying to figure out why a query returns false even though it updates the database just fine.
I have the following:
$results = $User->UpdateUser($UpdateAdminId,$UpdateFirstName);
which calls the following method:
function UpdateUser($AdminId,$FirstName)
{
return $this->sdb->dbUpdate("administrators",array("FirstName"=>$FirstName),array("AdminId"=>$AdminId));
}
I can see that the database is updated with the correct info. And if I change the query to be a simple select, it returns true.
But why is this update returning false when it updates?
Here is the update method:
function dbUpdate($table_name,$update_array,$update_condition_array=array())
{
$colums_val="";
$where_condition="";
$this->values=array();
$and_val="";
foreach($update_array as $col => $val)
{
$colums_val=$colums_val."`".trim($col)."`=?,";
$this->values[]=$val;
}
$colums_val=rtrim($colums_val,",");
foreach($update_condition_array as $col => $val)
{
$where_condition=$where_condition.$and_val." `".trim($col)."`=? ";
$this->values[]=$val;
$and_val=$this->and_or_condition;
}
if($where_condition)
$where_condition=" WHERE ".rtrim($where_condition,",");
/* Add Order By condition */
$where_condition=$this->getOrderbyCondition($where_condition);
/* Add Limit condition */
$where_condition=$this->getLimitCondition($where_condition);
try
{
if($this->rollbackTransaction&&$this->beginTransaction)
return;
if($this->beginTransaction==true)
{
if($this->dbh==NULL)
{
$this->dbh = new PDO("mysql:host=$this->host_name;dbname=$this->db_name", $this->user_name, $this->password);
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->dbh->beginTransaction();
}
}
else
{
$this->dbh = new PDO("mysql:host=$this->host_name;dbname=$this->db_name", $this->user_name, $this->password);
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
$this->message_info="Connected to database";
if($this->charset)
$this->dbh->exec("set names ".$this->charset);
$this->query="UPDATE $table_name SET $colums_val $where_condition";
$stmt = $this->dbh->prepare($this->query);
$stmt->execute($this->values);
$this->rows_affected=$stmt->rowCount();
if($this->beginTransaction==false)
$this->dbh = NULL;
if($this->resetAllSettings==true)
$this->resetSettings();
}
catch(PDOException $e)
{
if($this->beginTransaction==true)
{
$this->rollbackTransaction=true;
$this->dbh->rollBack();
}
$this->error_info=$e->getMessage();
}
}

Categories