Encoding PHP PDO MS SQL Server - php

I am starting learn PDO with MS SQL Server.
Connecting with this code:
$userDB = 'userBD';
$passwordDB = 'passwordDB';
try {
$DBH = new PDO('mssql:dbname=spr_bank;host=hostname', $userDB, $passwordDB);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
echo "<h1 style='font-weight:bold; color:red;'>Error. Can not connect to Database</h1>";
file_put_contents('PDOErrors.log', date("Y-m-d H:i:s")." - ".$e->getMessage()."\n", FILE_APPEND);
exit();
}
and now, I select data from table:
//simple query and binding with results
$query = $DBH->prepare("SELECT name FROM spr_sotrudnik WHERE login = :login AND password = :password");
$login = (isset($_POST['login']) === true) ? $_POST['login'] : '' ; // ? : shorthand for if else
$password = (isset($_POST['password']) === true) ? md5($_POST['password']) : '' ; // ? : shorthand for if else
// bind parameters - avoids SQL injection
$query->bindValue(':login', $login);
$query->bindValue(':password', $password);
//try... if not catch exception
try {
// run the query
$query->execute();
while($rows = $query->fetch()){
echo $rows["name"];
}
}
catch(PDOException $e){
echo $e->getMessage(), $e->getFile(), $e->getLine();
}
When I go to the browser, I get this error:
SQLSTATE[HY000]: General error: 10007 Unicode data in a Unicode-only collation or ntext data cannot be sent to clients using DB-Library (such as ISQL) or ODBC version 3.7 or earlier. [10007] (severity 5) [(null)]D:\www\sklad_new\inc\auth.php19
When I write this query
$query = $DBH->prepare(" SELECT CONVERT(VARCHAR(MAX),name) AS s FROM spr_sotrudnik WHERE login = :login AND password = :password");
I have no error, but I see "?????"
How can I change this?

You're omitting the charset parameter in the DSN string:
$DBH = new PDO('mssql:dbname=spr_bank;host=hostname', $userDB, $passwordDB);
... so you're probably using default encodings along the whole toolchain.
In any case, the PDO_DBLIB driver is clearly tagged as experimental and includes this notice:
On Windows, you should use SqlSrv, an alternative driver for MS SQL is
available from Microsoft: »
http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx .
If it is not possible to use SqlSrv, you can use the PDO_ODBC driver
to connect to Microsoft SQL Server and Sybase databases, as the native
Windows DB-LIB is ancient, thread un-safe and no longer supported by
Microsoft.
In my experience, this means that you can obtain all sort of unpredicted side effects.

Related

PHP 5.6.x lost ability to connect to ODBC source

I have a strange problem. My server has been running PHP 5.6 for years no problem. (WinServer Std 2K8 SP2, IIS 6, MySQL 5.6 {separate server}, PHP 5.6)
We connect it to a DB2 server at our parent company. Today (2017-02-14) the ODBC connection (PDO_ODBC) started returning "could not find driver".
Excel is able to use the same ODBC connection to query the database - the ODBC connection is working.
I tried using both the PDO method and procedural method to connect. Failures in seeing the driver both ways.
From phpinfo():
ODBC Data
PDO Data
Code snippet:
$dsn = "odbc:workingODBCdsn";
$user = "xxxx";
$password = "yyyy";
$conn = null;
$results = array();
try {
$conn = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
die($e->getMessage());
}
if ($conn) {
$qry = $conn->query($sql);
if ($qry) {
$qry->setFetchMode(PDO::FETCH_ASSOC);
foreach ($qry as $row) {
$results[] = $row;
}
}
}
print "<pre>" . print_r($results, true) . "</pre>";
//ALT Method
$conn = odbc_connect($dsn, $user, $password);
$results = odbc_exec($conn, $sql);
print "<pre>" . print_r($results, true) . "</pre>";
Thanks in advance for any help.
Are you using the unixODBC or ibm_db2 (http://php.net/manual/en/ref.pdo-odbc.php)? It it recommended to use IBM DB2 Universal Database with “ibm_db2” extension. It’s faster and more efficient than using generic driver. It calls the native IBM DB2 functions with the extension.
Check out the db2_* functions from php.net IBM DB2 functions manual
Server's PHP instance switched from IIS to IISExpress. Switching it back to (full) IIS, and enduring all appropriate PDO drivers were enabled fixed the problem.

Connection between PHP and SQL server using WAMP new approaches

what is the best way for create a connection between PHP and SQL server that are seperate?(two server: server a SQL and server b PHP)
notice that I use wamp.
I read some articles like below but I want to know is there any new idea?
I test this code that works perfectly:
try{
$user = 'user';
$password = 'pass';
$server="localhost";//or server IP
$database="database";
$conn = odbc_connect("Driver={SQL Server};Server=$server;Database=$database;", $user, $password);
} catch (PDOException $e) {
echo "Failed : " . $e->getMessage() . "\n";
exit;
}
I use PDO_ODBC Method:
1- Install ODBC on server that has wamp and enable PHP_PDO_ODBC extension on your wamp
2- Use this code that supports UTF-8:
try{
$hostname = "IP";
$dbname = "database";
$username = "username";
$pw = "password";
$pdo = new PDO ("odbc:Driver={SQL Server Native Client 10.0};Server=$hostname;Database=$dbname; Uid=$username;Pwd=$pw;");
} catch (PDOException $e) {
echo "Failed : " . $e->getMessage() . "\n";
exit;
}
$query = $pdo->prepare("select field_name from table");
$query->execute();
for($i=0; $row = $query->fetch(); $i++){
echo iconv("CP1256","UTF-8", $row['field_name'])."<br>";
}
3- replace these Items with yours:
IP-database-username-password-field_name-table
4- sometimes you need use "SQL SERVER" instead of "SQL Server Native Client 10.0" and sometimes you need use "IP,port" instead of "IP" and sometimes you need use "ISO-8859-6" instead of "CP1256".
From the PHP manual: http://php.net/manual/en/pdo.construct.php
Example #1 Create a PDO instance via driver invocation
<?php
/* Connect to a SQL Server database using driver invocation */
$dsn = "sqlsrv:Server=12345abcde.database.windows.net;Database=testdb", "UserName#12345abcde", "Password";
try {
$dbh = new PDO($dsn);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
Just change the HOST ip to the IP and port of your mysql server.

Connecting to MYSQL using php

I am trying to connect to MYSQL using php, but when I use the following command:
$link=mysql_connect("localhost","root","password");
and echo $link, it gives me Resource id #98. What does this mean? Am I not connected?
Okay, I guess it sounds like the connection is okay. Now, with the following code, I am not seeing any changes in the mysql database. Why could that be?
<?php
$conn=new mysqli("localhost","root","password","database");
$sql="INSERT INTO chat_active (user, time)
VALUES('John', '1234')";
?>
What makes you think you are not connected?
According to the docs, mysql_connect()
[r]eturns a MySQL link identifier on success or FALSE on failure.
Since it did not return FALSE, but rather a resource identifier, that means the connection was successful.
Also note that the mysql extension is deprecated since PHP 5.5.0 as MortimerCat pointed out. Instead you should look into the MySQLi or the PDO extension.
"Now, with the following code, I am not seeing any changes in the mysql database. Why could that be?"
As per your edit which you are now using mysqli_ to connect with, and that you're saying that you're not seeing any changes in your database, is because:
You're not passing the DB connection to your query and it is required when using mysqli_.
Rewrite, with a few more goodies:
<?php
$conn=new mysqli("localhost","root","password","database");
// Check if you've any errors when trying to access DB
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
$sql="INSERT INTO chat_active (user, time) VALUES ('John', '1234')";
$result = $conn->query($sql);
// Check if you've any errors when trying to enter data in DB
if (!$result)
{
throw new Exception($conn->error);
}
else{
echo "Success";
}
Read the manual http://php.net/manual/en/mysqli.query.php
Once you've grasped that, get to know mysqli with prepared statements, or PDO with prepared statements, they're much safer.
References:
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/language.exceptions.php
Footnotes:
Your column names user, time suggests that you're trying to enter a string and what appears to be and to be intended as "time" and that the user column is set to varchar.
Make sure that you haven't setup your time column other than a datetime-related type, otherwise MySQL may complain about that.
MySQL stores dates as YYYY-mm-dd as an example.
Visit https://dev.mysql.com/doc/refman/5.0/en/datetime.html in regards to different date/time functions you can use.
MySQL references:
https://dev.mysql.com/doc/refman/5.0/en/char.html
https://dev.mysql.com/doc/refman/5.0/en/data-types.html
https://dev.mysql.com/doc/refman/5.0/en/datetime.html
You yould use mysqli or PDO.
Here's a connection example with PDO:
<?php
$dbuser = 'user';
$dbpasswd = 'passwd';
$dbname = 'dbname';
try {
$gbd = new PDO("mysql:host=localhost;dbname=$dbname;charset=utf8", $dbuser, $dbpasswd);
$gbd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
}
PDO CRUD examples:
//INSERT
try {
$sentence = $gbd->prepare("INSERT INTO table (param1, param2) VALUES (:param1, :param2)");
$sentence->bindParam(':param1', $param1);
$sentence->bindParam(':param2', $param2);
$sentence->execute();
}
catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
//SELECT
try {
$sentence = $gbd->prepare("SELECT param1,param2 FROM table WHERE param1 = :param1 AND param2 = :param2)");
$sentence->bindParam(':param1', $param1);
$sentence->bindParam(':param2', $param2);
$sentence->execute();
while ($row = $sentence->fetch(PDO::FETCH_ASSOC)){ //Also available FETCH_NUM,FETCH_BOTH AND OTHERS
$result['param1'] = $row['param1'];
$result['param2'] = $row['param2'];
}
}
catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
//UPDATE
try {
$sentence = $gbd->prepare("UPDATE table SET param1 = :param1, param2 = :param2)");
$sentence->bindParam(':param1', $param1);
$sentence->bindParam(':param2', $param2);
$sentence->execute();
}
catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
//DELETE
try {
$sentence = $gbd->prepare("DELETE table WHERE param1 = :param1 AND param2 = :param2)");
$sentence->bindParam(':param1', $param1);
$sentence->bindParam(':param2', $param2);
$sentence->execute();
}
catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
And here's PDO manual
http://php.net/manual/en/book.pdo.php
u are not executing that query.u are only declaring that query.
for execution do--
$conn->query($qry);
it will,execute ur query.

php pdo with mssql and a dns

Trying to see if I can make PDO open my mssql database on my server. With vbscript my call to the connection looks like this:
set MyConn = Server.CreateObject("ADODB.Connection")
MyConn.Open("dsn=MYDSN;uid=MYUID;pwd=MYPWD;DATABASE=MYDATABASE;APP=ASP Script")
Then when trying to port this over to php using PDO I was unable to find any information on using DSN with PDO.
Here is what I have so far:
try {
$conn = new PDO('mssql:Server=localhost;Database=MYDSN','MYUID','MYPWD') or die('error');
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT name FROM people";
$qresult = $conn->prepare($sql);
$qresult->execute();
foreach ($qresult->fetch(PDO::FETCH_ASSOC) as $row){
echo $row['name'].'<br/>';
}
} catch (PDOException $e) {
print "Error!: ".$e->getMessage()."<br/>";
die();
}
But this is what I get
Error!: SQLSTATE[HY000]: General error: 10007 Invalid object name 'name'. [10007] (severity 5) [(null)]
My guess is because I cannot put the dsn anywhere in the pdo code.

PHP and Microsoft Access database - Connection and CRUD

I have no experience with access.
How to do update/insert/delete/select statement with and without $rs = new com("ADODB.RecordSet");
?
PDO
If you want to interface with an MS Access database using PHP, PDO is available for you.
<?php
try {
$pdo = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\accounts.mdb;Uid=Admin");
}
catch (PDOException $e) {
echo $e->getMessage();
}
When using PDO, due to the unified interface for DB operations, you have the opportunity to make your app more portable across various RDBMs systems. All you have to do is to provide the connection string to the PDO new instance and have the correct PDO driver installed.
As the result of this unified interface, your application can be easily ported from MS Access to MySQL, SQLite, Oracle, Informix, DB2, etc. which most certainly is the case if it ages enough.
Here's an insertion example:
<?php
try {
// Connect,
// Assuming that the DB file is available in `C:\animals.mdb`
$pdo = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\animals.mdb;Uid=Admin");
// INSERT data
$count = $pdo->exec("INSERT INTO animals(animal_type, animal_name) VALUES ('kiwi', 'troy')");
// echo the number of affected rows
echo $count;
// close the database connection
// See: http://php.net/manual/en/pdo.connections.php
$pdo = null;
}
catch (PDOException $e) {
echo $e->getMessage();
}
ODBC
In case you don't want to use PDO for some insane reasons, you can look into ODBC.
Here's an example:
<?php
if (! $conn = odbc_connect('northwind', '', '')) {
exit("Connection Failed: $conn");
}
if (! $rs = odbc_exec($conn, 'SELECT * FROM customers')) {
exit('Error in SQL');
}
while (odbc_fetch_row($rs)) {
echo 'Company name: ', odbc_result($rs, 'CompanyName'), PHP_EOL;
echo 'Contact name: ', odbc_result($rs, 'ContactName'), PHP_EOL;
}
odbc_close($conn);

Categories