Connect PHP to Ms SQL - php

I have completed all the steps to make a connection between PHP and Ms SQL but still its not working and showing an error of "Fatal error: Uncaught Error: Call to undefined function sqlsrv_connect()". I have installed MS SQL Driver also. the extension i am using in php.ini is php_pdo_sqlsrv_53_ts_vc9.dll right now but it is not included in xampp extensions. TCP/ IP is also enabled already.

You could use PDO statement to connect
An example bellow:
# Connecting to PostGreSQL
$dbh = new PDO("msql:dbname=$dbname; host=$host", $username, $password);
# Setting an attribute on the database handle and error reporting
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
# Prepares a statement for execution and returns a statement object
$query = 'SELECT * FROM test';
$stmt = $dbh->prepare($query);
$stmt->execute();
# Set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
# Returns an array containing all the results from the query
$allRows = $stmt->fetchAll();

Related

PDO database connection issue [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 1 year ago.
I am in the process of moving from hosted web sever to a VPS server I have setup with Apache, mysql, php etc. The following code works fine on my hosted server but throws an error on my VPS server
Fatal error: Uncaught PDOException: SQLSTATE[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 'groups' at line 1
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$host = 'localhost';
$db = 'dbname';
$user = 'user';
$pass = 'pass';
$charset = 'utf8';
$dsn = "mysql:host=$host; dbname=$db; charset=$charset";
echo $dsn .'<br>';
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$dbh = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
$sql = "SELECT * FROM groups";
$sth = $dbh->prepare($sql);
$sth->execute();
If I modify the SQL query to also include the database name e.g.
SELECT * FROM dbname.groups
Then it works fine, however I am at a loss to understand why I need to specify the database name in the query for it to work when the database is already selected in the DSN and it doesn't require it on my hosted server. I'm convinced it must be to do with some setting on my new VPS but cannot figure out what it may be and have a lot of code so really don't want to have to go through and alter every single SQL query to include the database name as well.
Hosted server is PHP 7.4.24
VPS server is PHP 7.4.3
Can anyone help?

Why can't I catch the error with PDOException?

Get info passed by POST method, and trim all space in the string, then start a new pdo instance, connect mysql, and insert info passed by POST into table.
$title = trim($_POST["title"]);
$content = trim($_POST["content"]);
$dsn = "mysql:host=localhost;dbname=blog";
$con = new PDO($dsn,"root","xxxx");
$title = $con->quote($title);
$content = $con->quote($content);
try
{
$sql = "insert into tmp (`title`,`content`) values('$title','$content')";
$stmt = $con->prepare($sql);
$stmt->execute();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
The above is my PHP code to make the job done,the most import command is
insert into tmp (`title`,`content`) values('$title','$content')";
No error info is shown by running the above PHP code, and no error exists in /var/log/mysql/error.log, but info has not been inserted into the database.
I changed the
insert into tmp (`title`,`content`) values('$title','$content')";
into
insert into tmp (`title`,`content`) values($title,$content)";
The info passed by POST can be inserted into mysql now, the issue that confuses me is that:
echo $e->getMessage(); take no effect at all.
no error info in /var/log/mysql/error.log
How can I catch these errors?
The exception you are trying to catch will never be thrown, because you need to tell PDO how you want it to handle errors.
$con = new PDO($dsn,"root","xxxx");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Otherwise, the default PDO::ERRMODE_SILENT will be used:
This is the default mode. PDO will simply set the error code for you to inspect using the PDO::errorCode() and PDO::errorInfo() methods on both the statement and database objects; if the error resulted from a call on a statement object, you would invoke the PDOStatement::errorCode() or PDOStatement::errorInfo() method on that object. If the error resulted from a call on the database object, you would invoke those methods on the database object instead.
Tangentially, you should be using prepared statements. You are using a prepare() call, but you are not parametrizing the query and binding the variables as you should. Using quote() is not secure enough.
2020 Update:
Interestingly, starting with PHP 8, the default behaviour for PDO will change and will throw exceptions by default. The change was voted on this RFC, which mentions:
The current default error mode for PDO is silent. This means that when an SQL error occurs, no errors or warnings may be emitted and no exceptions thrown unless the developer implements their own explicit error handling.
This causes issues for new developers because the only errors they often see from PDO code are knock-on errors such as “call to fetch() on non-object” - there's no indication that the SQL query (or other action) failed or why.
When PHP 8 is released on November 2020, the default error mode will be PDO::ERRMODE_EXCEPTION.

PDOException: "The auto-commit mode cannot be changed for this driver"

I'm trying to get PDO connecting to an SQL server to enter READ UNCOMMITTED, according to various sources (https://msdn.microsoft.com/en-us/library/cc296183(v=sql.105).aspx) this is how you do it.
$pdo = new PDO ("sqlsrv:server=$hostname;database=$dbname",$username,$pw,[PDO::SQLSRV_TXN_READ_UNCOMMITTED]);
This results in a PDOException: "The auto-commit mode cannot be changed for this driver"
When you're using PDO, you have to use this form:
$conn = new PDO("sqlsrv:Server=".$hostname.
";Database=".$database.
";TransactionIsolation=".PDO::SQLSRV_TXN_READ_UNCOMMITTED,
$username, $pw);
https://msdn.microsoft.com/en-us/library/ff628167.aspx

Cannot run mysql stored procedure in laravel4

Have some php code:
// Fetch PDO instance
$pdo = $this->conn->getPdo();
// Call procedure that checks is user credentials is ok
$stmt = $pdo->prepare('CALL Users_CheckLogin(:username, :password);');
$passw = md5($credentials['passw']);
$stmt->bindValue(':username', $credentials['username']);
$stmt->bindValue(':password', $passw);
// Execute procedure
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_CLASS, 'ArrayObject');
$stmt->closeCursor();
For some reasons this code doesn't work here and returns:
SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.
I also googled about this error and haven't found any fix for this. So perhaps someone here can explain me what the problem is? I don't have paralels queries, only my procedure, inside this procedure I executing additional queries so perhaps that a reason but then it is huge bug in pdo. This procedure call works in mysql manager and with mysqli also.

PHP Exception not raised on fatal error

I'm doing mysql queries with PHP5 and PDO.
I'm trying to handle exceptions from queries using try/catch. But if, for example, I have a syntax error like this :
try{
$sql = 'IggggNSERT INTO t_table (ID, MONTH) VALUES (:ID, :MONTH)';
$r = $conn->prepare($sql);
$r->bindValue(':ID', $id);
$r->bindValue(':MONTH', $month);
$r->execute();
return $r;
}
catch (Exception $e) {
die('Error');
}
I get this fatal error :
PHP Fatal error: Call to a member function bindValue() on a non-object
But no exception is raised and my catch block is not executed.
How could I handle this so I could rollback previous queries?
PDO will only throw an exception if the problem happens from within PDO. The error that you're getting is in reference to you accessing $r->bindValue despite $r failing to initialize.
In normal operation, you shouldn't ever get any syntax errors with your SQL.
You can however try setting the following line in your database file:
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
As far as I understand from PHP.NET, prepare() throws an exception if this line is set, which should set off the catch statement.
PHP.NET PDO::prepare
If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling).

Categories