"The connection was reset" in PHP-PDO - php

I am trying to access SQL Window Server from Linux (ubuntu 12.04) server by PHP PDO extension, but showing me "The connection was reset" from the browser.
Code is -
try {
self::$instance = new PDO('odbc:Driver=FreeTDS; Server=192.168.0.21; Port=1433; Database=MSSQLTips; UID=XXXX; PWD=XXXXX');
self::$instance->setAttribute(PDO::ATTR_PERSISTENT, true);
self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $exception) {
trigger_error($error->getMessage());
}
And the access code is
$query = 'SELECT * FROM tblEmployee where Employee_Id = ?';
$sth = $this->db->prepare($query);
$sth->execute(array('1557'));
$result = $sth->fetch();
echo "<pre>"; print_r($result); die;

This is a known bug in PHP. Refer to bug report 64483 for more information.
As an alternative to pdo_odbc you can use the pdo_dblib driver to access a MS SQL Server from PHP on Linux. Refer to the PHP documentation on pdo_dblib
I have adjusted your code to use dblib.
try {
self::$instance = new PDO ("dblib:host=192.168.0.21:1433;dbname=MSSQLTips","XXXX","XXXXX");
self::$instance->setAttribute(PDO::ATTR_PERSISTENT, true);
self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $ex) {
$msg = htmlentities($ex->getMessage());
trigger_error($msg);
}
And then:
$query = 'SELECT * FROM tblEmployee where Employee_Id = ?';
$sth = $this->db->prepare($query);
$sth->bindValue(1, "1557", PDO::PARAM_INT);
$sth->execute();
$result = $sth->fetchAll();
if($result === false) {
throw new Exception("Unable to fetch result.");
}
try {
echo "<pre>";
print_r($result);
echo "</pre>";
} catch (Exception $ex) {
$msg = htmlentities($ex->getMessage());
trigger_error($msg,E_WARNING);
}

Related

How to properly select from MSSQL using PHP PDO with query, containing cyrillic symbols?

I'am trying to perform simple SELECT query from PHP PDO to MSSQL database. While query contains cyrillic symbols in WHERE condition, result is empty (if not contains, result return successfully). What can I do to correct query?
putenv('ODBCSYSINI=/etc/');
putenv('ODBCINI=/etc/odbc.ini');
$configODBC = config('database.odbc');
try {
$this->pdo = new PDO('odbc:'. $configODBC['default']['source'], $configODBC['default']['username'], $configODBC['default']['password']);
} catch (PDOException $e) {}
...
$statement = $this->pdo->prepare("SELECT * FROM [DB].[dbo].table WHERE policy_num LIKE '%cyrillic_symbols%'");
$result = $statement->execute();
if ($result) {
while ($out = $statement->fetch()) {
var_dump($out[0]);
}
}
PS. MSSQL version 2012. Data in UTF-8 encoding.
I'll post this as an answer, because it's too long for comment. UTF-8 all the way through, suggested by #RiggsFolly has all the answers. In your case, you need to convert values from CP-1251 from/to UTF-8 . I've made this simple test case, see if this will help you:
T-SQL:
CREATE TABLE CyrillicTable (
[CyrillicText] varchar(200) COLLATE Cyrillic_General_CI_AS
)
INSERT INTO CyrillicTable
(CyrillicText)
VALUES
('Понедельник'),
('Вторник')
PHP (file is UTF-8 encoded, using Notepad++):
<?php
# Connection info
$hostname = 'server\instance,port';
$dbname = 'database';
$username = 'uid';
$pw = 'pwd';
# Connection
try {
$dbh = new PDO("odbc:Driver={SQL Server Native Client 11.0};Server=$hostname;Database=$dbname", $username, $pw);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch( PDOException $e ) {
die( "Error connecting to SQL Server. ".$e->getMessage());
}
# Query
try {
echo "Query"."<br>";
$sql = "SELECT * FROM dbo.[CyrillicTable] WHERE CyrillicText LIKE '%".iconv('UTF-8', 'CP1251', 'онед')."%'";
$stmt = $dbh->query($sql);
while ($row = $stmt->fetch( PDO::FETCH_ASSOC )) {
foreach($row as $name => $value) {
echo $name.": ".iconv('CP1251', 'UTF-8', $value)."<br>";
}
}
echo "<br>";
} catch( PDOException $e ) {
die( "Error executing query: ".$e->getMessage());
}
$stmt = null;
# Query
try {
echo "Prepared query"."<br>";
$sql = "SELECT * FROM dbo.[CyrillicTable] WHERE CyrillicText LIKE ?";
$stmt = $dbh->prepare($sql);
$text = 'орни';
$text = "%$text%";
$text = iconv('UTF-8', 'CP1251', $text);
$stmt->bindParam(1, $text, PDO::PARAM_STR);
$stmt->execute();
while ($row = $stmt->fetch( PDO::FETCH_ASSOC )) {
foreach($row as $name => $value) {
echo $name.": ".iconv('CP1251', 'UTF-8', $value)."<br>";
}
}
echo "<br>";
} catch( PDOException $e ) {
die( "Error executing stored procedure: ".$e->getMessage());
}
$stmt = null;
# End
$dbh = null;
?>
Notes:
Consider using parameterized query.

Slim framework PDO PGSQL, not binding parameters

I'm having a little bit of an issue with PDO binding Parameters.
My setup is as follows.
Ubuntu Desktop 16.04
Netbeans 8.1 (php and html only version)
php cli 7.0.4 (Running internal web server)
Postgres SQL 9.5
Slim Framework 3
I have opted to use PDO to access my database. This is my learning the system for a future project.
I can grab all records from a table, I can get the argument issued in the uri to echo on screen.
But using the GET method to locate a specific entry throws the following error at me.
{"error":{"text":SQLSTATE[08P01]: <>: 7 ERROR: bind message supplies 0 parameters, but prepared statement "pdo_stmt_00000001" requires 1}}
The following is my code.
db.php
<?php
function getDB() {
$dbtype="pgsql";
$dbhost="localhost";
$dbuser="postgres";
$dbpass="SomeSecurePassword";
$dbname="bms";
$dbConnection = new PDO("$dbtype:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbConnection;
}
?>
index.php
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require 'vendor/autoload.php';
require 'db.php';
$app = new \Slim\App;
$app->get('/','getRoot');
$app->get('/contacts', 'getContacts');
$app->get('/contacts/{contact_id}', 'getContact');
$app->run();
function getRoot() {
echo 'This is the Root URI';
}
function getContacts() {
$sql = "SELECT last_name,first_name FROM contacts ORDER BY last_name DESC";
try {
$db = getDB();
$stmt = $db->query($sql);
$contacts = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo '{"Contacts": ' . json_encode($contacts) . '}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
function getContact(Request $request, Response $response, $args) {
$contact_id = (int)$args['contact_id'];
$sql = "SELECT * FROM contacts WHERE contact_id = :contact_id";
try {
$db = getDB();
$stmt = $db->query($sql);
$stmt->bindParam(':contact_id', $contact_id, PDO::PARAM_INT);
$stmt->execute();
$stmt->debugDumpParams();
$db = null;
echo '{"Contact": ' . json_encode($contact) . '}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
Where could I be going wrong?
You need to use prepared statements.
$stmt = $db->query($sql); //Executes a query and returns a statement
What you want is...
$stmt = $db->prepare($sql);
$stmt->bindParam(':contact_id', $contact_id, PDO::PARAM_INT);
$stmt->execute();

PHP PDO query on MySQL does not return as expected

I've been working on an iOS web service using PHP, but I'm not having very much luck. I'm attempting to safely query the database and select the id of the user when the name and password match. Unfortunatly, nothing is showing up on the page. I would assume that means the query went wrong somewhere. I've attempted using static values, but to no avail. Any ideas?
P.S. I'm positive the values are correct.
P.P.S. Yes, I know, encrypt. For the simplicity, I'm not bothering.
error_reporting(E_ALL);
ini_set('display errors', 1);
try {
$DBH = new PDO("mysql:host='localhost';dbname='login_test'", 'test', 'development');
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo e->getMessage();
}
$data = array($_GET['name'], $_GET['password']);
$STH = $DBH->prepare('SELECT id FROM users WHERE name = ? AND password = ?');
$STH->execute($data);
$row = $STH->fetch(PDO::FETCH_ASSOC);
print '<pre>';
print_r($row);
Try it ,
try {
$DBH = new PDO("mysql:host='localhost';dbname='login_test'", 'test', 'development');
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo /*here*/ $e->getMessage();
}
$data = array($_GET['name'], $_GET['password']);
$STH = $DBH->prepare('SELECT id FROM users WHERE name = ? AND password = ?');
$STH->execute($data);
$row =$STH->fetch(PDO::FETCH_ASSOC)
print '<pre>';
print_r($row);

My openshift application PDO query didn't work

I am try to connect phpmyadmin database using my php script in openshift
but the result is a empty page.
then, I find the question is the query didn't work
but I don't know why
There is my original code
try{
$dsn = 'mysql:dbname=exampleDataBase;host=127.**.***.***;port=*****';
$dbh = new PDO($dsn, "account", "password");
$sth = $dbh->prepare('SELECT * FROM test1');
$fin = $sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)){
print_r($row);
}
} catch (PDOException $e){
echo "Sytan error" . $e -> getMessage();
}
$dbh = null;
and the result is a empty page, so I modify my code
There is my modify code
try{
$dsn = 'mysql:dbname=exampleDataBase;host=127.**.***.***;port=*****';
$dbh = new PDO($dsn, "account", "password");
$sth = $dbh->prepare('jngfcjfgcnmgcm,,hmnxf');
$fin = $sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)){
print_r($row);
}
} catch (PDOException $e){
echo "Sytan error" . $e -> getMessage();
}
$dbh = null;
I input the wrong query sytanx(jngfcjfgcnmgcm,,hmnxf), but it didn't return error.
Add this to your script see your errors
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors',1);
ini_set('html_errors', 1);
and change your query code to this, see notes
try{
//port=***** is only need where its different from the default
$dsn = 'mysql:host=localhost;dbname=exampleDataBase';
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$dbh = new PDO($dsn, "account", "password", $options);
$sth = $dbh->prepare('SELECT * FROM test1');
// execute $sth
$sth->execute();
//Change fetch to fetchAll
while($row = $sth->fetchAll(PDO::FETCH_ASSOC)){
print_r($row);
}
} catch (PDOException $e){
echo "Sytan error" . $e->getMessage();
}
You modified your code to a wrong statement to see the error message?
You have your PHP errors turned off, when doing a statement like:
$sth = $dbh->prepare('jngfcjfgcnmgcm,,hmnxf');
You would receive an error like:
Sytan errorSQLSTATE[42000]: Syntax error or access violation: 1064 You
have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near
'jngfcjfgcnmgcm,,hmnxf' at line 1
What do you exactly want? The exception is not showing?

Windows Azure MaxSizeInByte Statement

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");
?>

Categories