I am new to pdo as I am just moving into it from the traditional method of doing queries. Below is what I have wrote and it works. My concern now is that if there any error in any of the query either the select,insert or update they are all capture by that one catch but then I cant pin point exactly to the error. So will multiple try and catch be the right direction ?
try {
$dsn = 'mysql:dbname='.dbDatabase.';host='.dbHost;
$link = new PDO($dsn, dbUser, dbPassword );
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
$link->beginTransaction();
$rollBackStatus="False";
try
{
$selectQuery1 ="Select ......";
$selectQueryResult1 = $link->prepare($selectQuery1);
$selectQueryResult1->bindParam(':uname', $userName);
$selectQueryResult1->execute();
$n1=$selectQueryResult1->rowCount();
//echo "TEST : ".$n1;
if($n1==1)
{
$row1 = $selectQueryResult1->fetch();
$userID=$row1['userID'];
if($row1['up']==$up){
$insertQuery1 ="Insert .......... ".
$insertQueryResult1 = $link->prepare($insertQuery1);
$insertQueryResult1->bindParam(':uID', $userID);
$insertQueryResult1->bindParam(':uIP', $userIP);
if($insertQueryResult1->execute()){
}
else{
$rollBackStatus="True";
$link->rollback();
}
$updateQuery1 ="Update ........ ";
$updateQueryResult1 = $link->prepare($updateQuery1);
$updateQueryResult1->bindParam(':uID', $userID);
if($updateQueryResult1->execute()){
}
else{
$rollBackStatus="True";
$link->rollback();
}
}
}
catch(PDOException $pe)
{
$rollBackStatus="True";
die("Error in selectQuery1 :" . $pe->getMessage());
$link->rollback();
}
if($rollBackStatus=="False"){
$link->commit();
$link=null;
if($headerSent!="")
{
header($headerSent);
}
}
You can check any error after execute query with following method.
$selectQueryResult1->execute();
$arr = $selectQueryResult1->errorInfo();
print_r($arr);
Related
Please help fix "SQLSTATE[HY000]: General error:" in the following PHP script. Also, refer to the MySQL script in case.
<?php
# MySQL
$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'procdb';
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected to MySQL Server successfully." . "\n";
$sql = "CALL prepend('abcdefg', #inOutParam);";
$stmt = $pdo->query($sql);
do {
$rows = $stmt->fetchAll(PDO::FETCH_NUM);
if ($rows) {
foreach($rows as $row) {
print($row[0] . "\n");
}
}
} while ($stmt->nextRowset());
} catch (PDOException $e) {
#die("Could not connect to the database $dbname :" . $e->getMessage());
$error = $e->getMessage();
echo $error . "\n";
} catch (Exception $e) {
$error = $e->getMessage();
echo $error . "\n";
} finally {
$pdo = null;
echo "Connection closed." . "\n";
}
?>
Here's the MySQL Script:
DROP DATABASE IF EXISTS procdb;
DELIMITER $$
CREATE DATABASE procdb;$$
DELIMITER ;
USE procdb;
DROP PROCEDURE IF EXISTS prepend;
DELIMITER $$
CREATE PROCEDURE prepend
(
IN inParam VARCHAR(255),
INOUT inOutParam INT
)
BEGIN
DECLARE z INT;
SET z = inOutParam + 1;
SET inOutParam = z;
SELECT inParam;
SELECT CONCAT('zyxw', inParam);
END;$$
DELIMITER ;
USE procdb;
CALL prepend('abcdefg', #inOutParam);
/*
# Output
// (FieldName1 and its value)
inParam
'abcdefg'
// (FieldName2 and its value)
CONCAT('zyxw', inParam)
'zyxwabcdefg'
*/
What is the cause of the error? Note that adding "$stmt->close();" or "$stmt->closeCursor();" did not help.
Please help.
Thanks
Try this, line
$rows = $stmt->fetchAll(PDO::FETCH_NUM);
Outside While loop
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected to MySQL Server successfully." . "\n";
$sql = "CALL prepend('abcdefg', #inOutParam);";
$stmt = $pdo->query($sql);
$rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
foreach ($rows as $row) {
foreach ($row as $col) {
print $col . "\n";
}
}
$stmt->nextRowset();
$rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
foreach ($rows as $row) {
foreach ($row as $col) {
print $col . "\n";
}
}
} catch (PDOException $e) {
#die("Could not connect to the database $dbname :" . $e->getMessage());
$error = $e->getMessage();
echo $error . "\n";
} catch (Exception $e) {
$error = $e->getMessage();
echo $error . "\n";
} finally {
$pdo = null;
echo "Connection closed." . "\n";
}
I have made a code using PDO to read a table from a database.
I try to echo my result but I get a blank page without error.
My Code Is:
<?php
include 'config.php';
id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->fetchColumn() != 0)
{
foreach ( $result->fetchAll(PDO::FETCH_BOTH) as $row ) {
$Data1 = $row['Data1'];
$Data2 = $row['Data2'];
echo $Data2;
}
}
?>
But the echo is empty without any error.
What I am doing wrong?
Thank you All!
Few things to change:
dont forget $
if your going to catch the error, catch the whole pdo code
You can use rowCount() to count the rows
echo something if the record count is 0
include 'config.php';
$id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->rowCount() != 0)
{
$row = $result->fetch(PDO::FETCH_BOTH);
echo $row['Data1'];
echo $row['Data2'];
}else{
echo 'no row found';
}
}catch(PDOException $e){
echo "error " . $e->getMessage();
}
Also use prepared statements for example:
$result = $conn->prepare("SELECT * FROM mytable WHERE id=:id");
$result->execute(array(':id'=>$id));
I'm assuming there's only one record with the id "264540733647332".
The issue is that $result->fetchColumn() call reads first row in the result set and then advances to the next result. Since there's only one of the results, the subsequent call to $result->fetchAll() returns nothing, hence no data displayed.
To fix this replace fetchColumn with rowCount:
<?php
include 'config.php';
id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->fetchColumn() != 0)
{
foreach ( $result->fetchAll(PDO::FETCH_BOTH) as $row ) {
$Data1 = $row['Data1'];
$Data2 = $row['Data2'];
echo $Data2;
}
}
?>
i want to get the current max size of my DB. I have found the statements an checked it out. It works fine in VS2012 SQL Explorer. But when im using php im geting no data.
This is my function:
function getLoad() {
$conn = connect();
$string = 'DATABASEPROPERTYEX ( 'database' , 'MaxSizeInBytes' )';
$stmt = $conn->query($string);
return $stmt->fetchAll(PDO::FETCH_NUM);
}
The problem is that i get an error in fetching the $stmt. Error is:
can not fetchAll(11)
This code will print the database edition and max size in GB:
<?php
function get_database_properties($server, $database, $username, $password) {
try {
$conn = new PDO ("sqlsrv:server=tcp:{$server}.database.windows.net,1433; Database={$database}", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(constant('PDO::SQLSRV_ATTR_DIRECT_QUERY'), true);
$query = "SELECT CONVERT(NVARCHAR(128), DATABASEPROPERTYEX ('{$database}', 'Edition')) as 'Edition', " .
"CONVERT(DECIMAL,DATABASEPROPERTYEX ('{$database}', 'MaxSizeInBytes'))/1024/1024/1024 AS 'MaxSizeInGB'";
$stmt = $conn->query($query);
$row = $stmt->fetch();
$conn = null;
return $row;
}
catch (Exception $e) {
die(print_r($e));
}
}
$db_properties = get_database_properties("yourserver", "yourdatabase", "youruser", "yourpassword");
print("Edition={$db_properties['Edition']} MaxSizeInGB={$db_properties['MaxSizeInGB']}\n");
?>
I am crossing over to PDO and want to, simply put, return a single value from a table (and I feel really stupid for not getting it right). I am not getting any errors, but also no values, where there should be :)
try {
$sql = "SELECT `column_name` FROM `table` ORDER BY `id` DESC LIMIT 1";
$query = $this->handler->query($sql);
$result = $query->fetchColumn();
print_r($result);
}
catch(PDOException $e) {
return false;
}
return true;
Print the error message:
catch(PDOException $e) {
print_r($e->getMessage());
return false;
}
As shown this would work, if you have correctly connected to the database.
Check that your object is successfully connecting to the database, and that you have the correct column name and table name.
A snippet from one of my DB classes:
/**********************************************************************
* Try to connect to mySQL database
*/
public function connect($dbuser, $dbpassword, $dbhost ,$dbname)
{
try {
$this->dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpassword);
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return true;
} catch (PDOException $e) {
$this->setError($e->getMessage());
}
}
I'm just trying to do a simple insert:
$dbh = new PDO("mysql:host=" . WEBSITE_SERVER . "; dbname=fluenz_website", WEBSITE_LOGIN, WEBSITE_PW);
$query = $dbh->prepare("INSERT INTO crm_orders (crm_id, order_num, channel) VALUES (:crm_id, :order_num, :channel)");
if($query->execute(array(':crm_id'=>$crm_id, ':order_num'=>$order_num, ':channel'=>$channel))){
echo 'PDO SUCCESS';
}else{
echo 'PDO FAILURE';
}
But it's failing. Can someone tell me why? And even better, is it possible to get a more helpful return value from the execute() method than simply true or false?
But it's failing. Can someone tell me why?
Hard to say. Should those values be quoted? The error thrown by MySQL would be useful to diagnose the problem. Which leads me to...
And even better, is it possible to get a more helpful return value from the execute() method than simply true or false?
So long as PDO is set up to throw exceptions on errors...
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
...wrap it in a try/catch block and examine the exception thrown.
try {
$query->execute(...);
} catch (PDOException $e) {
echo $e->getMessage();
}
By default, PDO's error mode is ERRMODE_SILENT so it won't complain if anything goes wrong. To see real errors, either set it to ERRMODE_WARNING or ERRMODE_EXCEPTION to throw exceptions. http://php.net/manual/en/pdo.error-handling.php
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
try {
$query = $dbh->prepare("INSERT INTO crm_orders (crm_id, order_num, channel) VALUES (:crm_id, :order_num, :channel)");
$query->execute(array(':crm_id'=>$crm_id, ':order_num'=>$order_num, ':channel'=>$channel))
}
catch (PDOException $e) {
echo "Query failed: " $e->getMessage();
}
With something like this you will be able to get the error.
$dbh = new PDO("mysql:host=" . WEBSITE_SERVER . "; dbname=fluenz_website", WEBSITE_LOGIN, WEBSITE_PW);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $dbh->prepare("INSERT INTO crm_orders (crm_id, order_num, channel) VALUES (:crm_id, :order_num, :channel)");
try {
if($query->execute(array(':crm_id'=>$crm_id, ':order_num'=>$order_num, ':channel'=>$channel))){
echo 'PDO SUCCESS';
}else{
echo 'PDO FAILURE';
}
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}