PHP Remote MSSQL Connection - php

I'm trying to develop a solution for my company and my goal is to connect our web server (which is on php and there is a web site already running on it) to our CRM database ( which is on mssql and based on another server ). My first solution is to have a replica of this CRM database in web server and do synchronization on it daily or hourly because of security issues. But now I'm thinking about making a direct connection, do you think will that be possible and if it's possible what can be the security problems I may come across. Do anyone have an experience on this kind of problem?
Thanks
J

Connecting to remote database will be slow, but at least your data will be consistent. If speed is not everything, I suggest this method. Migrating data can be painful.
You may want to create secure (SSL) connection between the servers. For detailed information please ask your system administrator.

doing the synchronization daily should be discouraged because you will lose real time data reliability.
If you are using PHP version 5.1, it still supports php-mssql connection thru php_mssql.dll, just be sure to enable it on your PHP.ini

<?php
$serverName = "ServerName"; /// use remote server name here
$uid = "sqlusername";
$pwd = "sqlpassword";
$databaseName = "DBName";
$connectionInfo = array( "UID"=>$uid,
"PWD"=>$pwd,
"Database"=>$databaseName);
/* Connect using SQL Server Authentication. */
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$tsql = "SELECT id, FirstName, LastName, Email FROM tblContact";
/* Execute the query. */
$stmt = sqlsrv_query( $conn, $tsql);
if ( $stmt )
{
echo "Statement executed.<br>\n";
}
else
{
echo "Error in statement execution.\n";
die( print_r( sqlsrv_errors(), true));
}
/* Iterate through the result set printing a row of data upon each iteration.*/
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC))
{
echo "Col1: ".$row[0]."\n";
echo "Col2: ".$row[1]."\n";
echo "Col3: ".$row[2]."<br>\n";
echo "-----------------<br>\n";
}
/* Free statement and connection resources. */
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
?>

Related

How do you fetch from a mysql database?

I'm relatively new to any type of programming or coding. I'm not quite understanding why no matter what adjustments I make to my php file I can't seem to pull any data from a table.
Here is a link to the table: https://i.gyazo.com/4ad5e860895014c49dbe0539c38cdec2.png
Above is the test table I have been trying to use. From what I can understand I'm connecting to the database okay, but all of my problems come after the connection. Also, I'm using php 7.0 so a lot of the information I'm finding online has not been helpful.
If there is something glaringly wrong with my table or in my code, please let me know.
Here is my code:
'''
//Set Variables
$serverName = "localhost";
$userName = "root";
$password = "";
$databaseName = "test";
//Create Connection
$connection = mysqli_connect($serverName,$userName,$password,$databaseName);
//Check Connection
if(!$connection){
die("Connection failed: ".mysqli_connect_error());
}
echo "Connected successfully <br>";
//Fetch Data
$query = "SELECT * from table1";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
printf ($row[1], $row[2]);
mysqli_free_result($result);
mysqli_close($connection);
I figured out the issue a few hours ago. The code I had posted would have worked perfectly fine if I was connecting to the port for MySQL rather than MariaDB. Didn't realize that the port that MariaDB was connected to was the default.
MariaDB by default was port 3306, but MySQL was 3308. After specifying 'localhost:3308' I was able to start properly pulling rows from my tables.

How do i implement a persistent connection to a MySQL Database using PHP?

I need some help with PHP code architecture and best practice.
I need to run update on 4000 rows in a MySQL Database.
Here's the function/code i use to connect to the Database:
function connectToDB(){
$uname = "USERNAME";
$pword = "PASSWORD";
try {
$db_conn = new PDO('mysql:host=SERVERHOSTNAME;dbname=DATABASENAME;port=PORTNUMBER', $uname, $pword);
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $pdoe){
//fandle exception
}
return $db_conn;
}
Now, when i do the actual work, here's the code i use in the loop,
$all_array = array("1", "2", ......, "4000");
foreach ($all_array as $key => $value) {
$sqlcode = "INSERT INTO table .....";
$conn_db = connectToDB();
$conn_db_prepare = $conn_db->prepare($sqlcode);
$conn_db_prepare->execute();
}
With this, the code will run the connectToMitsubishiComfortDB for each key in the lop, which will be 4000 times, that's 4000 different connections.
I'm not sure if this best practice.
Is there a way for me to connect to the database once, and not run the 4000 loops so i don't have to connect every time?
Is there a way for me to improve the code?
This is an application that runs everyday and insert into 4000 rows in a table. The Database is MySQL, and code used is PHP.
you need to move the line $conn_db = connectToDB(); out of your loop
Move both the connection and the prepare outside of the loop. You only need to connect once and you only need to prepare once.
$conn_db = connectToDB();
$conn_db_prepare = $conn_db->prepare('INSERT INTO table .....');
$all_array = array("1", "2", ......, "4000");
foreach ($all_array as $key => $value) {
$conn_db_prepare->execute();
}
Best way to enable persistent connection in PDO by passing array(PDO::ATTR_PERSISTENT => true) into the connection string.
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(PDO::ATTR_PERSISTENT => true));
https://www.php.net/manual/en/pdo.connections.php
Note:
If you're using the PDO ODBC driver and your ODBC libraries support ODBC Connection Pooling (unixODBC and Windows are two that do; there may be more), then it's recommended that you don't use persistent PDO connections, and instead leave the connection caching to the ODBC Connection Pooling layer. The ODBC Connection Pool is shared with other modules in the process; if PDO is told to cache the connection, then that connection would never be returned to the ODBC connection pool, resulting in additional connections being created to service those other modules.

Library List is not being used in remote PHP DB2 connection to IBM i

I've successfully connected to a remote IBM i DB2 database (AS400) from my local Windows PC via PHP. I'm using the IBM Data Server Client in conjunction with the db2_* functions in PHP. The problem I'm having is that despite my library list being set properly, it is not being used for unqualified table names. Instead it uses the current user name as the library. However, when I qualify the table names everything works like a charm.
I've confirmed that my library list is actually changing when I create the connection by querying QSYS2.LIBRARY_LIST_INFO.
$database = '<database name>';
$user = '<user name>';
$password = '<password';
$port = <port>;
$options['i5_naming'] = DB2_I5_NAMING_ON;
$options['autocommit'] = DB2_AUTOCOMMIT_OFF;
$options['i5_libl'] = 'MYLIB YOURLIB ANYLIB';
$conn = db2_connect($database, $user, $password, $options);
if ($conn) {
echo "Connection succeeded."; //It succeeds
}
else {
echo db2_conn_error()." | ".db2_conn_errormsg()."<br />";
echo "Connection failed.";
}
$sql = "SELECT * FROM QSYS2.LIBRARY_LIST_INFO";
//Works and proves my library list reflects
//what I passed in when creating the connection.
//$sql = "SELECT * FROM LIBRARY_LIST_INFO";
//Generates: "42S02 : [IBM][CLI Driver][AS] SQL0204N "<user name>.LIBRARY_LIST_INFO" is an undefined name. SQLSTATE=42704 SQLCODE=-204"
//where <user name> is the username used to connect to the DB.
//It should be using the library list specified when creating the connection though.
//This holds true for any table from any library including those specified
//when creating the connection (which includes QSYS2).
$stmt = db2_prepare($conn, $sql);
$result = db2_execute($stmt);
if($result){
while($row = db2_fetch_assoc($stmt)){
echo "<pre>";
var_dump($row); //In addition to entries for QSYS, QSYS2, QUSRSYS and QHLPSYS I get entries for MYLIB, YOURLIB and ANYLIB.
echo "</pre>";
}
}else{
echo "failed<br />";
echo db2_stmt_error()." : ".db2_stmt_errormsg()."<br />";
}
Has anyone ever run into this while enabling i5_naming when connecting to a remote DB2 server? I'm not really sure why it wouldn't be using my library list as the PHP manual states "Unqualified files are resolved using the library list for the job." when enabled. http://php.net/manual/en/function.db2-connect.php
I finally solved this after opening a PMR with IBM. All I had to do was apply the latest Fix Pack for DB2 Connect Personal Edition.
Suggested Fix Packs for DB2 Connect:
http://www-01.ibm.com/support/docview.wss?rs=71&uid=swg21321001
Basically the DB2 Connect version I had was released prior to 2013. It was in 2013 IBM added two tier support by adding the i5_naming option. So my DB2 Connect setup was effectively ignoring the option I was passing. So that explains why the other options still went through. On the DB side, since it didn't receive a value for i5_naming - it remained as the default.

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 + MSSQL data not inserting into table using sqlsrv

I have a problem with my sqlsrv_query. I have made a simple insert and update thru my application..my system popup insert successful..but when I use mssql studio management (MSSQL 2008 R2) also used EMS SQL, there is no data in my table..i try to used back my query form my application and paste at my query editor at mssql studio management, it’s works, 1 row(s) affected. I don’t now what is actually happening. I am using PHP 5.3.22, driver php_sqlsrv_53_nts_vc9.dll. I have no problem with my db connection..please help me.
$serverName = "servername"; $connectionInfo = array( "Database"=>"databasename", "UID"=>"username", "PWD"=>"password"); $conn = sqlsrv_connect( $serverName, $connectionInfo);
function msexecDB($query, $conn){
$result = sqlsrv_query($conn, $query) or trigger_error("A SQL error has occurred.Your Query:---------" . $query . "---------"); return $result;
}
$insert_program = "INSERT INTO TB_PROGRAM (kod_program) VALUES ('$kod_program')";
$row_program = msexecDB($insert_program, $conn);
Check the value of $kod_program. It's possible you're inserting a blank string, which could have the appearance of having no record at all, yet would successfully run the query.

Categories