I'm trying to connect to my Azure sql database using following code:
<?php
//Constants to connect with the database
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'pass');
define('DB_HOST', 'xyz-server.database.windows.net');
define('DB_NAME', 'xyz_db');
<?php
//Class DbConnect
class DbConnect
{
//Variable to store database link
private $con;
//Class constructor
function __construct()
{
}
//This method will connect to the database
function connect()
{
//Including the constants.php file to get the database constants
include_once dirname(__FILE__) . '/Constants.php';
//connecting to mysql database
$this->con = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
//Checking if any error occured while connecting
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//finally returning the connection link
return $this->con;
}
}
I'm getting this error
Type: ErrorException
Code: 2
Message: mysqli::__construct(): (HY000/9002): The connection string may not be right. Please visit portal for references.
File: /home/site/wwwroot/blingoo/include/DbConnect.php
Line: 22
I'm just beginning with Azure. Maybe I'm missing something. If you could simply point how to connect my database and web app(where I'm using php files to connect to the database), that will be great.
Seems to me that your code is trying to connect to MySQL rather than MSSQL.
To connect to MSSQL use the following:
<?php
$serverName = "your_server.database.windows.net"; // update me
$connectionOptions = array(
"Database" => "your_database", // update me
"Uid" => "your_username", // update me
"PWD" => "your_password" // update me
);
//Establishes the connection
$conn = sqlsrv_connect($serverName, $connectionOptions);
$tsql= "SELECT TOP 20 pc.Name as CategoryName, p.name as ProductName
FROM [SalesLT].[ProductCategory] pc
JOIN [SalesLT].[Product] p
ON pc.productcategoryid = p.productcategoryid";
$getResults= sqlsrv_query($conn, $tsql);
echo ("Reading data from table" . PHP_EOL);
if ($getResults == FALSE)
echo (sqlsrv_errors());
while ($row = sqlsrv_fetch_array($getResults, SQLSRV_FETCH_ASSOC)) {
echo ($row['CategoryName'] . " " . $row['ProductName'] . PHP_EOL);
}
sqlsrv_free_stmt($getResults);
?>
source: https://learn.microsoft.com/en-us/azure/sql-database/sql-database-connect-query-php
Since you are trying to connect to Azure SQL you can use PDO_DBLIB driver, if you have this extension installed. See php -m.
$config = [
'dsn' => 'dblib:host=xyz-server.database.windows.net;dbname=xyz_db',
'user' => 'username',
'pass' => 'password',
];
$connection = new PDO($config['dsn'], $config['user'], $config['pass']);
$sth = $connection->prepare('Your query comes here;');
$sth->execute();
$rows = $sth->fetchAll(PDO::FETCH_CLASS);
foreach ($rows as $row) {
// Do the processing here
}
Related
This script
<?php
/* Connect to a MySQL database using driver invocation */
$dsn = 'mysqldg';
$user = 'odbc_dg';
$password = '999999999';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
gives the error *Connection failed: invalid data source name*
I have created an entry in /etc/odbc.ini as follows:
[mysqldg]
Description = DGDB
Driver = mysql537
Database = dg1
Servername = 99.99.99.99
UID = odbc_dg
PWD = 999999
SSLKeyFile = /etc/mysql/ssl/ck.pem
SSLCertFile = /etc/mysql/ssl/cc.pem
SSLCAFile = /etc/mysql/ssl/c1.pem
/etc/odbcinst.ini has the following entry:
[mysql537]
Description = MySQL driver for Plesk
Driver = /usr/lib/odbc2/lib/libmyodcb5w.so
Setup = /usr/lib/odbc2/lib/libmyodbc5w.so
The entry in odbcinst.ini works with a non-DSN connection.
I'm obviously missing something, can anyone help? Thanks.
UPDATED....
I have tried Your Common Sense's code as follows:
<?php
$host = '46.99.199.199';
$db = 'dg';
$user = 'odbc_dg';
$pass = '999999';
$charset = 'utf8mb4';
$options = array(
PDO::MYSQL_ATTR_SSL_KEY => '/etc/mysql/ssl/ck.pem',
PDO::MYSQL_ATTR_SSL_CERT => '/etc/mysql/ssl/cc.pem',
PDO::MYSQL_ATTR_SSL_CA => '/etc/mysql/ssl/c1.pem'
);
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
... but I get a connection fail message - Connection failed: SQLSTATE[HY000] [2002]
I think the problem is that the keys I have supplied only work with ODBC
For example this code, which uses odbc_connect works....
<?php
ini_set ('error_reporting', E_ALL);
ini_set ('display_errors', '1');
error_reporting (E_ALL|E_STRICT);
$user = "odbc_dg";
$pass = "99999";
$connection = "Driver= {mysql537};Server=46.99.199.199;Database=dgdb;UID=dgdb;PWD=999999;sslca=/etc/mysql/ssl/c1.pem;sslkey=/etc/mysql/ssl/ck.pem;sslcert=/etc/mysql/ssl/cc.pem";
$con = odbc_connect($connection, $user, $pass);
$sql="SELECT Id from stk_item";
$rs=odbc_exec($con,$sql);
if (!$rs) {
exit("Error in SQL");
}
echo "<table><tr>";
echo "<th>Companyname</th>";
echo "<th>Contactname</th></tr>";
while (odbc_fetch_row($rs)) {
echo odbc_result($rs, "Id"), "\n";
}
odbc_close($con);
echo "</table>";
?>
My problem is that I want to connect to the remote database via pdo because that's the only type of connection allowed in the Drupal synchronising code.
I am trying to access a database on my web host with a php file that is on the same server. When trying to load the page I get the following error: mysql_connect(): Lost connection to MySQL server at 'reading initial communication packet', system error: 111. I cannot find a good answer what it going wrong. Below is my php that I am using. I have my IP address of my database set as my host name.
<?php
$con = mysql_connect("10.123.0.209:3306","username", "password");
if (!$con){
die("cannot connect: " . mysql_error());
}
mysql_select_db("matmac78_macy", $con);
$sql = "SELECT * FROM countries";
$mydata = mysql_query($sql, $con);
while ($record = mysql_fetch_array($mydata)){
echo $record['country'] . " " . $record['population']
echo"<br/>";
}
mysql_close($con);
?>
Any help would be greatly appreciated!
You should switch to using PHP's PDO connection protocol.
$username = 'username';
$password = 'password';
$dbName = 'matmac78_macy';
$host = '10.123.0.209:3306';
try {
$this->database = new \PDO( "mysql:host={$this->host};dbname={$this->dbName}", $this->username, $this->password );
$this->database->setAttribute( \PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION );
$this->database->setAttribute( \PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC );
return $this->database;
} catch (\PDOException $e) {
throw new \Exception( "Could not establish database connection. \n" ); #Push error message
}
I am trying to sent data to the server database, i implement it using wamp server it was working fine but when i installed the db on my domain and switched it to my domain its giving the following error.
I have kept my files inside a folder in root directory
Unknown MySQL server host 'DB_HOST' (0)
Below is my config file i am using to connect to the db
<?php
// Database configuration
define('DB_USERNAME', 'user');
define('DB_PASSWORD', 'xxxx');
define('DB_HOST', '192.210.195.245');
define('DB_NAME', 'tabanico_userlogin');
?>
here my code connecting db, config.php file contains the code pasted above
<?php
class DbConnect {
private $conn;
function __construct() {
// connecting to database
$this->connect();
}
function __destruct() {
$this->close();
}
function connect() {
include_once dirname(__FILE__) . './Config.php';
$this->conn = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
mysql_select_db(DB_NAME) or die(mysql_error());
// returing connection resource
return $this->conn;
}
// Close function
function close() {
// close db connection
mysql_close($this->conn);
}
}
?>
and my file receiving data
<?php
include_once './DbConnect.php';
function createNewPrediction() {
$response = array();
$id = $_POST["id"];
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
$db = new DbConnect();
// mysql query
$query = "INSERT INTO login(id,name,email,password) VALUES('$id','$name','$email','$password')";
$result = mysql_query($query) or die(mysql_error());
if ($result) {
$response["error"] = false;
$response["message"] = "Prediction added successfully!";
} else {
$response["error"] = true;
$response["message"] = "Failed to add prediction!";
}
// echo json response
echo json_encode($response);
}
createNewPrediction();
?>
I have seen related post but didn't find useful answers. Can anyone help me in getting out of this. Thanks in advance.
Please post the code where you try to connect to the server. I guess you tried to connect using the following function:
mysql_connect('DB_HOST', 'DB_USERNAME', 'DB_PASSWORD');
Since you defined the host using define('DB_HOST', 'localhost');, you do not have to use apostrophes. DB_HOST is a constant here. So try to use to
mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD);
instead. If you use apostrophes like in 'DB_HOST', it is interpreted as a string instead of the value of the constant DB_HOST containing localhost. That's a possible reason why you get the error that DB_HOST is an unknown host.
But please post the connection part of your code to see if that's really the mistake.
I'm able to connect to my Cloud SQL through Desktop MySQL software, but now I'm trying to connect to the Database via PHP.
I have a PHP subdomain which does the server requests to MySQL, the PHP is live on a web accessible website whilst I work on an AngularJS project locally via localhost:9000
define("DB_HOST", "[my ip]:3306");
define("DB_NAME", "db");
define("DB_USER", "user");
define("DB_PASS", "pass");
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (!$db) {
die('Could not connect: ' . mysql_error());
} else {
echo 'Connected';
}
So if I check my PHP page I see that page displays Connected but my MySQLi queries are failing.
I have a simple GET which returns empty
$q = $db->query("SELECT * FROM items");
$items = array();
while($r = mysqli_fetch_array($q)) {
$item = array(
'id' => $r['id'],
'item_id' => $r['item_id'],
'name' => $r['name'],
'json' => $r['json']
);
array_push($items, $item);
}
Usually you need to set your PHP with the first line with this:
header('Content-Type: text/html; charset=utf-8');
I am new to php development.I have created a database using phpmyadmin.Now i want all the data to be displayed on the page.But when ever i try to run the file nothing is showing up.I dont know why this is happening.
db_config.php
<?php
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "moviesreview"); // database name
define('DB_SERVER', "localhost"); // db server
$con = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if($con->connect_errno > 0) {
die('Connection failed [' . $con->connect_error . ']');
}
db_connect.php
<?php
/**
* A class file to connect to database
*/
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysqli_error($con));
// Selecing database
$db = mysqli_select_db($con,DB_DATABASE) or die(mysqli_error()) or die(mysqli_error($con));
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
}
}
?>
Code
<?php
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
$con=new db_connect();
$strQuery="SELECT * FROM `moviesdetails WHERE `recent_upcoming` =0";
$result=mysqli_query($con,$strQuery);
while($row=mysqli_fetch_array($result)){
$row_array['movies_id']=$row['movies_id'];
$row_array['movies_name']=$row['movies_name'];
$row_array['movies_description']=$row['movies_description'];
$row_array['movies_time']=$row['movies_time'];
$row_array['movies_release_date']=$row['movies_release_date'];
$row_array['movies_youtube_link']=$row['movies_youtube_link'];
$row_array['recent_upcoming']=$row['recent_upcoming'];
$row_array['movies_image']=$row['movies_image'];
$row_array['movies_actors']=$row['movies_actors'];
array_push($response,$row_array);
}
echo json_encode($response);
?>
Error what i am getting
There are a few things wrong with your code.
The space between <? and php
A missing tick for your table, and a missing semi-colon for your query.
A missing DB connection link.
Your code:
<? php
^ space
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
$strQuery="SELECT * FROM `moviesdetails WHERE `recent_upcoming` =0"
^ ^
$result=mysqli_query($strQuery);
^ no DB connection
<?php
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
$strQuery="SELECT * FROM `moviesdetails` WHERE `recent_upcoming` =0";
$result=mysqli_query($con,$strQuery);
Using error reporting http://php.net/manual/en/function.error-reporting.php would have signaled that, including or die(mysqli_error($con)) to mysqli_query()
You've edited your question. You are mixing mysqli_ and mysql_ functions. They do not mix.
All mysql_error should be mysqli_error($con) and mysql_close() to mysqli_close($con)
Edit:
Replace the entire contents of db_connect.php with the following:
<?php
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "moviesdetails"); // database name
define('DB_SERVER', "localhost"); // db server
$con = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if($con->connect_errno > 0) {
die('Connection failed [' . $con->connect_error . ']');
}
Edit #2:
while($row=mysqli_fetch_array($result)){
$response[] = $row;
$row['movies_id'];
$row['movies_name'];
$row['movies_description'];
$row['movies_time'];
$row['movies_release_date'];
$row['movies_youtube_link'];
$row['recent_upcoming'];
$row['movies_image'];
$row['movies_actors'];
}
echo json_encode($response);
You have missing connection link as parameter in your mysqli_query() function. Should be:
$result = mysqli_query($connection_link, $strQuery);
http://php.net/manual/en/mysqli.query.php
$connection_link will have in this case following format:
// include db connect class
require_once __DIR__ . '/db_connect.php';
$connection_link = new DB_CONNECT();
But as #Fred -ii- said in comments, you have some syntax errors in PHP and SQL query too.
Your DB class is badly designed, you should store connection link in property and making queries through this class.