Laravel 8 connect to MSSQL 2000 issue - php

OS: CentOS 7
DB: MSSQL 2000
Larvel: 8
PHP: 7.4.26
My project need to use Laravel 8 eloquent to connect to MSSQL 2000, MSSQL 2000 is too old to be connected by modern PHP SQL server driver, people suggest using ODBC + FreeTDS, so I take this article as a reference, I successfully connect to the SQL server by native PHP code via PDO, just like the example in that article.
<?php
$host = '{IP}';
$port = '1433';
$dbname = '{DATABASE}';
$username = '{USERNAME}';
$password = '{PASSWORD}';
try {
$dsn ='odbc:Driver=FreeTDS;Server=' . $host . ';Port=' . $port . ';Database=' . $dbname . ';UID=' . $username . ';PWD=' . $password . ';clientcharset=UTF-8';
$dbConn = new PDO($dsn);
$stmt = $dbConn->query("SELECT TOP 2 t.*
FROM {DATABASE}.dbo.{TABLE} t
WHERE CREATOR = '{SOMEONE}'
ORDER BY CREATE_DATE DESC");
$row = $stmt->fetchAll();
echo '<pre>';
var_dump($row);
echo '</pre>';
} catch (PDOException $e) {
echo $e->getMessage();
}
Then I go to packagist to search ODBC package for Laravel and try:
https://packagist.org/packages/yoramdelangen/laravel-pdo-odbc
https://packagist.org/packages/cooperl/laravel-db2
https://packagist.org/packages/abram/laravel-odbc
https://packagist.org/packages/dbt/odbc-driver
Laravel was able to connect to the SQL server, but I got some error messages if has SQL condition:
Table::where("CREATE_DATE", $this->date)
->orWhere("MODI_DATE", $this->date)
->get();
SQLSTATE[42000]: Syntax error or access violation: 306 [FreeTDS][SQL Server]The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator. (SQLExecute[306] at /builddir/build/BUILD/php-7.4.26/ext/pdo_odbc/odbc_stmt.c:259) (SQL: select * from "{TABLE}" where "{TABLE}"."CREATE_DATE" = 20060419 or "{TABLE}"."MODIFY_DATE" = 20060419)
I think it's not caused by the packages, but I try the SQL statement in native PHP with the same driver works perfectly, have no idea.

Related

mysql vs mysqli error when running php code in wamp stack

( mysql vs mysqli error (advait) )
Hi All, See code. This code runs on my localhost WAMP Win7 php ver 5.5.12 but it gives an error:
---
Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\wamp\www\get_data02.php on line 9
Call Stack
# Time Memory Function Location
1 0.0010 135216 {main}( ) ..\get_data02.php:0
2 0.0010 135680 mysql_connect ( ) ..\get_data02.php:9
---
I tried replacing mysql with mysqli but that just gave more errors. How do I fix this? Thanks,
<?php
// 1. Enter Database details
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'iamdb_copy_04';
// 2. Create a database connection
$connection = mysql_connect($dbhost,$dbuser,$dbpass);
if (!$connection) {
die("Database connection failed: " . mysql_error());
}
// 3. Select a database to use
$db_select = mysql_select_db($dbname,$connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$query = mysql_query("SELECT * FROM users WHERE city = 'city' ");
while ($rows = mysql_fetch_array($query)) {
$f_name = $rows['first_name'];
$address_01 = $rows['address_01'];
$city = $rows['city'];
echo "$f_name<br>$address_01<br>$city<br><br>";
}
?>
There are two options to get out from this error.
Set display_errors off in php file using ini_set("display_errors",0) after start of php <?php.
Replace mysql with mysqli in mysql_connect, mysql_select_db,mysql_query, mysql_fetch_array.
Let me know if you still face any problem and also comment your error.

Run SQL script via PHP

I've created a backup.sql script to restore a MySql database. I've checked the script with PHPMyAdmin import and everything works fine (the database has been restored successfully). Now I would like to run it via PHP. I've found this question and I have:
1) created a PHP file into htdocs folder with the following content
$site_path= realpath(dirname(__FILE__)).'/';
$command = 'mysql'
. ' --host=' . 'localhost'
. ' --user=' . 'myuser'
. ' --password=' . 'mypass'
. ' --database=' . 'dbname'
. ' --execute="SOURCE ' . $site_path;
$output = shell_exec($command . 'backup.sql"');
echo "<pre>".$output."</pre>";
2) placed the backup.sql script into htdocs folder
But when I run the script, nothing happens on the database and nothing is displayed regarding shell_exec results. I'm running PHP and MySql under Apache on a windows machine. The command variable has the following value:
mysql --host=localhost --user=myuser --password=mypass--database=dbname --execute="SOURCE C:\Programmi\Apache Software Foundation\Apache2.2\htdocs/
What am I missing?
$mysql_host = "localhost";
$mysql_database = "db";
$mysql_user = "user";
$mysql_password = "password";
# MySQL with PDO_MYSQL
$db = new PDO("mysql:host=$mysql_host;dbname=$mysql_database", $mysql_user, $mysql_password);
$query = file_get_contents("shop.sql");
$stmt = $db->prepare($query);
if ($stmt->execute())
echo "Success";
else
echo "Fail";
If you have the whole code in your sql file 100% correct and nothing to change on it, then try this, use PDO for better security in your code.
You can overcome this by using a MYSQL DBMS tool as Workbench where you can connect to the remote/local server and run the .sql file without the use of PHP.
PHP is meant to be used for applying business queries that reflect certain business functionality and not basically made for server actions or other tool jobs like DBMS tools..
If you really need to do this you can check this tutorial that reads the sql file and explode the queries into an Array using the ; character that shall delimit each query.
It then loops through each query in the array using foreach and executes the query on its own.
One thing I notice is that, the operation may take longer or if another operation is needed afterwards, especially during development to test that the file has been executed, the execute method will no to terminated.
I simple solution is to execute the query, then get the prepared query and run method rowCount,with this then we can safely test whether or not the execution has terminated.
So just use $count = $stmt->rowCount(); and not only $stmt->execute();
try {
$db = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
$query = file_get_contents(__DIR__ . "/test.sql");
$stmt = $db->prepare($query);
$stmt->execute();
$stmt->closeCursor();// Safely consuming the SQL operation till end
$count = $stmt->rowCount(); // Check if not pending transaction
if ($count) {
foreach($db->query('SELECT * from person') as $row) {
print_r($row);
}
}
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
exit;
}

PHP mssql_connect() to Azure Database

I try to set connection with my site and mssql database. I can connect to database, but i can't execute SQL queries. My code is
$connection = mssql_connect('jass8l1.database.windows.net', 'username', 'password');
if (!$connection){
print_r(mssql_get_last_message());
}else{
$res= mssql_query('SELECT * FROM [my_database].[dbo].[table]', $connection);
print_r(mssql_get_last_message());
$row = mssql_fetch_array($res);
echo $row[0];
}
This code shows error
Reference to database and/or server name in 'my_database.dbo.table' is not supported in this version of SQL Server.
But when I execute this query online, link MANAGE URL, this error does not occur.
How can I solve this problem? Maybe I need some additional driver is for PHP?
The error message cannot be more descriptive than it is!
You simply cannot use the 4-word-notation (i.e. [DB_NAME].[SCHEMA].[TABLE_NAME].[COLUMN]. With SQL Azure you shall always use the 3-word notation (i.e. [SCHEMA].[TABLE].[COLUMN]).
Something more for SQL Azure is that you have to explicitly set Database in your connection. You can not do USE [DB_NAME] in SQL Azure.
When using SQL Azure with PHP I recommend that you go through the How to: Connect to Windows Azure SQL Database from PHP.
You have to alter your connection to something like:
$serverName = "tcp:ProvideServerName.database.windows.net,1433";
$userName = 'ProvideUserName#ProvideServerName';
$userPassword = 'ProvidePassword';
$dbName = "TestDB";
$table = "tablePHP";
$connectionInfo = array("Database"=>$dbName, "UID"=>$userName, "PWD"=>$userPassword, "MultipleActiveResultSets"=>true);
sqlsrv_configure('WarningsReturnAsErrors', 0);
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if($conn === false)
{
FatalError("Failed to connect...");
}
Also, it is strongly recommended to use Microsoft's MS SQL driver and not the standard PHP provided MSSQL (also referred in the How To).

PHP to query SQL Server 2008 R2

We have a database running on Windows Server 2008 R2, SQL Server 2008 R2. I need to query the database via PHP (I'm also open to other options) and display the data in a web page.
I have tested connectivity with my username, password and server name using a UDL test file. My connection is successful.
My web server has PHP 5.4 installed and working.
I have built a PHP script that is supposed to connect and query the database but I get a server error.
<?php
$myServer = "ipaddress";
$myUser = "username";
$myPass = "password";
$myDB = "dbname";
//connection to the database
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
//select a database to work with
$selected = mssql_select_db($myDB, $dbhandle)
or die("Couldn't open database $myDB");
//declare the SQL statement that will query the database
$query = "SELECT fullName, email_address, pos_desc";
$query .= " FROM dbo.EMPLOYEE_VIEW ";
$query .= "WHERE grp_cde='STAFF'";
//execute the SQL query and return records
$result = mssql_query($query);
$numRows = mssql_num_rows($result);
echo "<h1>" . $numRows . " Row" . ($numRows == 1 ? "" : "s") . " Returned </h1>";
//display the results
while($row = mssql_fetch_array($result))
{
echo "<li>" . $row["id"] . $row["name"] . $row["year"] . "</li>";
}
//close the connection
mssql_close($dbhandle);
?>
Keep in mind the Database server and the Web Server are both running Windows Server 2008 R2 and exist in the same domain.
The only error I receive is:
500 - Internal server error.
There is a problem with the resource you are looking for, and it cannot be displayed.
Is there anything I can do to troubleshoot why this is not working?
I appreciate any and all help on this question.
Error 500 usually means you forgot a ; or ', I suggest you check your code carefully for any redundant or missing characters.
Also, turning on php errors in your php.ini file helps alot with fixing these sort of stuff.
After pheww... what now? 6 hours? I have it working! The problem was that I needed to set up SQL Server 2008 drivers on my web server and connect using ODBC via my PHP script. I am now pulling and displaying data from my SQL Server 2008 Database like a pro. Thanks for the assistance guys.
odbc_connect("DRIVER={SQL Server Native Client 10.0};Server=serverip;Database=tablename", "username", "pass");

PHP Can't Connect to MS SQL Express 2008

I'm struggling to connect to my MS SQL Express 2008 edition from my PHP files, but it seems virtually impossible.
I've found several guides/notes on teh intarweb solving the issues, but none of these have helped me any further.
I've taken a script from another site and entered my database information, but I still get errors:
<?php
$myServer = "localhost";
$myUser = "demo_basic";
$myPass = "1234";
$myDB = "demo_basic";
//connection to the database
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
//select a database to work with
$selected = mssql_select_db($myDB, $dbhandle)
or die("Couldn't open database $myDB");
//declare the SQL statement that will query the database
$query = "SELECT nitid, nisname ";
$query .= "FROM navitems";
//execute the SQL query and return records
$result = mssql_query($query);
$numRows = mssql_num_rows($result);
echo "<h1>" . $numRows . " Row" . ($numRows == 1 ? "" : "s") . " Returned </h1>";
//display the results
while($row = mssql_fetch_array($result))
{
echo "<li>" . $row["nitid"] . $row["nisname"] . "</li>";
}
//close the connection
mssql_close($dbhandle);
?>
I get this error:
Warning: mssql_connect()
[function.mssql-connect]: Unable to
connect to server: localhost in
C:\inetpub\vhosts\dexterholding.dk\httpdocs_rip\sql.php
on line 8 Couldn't connect to SQL
Server on localhost
You can see for yourself at: http://www.dehold.net/_rip/sql.php
Any ideas?
I'm running Windows Server 2008 with PLESK and PHP5 as FastCGI.
I found this guide which actually made it work for me:
http://samsami2u.wordpress.com/2008/06/30/how-to-connect-mssql-with-php/
With MSSQL, your server name will look like this: machinenameoraddress\serverinstancename
and example would be 192.168.14.201\MSSQLEXPRESS or TESTMACHINE\MYTESTDBSERVER.
It could be that the user account does not have permission to access SQL Server.
Although looking at your code you are using SQL auth and not Windows authentication, presumably this account is set up in SQL Server and it is configured to allow SQL Auth?

Categories