Output from a PDO statement - php

Can anyone spot where I might be going wrong with the following code?
<?php
//MySQL Database Connect
require 'config.php';
$unitFrom = "kilogram";
$unitTo = "gram";
$units = "9000";
try{
require 'config.php';
$stmt = $dbh->prepare('CALL sp_get_conversion(:in_unit_from, :in_unit_to, :in_amount, #out_amount)');
$stmt->bindParam(':in_unit_from',$unitFrom,PDO::PARAM_STR,4000);
$stmt->bindParam(':in_unit_to',$unitTo,PDO::PARAM_STR,4000);
$stmt->bindParam(':in_amount',$units,PDO::PARAM_STR,4000);
$stmt->execute();
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
$conversion = $dbh->query( "SELECT #out_amount" )->fetchColumn();
echo $conversion;
}
?>
When I run the stored procedure in phpmyadmin it works fine but nothing is echoed out when I try the code above.
Thanks

The following should be in the try block:
$conversion = $dbh->query( "SELECT #out_amount" )->fetchColumn();
echo $conversion;
You currently have it in the catch block so it will get executed only if there is an exception is generated.

Try handling your error as dictated here. It's how I've always worked with PDO issues.

Related

PDO and query troubleshoot - basic

I am converting an old php 5.6 code to 7.2 and learning how to use PDO.
I have reached a point where I got stuck and would like to learn from the community.
I created a test file structure:
db.php:
<?php
try {
$conn = new PDO($initlocation, $username, $pwdata);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "worked"; // THIS WORKS ON THE SCREEN
}
catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
?>
test.php:
<?php
include("db.php");
$user_query='SELECT * FROM `users` WHERE `email`="user1.a#gmail.com"';
echo $user_query; // I GET THE QUERY PRINTED ON THE SCREEN
echo is_object($conn); // THIS IS 1 WHICH IS GOD
echo "<br>";
echo is_object($res); // THIS IS 1 WHICH IS ODD
try{
$res = $conn->query($user_query);
}
catch (Exception $e){
echo "Query failed: " . $e->getMessage(); // NOTHING
}
echo "<br>";
echo is_object($res); // NOTHING
$data_exists = $res->fetch();
if ($data_exists==1) echo "yes"; // NOTHING
?>
I have left the testing method in the code as well and I am keen to find a better solution to find out why the query does not show anything.
The aim would be to find the email address in the DB and give me some feedback about it. Thank you in advance all the comments I will only learn form them.
Additional info:
When I run the SQL query in the DB directly it does give me the record that has the same email.
Try the following and use prepared statements like protection from SQL injections.
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);
$user = $stmt->fetch();

PDO PHP select distinct query not working for mssql

I've got a website that is pulling data from my MSSQL Server. I am using functions to build tables for reports. Here's what I've got:
function BeginTable($rowCount,$headings,$searchValue,$ReportName,$OneButton,$NewSearch)
{
try{
$StateSelectSQL = "select distinct State from pmdb.MaterialTracking where State is not null";
var_dump($StateSelectSQL);echo " What!<br>";
$getSelect = $conn->query($StateSelectSQL);
var_dump($getSelect);echo " When!<br>";
$StateSelectNames = $getSelect->fetchALL(PDO::FETCH_ASSOC);
var_dump($StateSelectNames);echo " Where!<br>";
}
catch(Exception $e)
{
echo "Something went wrong";
die(print_r($e->getMessage()));
}
I tried this too:
try{
$StateSelectSQL = "select distinct State from pmdb.MaterialTracking where State is not null";
var_dump($StateSelectSQL);echo " What!<br>";
$getSelect = $conn->prepare($StateSelectSQL);
$getSelect->execute();
//$getSelect = $conn->query($StateSelectSQL);
//var_dump($getSelect);echo " When!<br>";
$StateSelectNames = $getSelect->fetchALL(PDO::FETCH_ASSOC);
var_dump($StateSelectNames);echo " Where!<br>";
}
catch(Exception $e)
{
echo "Something went wrong<br>";
die( print_r( $e->getMessage()));
}
The second and third var_dump's never show anything and the rest of the code (not shown here) doesn't get run. If I comment out the $getSelect and $StateSelectNames lines (with the var_dump's under them) then everything else works.
Here is my DBConn.php file that is included above the Function:
$conn = new PDO("sqlsrv:server=$servername;database=$dbname", $username,$password);
//set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::SQLSRV_ATTR_QUERY_TIMEOUT, 10);
What is wrong with the line $getSelect = $conn->query($StateSelectSQL); I can't figure it out. I tried using it later in my foreach like this:
foreach($conn->query($StateSelectSQL) as $StateName)
But that doesn't work either. It again stops at this line and doesn't go any further. The only thing I can think of is that my SQL is messed up, but when I run it in SSMS it works fine!
What's going on?
Try preparing and executing your SQL before using fetchAll. Also consider enabling exception mode if you haven't already and wrapping your statement in a try catch - this should flag any issues (e.g. your applications database user not having permission to access the schema, or syntax error etc)
Exceptions:
See this stack overflow post for info about how to enable
And for your code:
try {
$sql = "
SELECT DISTINCT State
FROM pmdb.MaterialTracking
WHERE State IS NOT NULL
";
$sth = $conn->prepare($sql);
$sth->execute();
$rowset = $sth->fetchAll(PDO::FETCH_ASSOC);
print_r($rowset);
} catch PDOException($err) {
echo "Something went wrong".
echo $err;
}
I have figured it out after pulling my hair out all day! I had to include my DBConn.php inside the function. After this it worked. I don't know why that mattered since it is included at the beginning of the file. If there is anyone who can explain why that is i'd be grateful!
It now looks like this:
function BeginTable($rowCount,$headings,$searchValue,$ReportName,$OneButton,$NewSearch)
{
try{
include("DBConn.php");
$SelectSQL = "select distinct State from pmdb.MaterialTracking where State is not null order by State";
$getSelect = $conn->prepare($SelectSQL);
$getSelect->execute();
$StateSelectNames = $getSelect->fetchALL(PDO::FETCH_ASSOC);
}
catch(Exception $e)
{
echo "Something went wrong<br>";
die( print_r( $e->getMessage()));
}

Cannot update MySQL using PDO::PARAM_LOB on a serialized array.No error is being thrown

I am running a test to serialize an array using PHP, in order to update my database I use the PDO extension. I have tried changing the code a bit, but there is no error to be catched by the try block. I have other functions where I successfully updated other tables, the only diferense here is the PDO::PARAM_LOB line. Any help is greatly appreciated.
<?php
require("database.php");
try {
$test = array('15525');
array_push($test, '12345');
var_dump($test);
$stest = serialize($test);
var_dump($stest) ;
$dapartmentToUpdate = 3;
$result = $db->prepare("
UPDATE departments_employees
SET employee_id = ?
WHERE department_id = ?
");
$result ->bindParam(1,$stest,PDO::PARAM_LOB);
$result ->bindParam(2,$departmentToUpdate,PDO::PARAM_INT);
$result -> execute();
} catch (Exception $e) {
echo "Could not write to database for some odd reason";
exit;
}
?>
I must add that by taking the query directly to SQL makes it run just fine, so I must be missing something. The statement on SQL looks like
UPDATE departments_employees
SET employee_id = 'a:2:{i:0;s:5:"15525";i:1;s:5:"12345";}'
WHERE department_id = 3
config.php are just some environment constants, user, password and some other private stuff, database.php looks like this:
<?php
require_once ('config.php');
try {
$db = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME .";port=" . DB_PORT,DB_USER,DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch (Exception $e) {
echo "Could not connect to the database.";
exit;
}

PDO connection try catch include

I'm new to PDO and I wanna do it right from the beginning - I'm going to replace my old mysql_ functions on a site.
Have I got it right?:
Should I put the connection code in a try/catch and save it to a file, and include it on top of the page. Then put the queries in try/catch as well.
Or:
Should I put the connection code in a file and include it in the in the top of the try/catch statement above the query?
ver1:
include('pdo.php'); // try/catch in file
try {
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
while($row = $stmt->fetch()) {
print_r($row);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
ver2:
try {
include('pdo.php'); // no try/catch in file
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
while($row = $stmt->fetch()) {
print_r($row);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Or should I put the try/catch in both places?
You should do both and even more :
Set an error handler that displays a message to the user and stops the PHP (see set_error_handler)
When you initiate the connexion, add a try/catch and throw an error if you catch an exception. Your website won't run without database connection i guess.
Do a try/catch around your queries to recover gracefully from error (when you can)

Why is my PDO not working?

I am starting to use PDO and I successfully connected to MySQL using PDO. However, when I try to SELECT stuff from my DB, nothing happens. Nothing is echoed. (even though I have records in that table, and the column username exists) No error in my PHP log.
I am using MAMP and all PDO components seem to be working in phpinfo() (since I was able to connect to db in the first place)
Please let me know what could have gone wrong. Thanks a lot
<?php
try
{
$connection = new PDO('mysql:host=localhost;dbname:my_db','my_username',
'xxxxxxx');
$stmt=$connection->prepare("SELECT * FROM users");
$stmt->execute();
while ($row=$stmt->fetch(PDO::FETCH_OBJ)){
echo $row->username;
}
}
catch(Exception $e)
{
echo "There was an error connecting to the database";
}
?>
You need to tell PDO that you want it to throw exceptions:
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Following your comment below, it is apparent that your DSN is incorrect. It should be:
$connection = new PDO('mysql:host=localhost;dbname=my_db','my_username','xxxxxxx');
Note that the syntax is dbname= rather than dbname: (which you had originally).
First, get your query out of your PDO connection segment...
<?php
try
{
$connection = new PDO('mysql:host=localhost;dbname:my_db','my_username',
'xxxxxxx');
}
catch(Exception $e)
{
echo "There was an error connecting to the database";
}
?>
Then, do it.
<?php
$SQL = 'SELECT * FROM users';
foreach($connection->query($SQL) as $row){
print $row['username'] . "\n".'<br />';
}
?>
Why not ask PHP?
catch(Exception $e)
{
die($e);
}
Looks like your either don't have data in that table or have an error:
Try to add this code after $stmt->execute();:
$arr = $sth->errorInfo();
print_r($arr);

Categories