Connecting PHP to Cloud SQL - php

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');

Related

How to know if MySQL is using SSL to connect to a remote database?

Here is my code to connect to my remote DB:
$con = mysqli_init();
mysqli_ssl_set($con, "/etc/letsencrypt/keys/...certbot.pem", "/etc/letsencrypt/live/.../cert.pem", "/etc/letsencrypt/live/.../fullchain.pem", NULL, NULL);
$connection = mysqli_real_connect($con, self::$host, self::$user, self::$password);
self::$lastConnection = $connection;
$db = "db_prod";
Unfortunately, I cannot tell if it's actually working because if I intentionally mispell any of the characters for my certificates in mysqli_ssl_set, the connection is still successful. So how can I know for sure that this is working as intended?
Any help appreciated.
Since you have used mysqli_ssl_set to try establishing SSL connection to MySQL. The system will proceed to use it for subsequent connection request.
Hence, You may check the $connection which is the return value of mysqli_real_connect
So please amend to:
<?php
$con = mysqli_init();
mysqli_ssl_set($con, "/etc/letsencrypt/keys/...certbot.pem", "/etc/letsencrypt/live/.../cert.pem", "/etc/letsencrypt/live/.../fullchain.pem", NULL, NULL);
$connection = mysqli_real_connect($con, self::$host, self::$user, self::$password);
/////////////////
if (!$connection)
{
die("Connect Error: " . mysqli_connect_error());
}
/////////////////
self::$lastConnection = $connection;
$db = "db_prod";
?>

Separating database config from connection

I'm trying to make a connection to the database while having the database config information saperated from the connection.
This is the code I wrote
db config information:
$config = array(
"database" => array(
"host" => "host",
"username" => "username",
"password" => "password",
"name" => "name",
)
);
define("databse_config", $config["database"]);
$config normaly also contains other information not relevant to the question ,that is why I have defined "database_config".
database connection:
require_once "config.php";
define("DB_HOST", databse_config['host']);
define("DB_USERNAME", databse_config['username']);
define("DB_PASSWORD", databse_config['password']);
define("DB_NAME", databse_config['name']);
function connect()
{
$dbhost = DB_HOST;
$dbuser = DB_USERNAME;
$dbpass = DB_PASSWORD;
$dbname = DB_NAME;
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$conn->exec("set names utf8");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
connect();
The problem I keep running in to is that wile trying to execute the function the page keeps loading and eventualy outputs the following error:
Connection failed: SQLSTATE[HY000] [2002] Connection timed out
I'm fairly new to PDO so I also tried the same while using mysqli, which gave the same result.
Any help would be appreciated.
Connection failed: SQLSTATE[HY000] [2002] Connection timed out
This means php tried to establish a TCP/IP connection to your database server AND FAILED. You provided a DB_HOST hostname that's unreachable by network from the location of your php program.
The hostname value could be missing, or it could be wrong. If you provided it by name (mysql-server.example.com), this error message tells you the DNS name lookup succeeded.
So your php sends out a request to the server for a TCP/IP connection. That request never gets a response. That means there's a firewall somewhere blocking the connection, or that there's no network route from your php program to the network.
This all means the $dbhost value is wrong in your new PDO() operation.
Your code could be simplified a lot like this with no loss of modularity. sprintf() helps. Simpler is better for troubleshooting.
require_once "config.php";
function connect()
{
try {
$connectionString = sprintf ("mysql:host=%s;dbname=%s",
database_config['host'],
database_config['name']);
$conn = new PDO($connectionString,
database_config['username'],
database_config['password']);
$conn->exec("set names utf8");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
connect();
And you can echo $connectionString; to see what's in it, and make sure it isn't something bizarre.

Connect to Azure Database using Azure Web App

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
}

How to connect to database file to extract the data? [duplicate]

This question already has answers here:
How to connect to a SQLite3 db with PHP
(3 answers)
Closed 5 years ago.
I need some help with my PHP code. I want to connect to the database file called myChannel.db to extract the data from the rows, but I have got no idea how to do that by using this code:
Here is the config:
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'myusername');
define('DB_PASSWORD', 'mypassword');
define('DB_DATABASE', 'mydbname');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link)
{
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db)
{
die("Unable to select database");
}
?>
Here is the get-listing.php script:
<?php
$errmsg_arr = array();
$errflag = true;
$link;
//Connect to the database
require_once('config.php');
$qrytable1="SELECT id, channels, programme_title, programme_description, programme_start_date, programme_end_date FROM tvguide WHERE channels='$channels' && id='$id'";
$result1 = mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
while ($row = mysql_fetch_array($result1))
{
//output the data for channels, programme_title, programme_description, programme_start_date, programme_end
}
?>
The code will only allow me to connect to mysql and nothing is else.
Can you please show me an example how I could connect to myChannel.db and extract the data from the columns called channels, programme_title, programme_description, programme_start_date, programme_end where the channels is matched?
You asked for an example... this was my solution for querying geocoordinates from mySQL database. I call all of this in my php file...
//set up a MySQL query, this is the data you are asking for. This asks for all data from tabele 'shelters'. Be sure to call your specific table.
$sql = "SELECT * FROM shelters;";
if(!$results = $link->query($sql)){
die("Query Unsuccessful");
}
//Here I create a value map and pull out the results I care about from my request query.
$valueMap = array();
while ($data = $results->fetch_assoc()){
$valueMap[] = array(
'title' => $data['title'],
'lat' => $data['lat'],
'lng' => $data['lng'],
);
}
//encoding it into JSON is more manageble for me, but you will have to parse it into a javascript object in your index file.
$JSONData = json_encode($valueMap);
//heere you want to echo your data in order to retrieve it in your index file. Has the functionality of connecting to an API
echo $JSONData;
Hit me up in the comments with any more specific questions.

Error when trying to access database on server: Lost connection to MySQL server

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
}

Categories