php pdo with mssql and a dns - php

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.

Related

Is it possible to connect to server management studio database from joomla?

I am trying a simple datababase connection from a joomla website, to a server management studio database.I have tried serveral different ways, srv, dbo etc.
It still displays errors in its simplest form.
Is it possible to establish such a connection?
Error messages:
Unable to load Database Driver: mssql
Uncaught Error: Call to undefined function mssql_connect()
Call to undefined function sqlsrv_connect()
simplest:
<?php
// Create a link to MSSQL
$con = mssql_connect('server1', 'name', 'pass');
// Select the database 'php'
mssql_select_db('database1', $con);
?>
way2:
<?php
$servername = "s1";
$username = "u1";
$password = "p1";
try {
$conn = new PDO("sqlsrv:Server=$servername;Database=db1", $username, $password);
// set the PDO error mode to exception
$setAttribute = $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>

Error With PHP7 and SQL Server on Windows

I am getting "Fatal error: Invalid handle returned. in" in PHP 7 while trying to connect with SQL Server.
I have already tried below option
Error connecting to MSSQL with SQLSrv and PHP 5.4.7
Unable to connect to SQL Server with PHP
I am using below code:
try {
$conn = new PDO( "sqlsrv:Server=(10.10.10.222\sql2008r2);Database=test",'sa', 'sipl#123');
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch( PDOException $e ) {
die( "Error connecting to SQL Server" );
}
echo "Connected to SQL Server\n";
$query = 'SELECT *FROM atlas_positions';
$stmt = $conn->query( $query );
while ( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ){
echo '<pre>';
print_r( $row );
echo '</pre>';
}
Your views will be beneficial for me.
Try "ConnectionPooling=0" in DSN, it worked for me.
$conn = new PDO( "sqlsrv:Server=(10.10.10.222\sql2008r2);Database=test;ConnectionPooling=0",'sa', 'sipl#123');
(My answer is based on #maydimanche's answer from here)

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.

Encoding PHP PDO MS SQL Server

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.

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