Can't Connect to local server using PDO? - php

I have been playing around for PHP with a while. This is how i connect to sql server and it works:
$serverName = "SNAME";
$connectionInfo = array( "Database"=>"DBNAME", "UID"=>"USERNAME", "PWD"=>"PASSWORD");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$sql = "SELECT X FROM myTable";
$query = sqlsrv_query($conn,$sql);
if ($query === false){
echo "Could not link to SQL Server";
}
while ($row = sqlsrv_fetch_array($query))
{
$ARRAY[] = "$row[X]";
}
Server SNAME is on the local network, and i can connect to it from my computer using Sql Management Studio.
Now looking online and other places I have realized PDO is the better way to go. So I have been trying to connect to my server using PDO, by following examples online. Here is the code:
$username = "USERNAME";
$password = "PASSWORD";
try{
$conn = new PDO('mysql: host=SNAME;port=1433;dbname=DBNAME',$username,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = $conn->query('SELECT X FROM myTable');
foreach($data as $row) {
print_r($row);
}
}
catch{
echo 'ERROR: ' . $e->getMessage();
}
When i run this i get this on my page:
ERROR: SQLSTATE[HY000] [2002] No connection could be made because the
target machine actively refused it.
Now i know my other information is right since i can use the top block and sql management studio. Is there anyother library or something special needed. Is there problem with my code?
UPDATE
I ran this in my SQL Management Studio to check my port and it gave me 1433.
SELECT DISTINCT local_tcp_port FROM sys.dm_exec_connections WHERE local_tcp_port IS NOT NULL

In one example, you are using sqlsrv_connect, but in the other you tell PDO to connect to a 'mysql:' database.
You need to use the correct DSN string for a SQL Server connection.
$conn = new PDO('sqlsrv:Server=SNAME,1433;Database=DBNAME',$username,$password);
Manual: http://php.net/manual/en/ref.pdo-sqlsrv.connection.php
P.S. Make sure you have PDO_SQLSRV installed. http://php.net/manual/en/ref.pdo-sqlsrv.php

Related

PHP script to connect to SQL Server

I am running this script
<?php
$mysqli = mysqli_connect("ServerName", "username", "password", "dbname");
$res = mysqli_query($mysqli, "SELECT * from table1");
$row = mysqli_fetch_assoc($res);
echo $row['_msg'];
?>
I am getting this error:
mysqli_connect(): (HY000/2002): No connection could be made because
the target machine actively refused it
I have looked around online, but I can't figure out what is wrong. All the credentials are correct and it still doesn't work.
I am connecting to a local db on SQL Server through SQL Server authentication. Do I need MySQL running on xamp for this to work? Any ideas?
I am using Windows 10 through bootcamp on a mac. This is for SQL Server, not for mysql
It seems that you want to connect to a Microsoft SQL Server database. In this case maybe this code helps:
<?php
$serverName = "serverName\\sqlexpress"; //serverName\instanceName
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
?>
Also, if you run your php server locally with XAMPP you need to have Apache activated. If you try to connect to a MS SQL Server database you dont have to have MySQL enabled since you are not trying to connect to a MySQL database.
Source

Can not connect AWS RDS using PHP file hosted online (GoDaddy) [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
I do not believe the question to be a duplicate as I believe the issue is related to Shared Hosting environments getting outbound to other cloud mysql servers.
Error message
PDO Exception: SQLSTATE[HY000] [2002] Connection timed out.
I am simply just trying to connect to my instance of AWS RDS and run a query on one of my tables.
SOLUTION: GODADDY BLOCKS ALL PORTS EXCEPT 21 AND 22 (FTP) ON A STANDARD ACCOUNT. THIS IS WHAT I WAS TOLD BY GODADDY TECHNICAL SUPPORT. HENCE, IT WILL BLOCK PORT 1234 AND EVEN 3306 FOR A DATABASE CONNECTION.
UPDATE:
#Drew has validated that this php code works for the connection:
try {
$db = new PDO('mysql:host=uwmparkingbackend.cb7gmuw49vhs.us-east-1.rds.amazonaws.com;port=1234;dbname=uwm_parking;charset=utf8', 'fbgrecojr', 'test1234');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
echo "Connected and Happy<br>";
$sql="select id,thing from thingsCoveted where id in (1,3)";
foreach ($db->query($sql) as $row) {
print $row['id'] . "\t";
print $row['thing'] . "<br>";
}
} catch (PDOException $e) {
echo 'PDO Exception: ' . $e->getMessage();
exit();
}
I am getting this error however on my end:
PDO Exception: SQLSTATE[HY000] [2003] Can't connect to MySQL server on 'uwmparkingbackend.cb7gmuw49vhs.us-east-1.rds.amazonaws.com' (110)
Hence, there is either a config issue on the Godaddy side (where the .php is hosted) or the AWS RDS side (where the database is hosted);
Things I have tried:
1) checked to make sure all PDO options are selected in GoDaddy's php settings
2) added an inbound rule for my AWS RDS security group to allow all connections using my port (1234).
The problem is you've just copied and pasted your connection info into the example given by Amazon inside the $_SERVER array.
// Example
$link = mysqli_connect($_SERVER['RDS_HOSTNAME'], $_SERVER['RDS_USERNAME'], $_SERVER['RDS_PASSWORD'], $_SERVER['RDS_DB_NAME'], $_SERVER['RDS_PORT']);
// What yours should be
mysqli_connect(
'***********.******.us-east-1.rds.amazonaws.com',
'*******',
'********',
'dbname',
'1234'
);
You also need to use mysqli functions since that's how you're connecting, e.g. http://php.net/manual/en/mysqli.query.php
EDIT:
Now you're using PDO you will need to take a different approach to getting your data.
$dbhost = '***********.******.us-east-1.rds.amazonaws.com';
$dbport = 3306;
$dbname = '*****';
$dsn = "mysql:host={$dbhost};port={$dbport};dbname={$dbname}";
$username = '*****';
$password = '*****';
try {
$dbh = new PDO($dsn, $username, $password);
$query = $dbh->query("SELECT num_spaces FROM uwm_parking.lots");
while($row = $query->fetch(PDO::FETCH_OBJ)) {
var_dump( $row );
}
} catch(PDOException $e ){
echo "Error: ".$e;
}

Connect to SQL Server using PHP?

I am fairly new to using PHP. I downloaded XAMPP, and installed everything. PHP 5.5.27 is the version. I ran a test php program which was jsut echo "Hello World". It worked fine. I also was able to connect to MYSQL database using PHP.
$link = mysqli_connect("localhost", "u/n", "pass", "databasename";
Problem i am having and need help is with connecting to sql server. How do i do that? I saw an example online and tried it:
$serverName = "servername";
$connectionInfo = array("Database"="name", "UID"=>"U/N", "PWD"=>"pass";>
$conn = sqlsrv_connect($serverName, $connectionInfo);
But everytime i run this it tells me:
Call to undefined function sqlsrv_connect()
Can someone help me understand what is going on?
Consider using PHP's Data Objects (PDO) to connect to SQL Server (in fact you can use it to connect to MySQL or any other database).
Using the MSSQL sqlsrv API (various dlls must be set):
<?php
$server = 'servername';
$database = 'databasename';
$username = 'username';
$password = 'pass';
try {
$conn = new PDO("sqlsrv:Server=$server;Database=$database",
$user, $password);
}
catch(PDOException $e) {
echo $e->getMessage()."\n";
exit;
}
?>
Using the ODBC Driver or DSN API (requiring MSSQL ODBC Driver installed which usually ships with database or Windows in general):
<?php
$server = 'servername';
$database = 'databasename';
$username = 'username';
$password = 'pass';
try {
$dbh = new PDO("odbc:Driver={SQL Server};Server=$server;
database=$database",$username,$password);
}
catch(PDOException $e) {
echo $e->getMessage()."\n";
exit;
}
?>

MSSQL using PDO to connect

I am trying to connect to a mssql server on my mac through pdo_dblib. I have the freetds.conf updated to the host I want to connect. My phpinfo tells me that I have all the driver hooked up and good to go. Below is the code that I wrote to test if I can connect to the server.
<?php
$servername = "IP";
$port = "port";
$username = "username";
$password = "password";
$myDB = "database";
try {
$conn = new PDO("dblib:dbname=$myDB;host=$servername:$port", "$username", "$password");
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
However I get an error:
Connection failed: SQLSTATE[] (null) (severity 0)
I tried using SQL Developer to connect to the mssql server and it worked. I have been trying to solve this problem for a whole day. What might be the problem? Thanks!
Remove the quotes from the variables in the connection string -
$conn = new PDO("dblib:dbname=$myDB;host=$servername:$port", $username, $password);
I found out the answer!
You have to uncomment TDS version protocol in /usr/local/Cellar/freetds/0.91/etc/freetds.conf.
Found the solution in Why won't my server connect to a remote MSSQL server using PHP mssql_connect?
but why do I have to do this...no idea...wish some one could give some explanation.

php local connection mysql database

I try to make a simple IOS app that can connect to mysql database and read one table. But my php code does't work and really have no idea why, it's seems correct to me. The database is in a raspberry phpmyadmin server and the server works great.
I will put my code here and please tell me what's wrong.
<?php
$host = "192.168.2.193";
$db = "produtos";
$user = "root";
$pass = "1234";
$connection = mysql_connect($host, $user, $pass);
if(!$connection)
{
die("Database server connection failed.");
}
else
{
//attempt to select the database
$dbconnect = mysql_select_db($db, $connection);
//check to see if we could select the database
if(!dbconnect)
{
die("Unable to connect to the specified database!");
}
else
{
$query = "SELECT * FROM produtos";
$resultset = mysql_query($query, $connection);
$records = array();
//loop throught all our records and add them to our array
while ($r = mysql_fetch_assoc($resultset))
{
$records[] = $r;
}
echo json_ecode($records);
echo $resultset;
}
}
?>
Based on the question:
use mysqli_connect rather than mysql_connect because mysql_connect is deprecated and will not work someday. Also what is the the error you are getting? change your die() statement to something more helpful die(mysqli_error($connection));
Based on your comment:
That error would suggest that you either A) don't have the right IP address or B) there is a network issue between your host server and the SQL server, is this code running on the same server that is hosting the SQL database? if so then you can probably just use localhost for your $host

Categories