PDO Mutiple Query execute and catch error - mysql

i need to execute three queries and find out which query is failed in PDO.
My config php
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password,array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::ATTR_AUTOCOMMIT, FALSE));
My class file
class myClass
{
function lastbench()
{
try {
$q1 = "select * from user";
$code_pre = $dbh->prepare($q1);
$code_pre->execute();
if(!$code_pre)
{
throw new Exception("no table called user");
}
$q2 = "select * from userprofile";
$code_pre2 = $dbh->prepare($q2);
$code_pre2->execute();
if(!$code_pre2)
{
throw new Exception("no Profile table");
}
}
catch ( Exception $e)
{
$e->getMessage();
}
}
}
Any idea how to get the specific block is not executing..

Related

DB::rollback not working in CPanel server using Laravel 8 and MySQL

I am using Laravel 8 and MySQL. Things are working as expected on my local machine, but it is not working on the server, e.g., DB::rollback is not working.
Testing Code
$condition = true;
DB::beginTransaction();
$user = $request->user();
try {
$user->code = 'ABC';
$user->save();
if ($condition) {
DB::rollback();
return response()->json(['message' => 'Update Fail'], 403);
} else {
DB::commit();
return response()->json(['message' => 'Update Success'], 200);
}
} catch (\Exception $e) {
// Rollback Transaction
DB::rollback();
return response()->json(['message' => 'Update Fail'], 403);
}

Update sales_flat_order_item table in Magento

I've a scenario in which I need to update sales_flat_order_item table after creation of order. I am using following code:
$combine_array = Array
(
[22500] => 257
[4500] => 258
)
foreach ($combine_array as $item=>$key)
{
$data = array('discount_amount'=> $item);
$orderModel = Mage::getModel('sales/order_item')->load($key)->addData($data);
try{
$orderModel->setItemId($key)->save();
}catch(Exception $e)
{
echo $e->getMessage();
}
}
But this code is not working. Kindly suggest how to update.
I tried the same code and it is updating the data perfectly. Below is my code:-
$combine_array = array(225010 => 108, 45010 => 109);
foreach ($combine_array as $item => $key) {
$data = array('discount_amount' => $item);
$orderModel = Mage::getModel('sales/order_item')->load($key)->addData($data);
try {
$orderModel->setItemId($key)->save();
} catch (Exception $e) {
echo $e->getMessage();
}
}

Cannot pass whitespace separated value to Query

My project with PHP and MySql stuck here ,
$searchfriend = "Jason";
$status = query("SELECT status FROM users.profile WHERE name = ?" , $searchfriend );
The above statement works quite well.
When I replace,
$searchfriend = "Jason R"
It's not working. What is the solution ?
I have created my own query function with PDO.
function query()
{
$sql = func_get_arg(0);
$parameters = array_slice(func_get_args(), 1);
static $handle;
if (!isset($handle))
{
try
{
$handle = new PDO("mysql:dbname=" . DATABASE . ";host=" . SERVER, USERNAME, PASSWORD);
$handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (Exception $e)
{
trigger_error($e->getMessage(), E_USER_ERROR);
exit;
}
}
$statement = $handle->prepare($sql);
if ($statement === false)
{
trigger_error($handle->errorInfo()[2], E_USER_ERROR);
exit;
}
$results = $statement->execute($parameters);
if ($results !== false)
{
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
else
{
return false;
}
}

Preparing simple query for PDO connection

I would like to prepare PDO statement and convert results to JSON in PHP. I managed to connect to database by following method:
class DB_CONNECT {
function __construct() {
$this->connect();
}
function __destruct() {
$this->close();
}
function connect() {
$root = getenv("DOCUMENT_ROOT");
require_once ($root.'/db/db_config.php');
try
{
$db = new PDO('mysql:host='.DB_SERVER.';dbname='.DB_DATABASE.';charset=utf8;port='.DB_PORT, DB_USER, DB_PASSWORD);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'OK';
return $db;
}
catch (PDOException $e)
{
print "Connection error!: " . $e->getMessage() . "<br/>";
die();
}
}
function close() {
$db = null;
}
PHP, where I make statements looks like this:
$root = getenv("DOCUMENT_ROOT");
require_once ($root.'/db/db_connect.php');
$db = new DB_CONNECT();
$statement=$db->prepare("SELECT name, surname FROM lecturer");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
When I run this PHP, I'm getting only OK message, that the connection went successfully. What's wrong with that query code?
What does your error log say? From your code, I can tell you that $db doesn't contain a PDO object, as you don't return anything in the constructor of DB_CONNECT. So $db is an object of type DB_CONNECT, not of type PDO, and thus doesn't have prepare as a method.
For a quick fix, change
$db = new DB_CONNECT();
to
$db = DB_CONNECT::connect();
and make connect static.

PDO in Classes: Call to a member function prepare() on a non-object

I try to work with classes and PDO but I don't know how to fix the Problem.
With the help of var_dump($pdo) in RunQuery (after $pdo = self::$pdo_conn;) i get the value "null". Can anybody please help me how i can get the pdo object there? Or am I completely wrong with it?
index.php
require_once ('assets/socialbar/defines.php');
require_once ('assets/socialbar/mysql/classes/class.socialbar.php');
$ajaxid = 1;
$getinfo = "";
$getinfo = Socialbar::getInfo($ajaxid);
print_r($getinfo);
class.socialbar.php
require_once(MYSQL_DIR . 'config/pdo_connection.php');
class Socialbar extends Connection {
function __construct(){
parent::__construct();
}
public function GetInfo ($ajaxid) {
$sql = "SELECT * FROM uploads WHERE id = :ajaxid ";
$inputs = array('ajaxid' => $ajaxid);
//$stmt = $this->RunQuery($sql, $inputs);
$stmt = parent::RunQuery($sql, $inputs);
$rowCount = $stmt->rowCount();
if($rowCount > 0){
return $stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
return $rowCount;
}
}
}
pdo_connection.php
abstract class Connection {
protected static $pdo_conn;
private $dsn, $user, $pass;
function __construct (){
require_once MYSQL_DIR . 'pdo_config.php';
$host = $config['db']['host'];
$dbname = $config['db']['dbname'];
$port = $config['db']['port'];
$this->user = $config['db']['user'];
$this->pass = $config['db']['pass'];
$this->dsn = "mysql:host=" . $host . ";port=" . $port . ";dbname=" . $dbname;
$this->Start();
}
protected function Start(){
try {
$this->pdo_conn = new PDO($this->dsn, $this->user, $this->pass);
} catch (PDOException $e){
print_r($e);
exit(0);
}
}
function RunQuery ($sql, $inputs=null){
// $pdo = $this->pdo_conn;
$pdo = self::$pdo_conn;
if(is_null($inputs)) {
$pdo->query($sql);
} else {
try {
$stmt = $pdo->prepare($sql);
if ($stmt) {
$stmt->execute($inputs);
} else {
print_r("Unable to prepare query");
}
} catch (PDOException $e) {
print_r($e);
exit(0);
}
}
return $stmt;
}
}
pdo_config.php
$config['db'] = array(
'host' => 'localhost',
'user' => 'root',
'pass' => '',
'dbname' => 'images',
'port' => '3306',
);
IMHO problem is your understanding or misunderstanding of static variables and functions.
So if you declare:
abstract class Connection {
protected static $pdo_conn;
That means that you can access $pdo_conn even if you had not instatntiate the object of your class and did not pass the __construct so if you have not passed __construct what value holds that property? Correct - NULL ;-)
so when you try to:
function RunQuery ($sql, $inputs=null){
// $pdo = $this->pdo_conn;
$pdo = self::$pdo_conn;
What will you get? Correct $pdo = NULL. And commented line looks as correct one.
There is no reason to declare and call pdo_conn as static property.
It could be private, protected even public but not static.
Try to instantiate the object first:
$socialBarObj = new Socialbar();
$getinfo = $socialBarObj->getInfo($ajaxid);
print_r($getinfo);