Microsoft Azure for MySQL can't connect to DB using PHP - php

Goodmorning to all,
I'm trying to connect to my Azure server for MySQL using php but it gives me an error. The php file runs every day at 00:00 on a server where my website is hosted and must connect to the azure DB to run queries on the Azure DB.
The error I get is "connection timed out" i've tried to add in my firewall the rule with the ip of my server with the sample command: " az mysql server firewall-rule create --resource-group myresourcegroup --server mydemoserver --name AllowMyIP --start-ip-address 192.168.0.1 --end-ip-address 192.168.0.1 " obviously changing the values but it fails...
I attach the code below:
$conAzure = mysqli_init();
mysqli_ssl_set($conAzure, NULL, NULL, "pathToSSLCert",NULL, NULL);
mysqli_real_connect($conAzure, "test.mysql.database.azure.com", "test#test", "test", "proj_sophie", 3306, MYSQLI_CLIENT_SSL);
// Check connection
if ($conAzure->connect_error) {
// THE PROGRAM STOPS HERE
die("Connection failed: " . $conAzure->connect_error);
}
echo "Connected successfully";
$sqlAzure1 = "TRUNCATE TABLE elenco_post;";
if ($conAzure->query($sqlAzure1) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sqlAzure1 . "<br>" . $conAzure->error;
}
// inserting in the selected table and fields the data (it's in a for-each so don't worry for the repetitions).
$sqlAzure2 = "INSERT INTO elenco_post ('ID', 'Titolo', 'Contenuto', 'Data', 'URL', 'Ultima_Modifica', 'URL_Immagine', 'Nome_immagine', 'Categoria') VALUES ('".get_the_ID()."',
'".get_the_title()."',
'".get_the_content()."',
'".get_the_date()."',
'".get_permalink()."',
'".get_the_modified_date()."',
'".get_the_post_thumbnail_url(get_the_ID(),'full')."',
'".get_post(get_post_thumbnail_id())->post_title."',
'".$category."');";
if ($conAzure->query($sqlAzure2) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sqlAzure2 . "<br>" . $conAzure->error;
}
Thank you, waiting for support!

--start-ip-address 192.168.0.1
This looks very improbable for a client address running in Azure. Where is your PHP running? I suspect you are running it on a home PC in a masqueraded LAN - in which case that's not the IP address which is connecting to Azure, merely the address you use to connect to your router.
Try https://whatismyipaddress.com/ to find out what your address is right now - but if I'm right, it will change regularly.

Related

Mysql database connection file errors

I am on an Amazon ec2 instance and I have a database that I am trying to access via a PHP script. I am echoing out tests through the script so i seem to get to the end but I am not getting any errors. Whenever I change my localhost to my IP it says: Connection error: Can't connect to MySQL server on 'MY IP' (110). I have tried binding my localhost and server server IP to my.cnf file and still the same result. Are there any other configurations I am missing? I have never had this much trouble before but this is my first time working on an amazon ec2 Linux instance.
<?php
$con=mysqli_connect("localhost","root","password","database");
if (!$con)
{
die("Connection error: " . mysqli_connect_error());
}
echo "testing1";
$query = "SELECT id, email FROM user_key ORDER BY email DESC LIMIT 10;";
echo "here";
$result = mysql_query($query);
echo "here2";
while($row = mysql_fetch_assoc($result))
{
echo $row['id']." ";
echo $row['email']." ";
}
echo "last";
?>

PHP mysqli_query won't execute

I'm trying to write my first basic PHP RESTful API - I managed to get it working on my local machine using MAMP. But when I uploaded to hosting server, it doesn't want to work.
Code below - I've added some ECHO's in there to make sure things are working along the way. It seems like we're all good up until the $result=mysqli_query.
<?php
//header('Content-type:application/json');
// Connect to db
$con = mysqli_connect("HOSTNAME","USER","PASSWORD","DATABASE");
echo "Database: ";
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
echo "Connected successfully";
echo "<br><br>";
// Get value from url
$bid = $_GET['bid'];
echo "BID: ";
echo $bid;
echo "<br><br>";
// Define Query
$sql = "SELECT id, bandname, members, bio, songlist FROM bands WHERE id='$bid'";
echo "SQL Query: ";
echo $sql;
echo "<br><br>";
// Run Query
$result = mysqli_query($con, $sql);
echo "Result: ";
print_r($result);
echo "<br><br>";
// Put Query result into array
$result_array = mysqli_fetch_array($result, MYSQLI_ASSOC);
echo "Result Array: ";
print_r($result_array);
echo "<br><br>";
// Encode array as JSON and output
echo "JSON: ";
echo json_encode($result_array);
?>
The url I'm entering is http://bandsly.com/api.php?bid=1 and this is the output I'm getting in the browser...
Database: Connected successfully
BID: 1
SQL Query: SELECT id, bandname, members, bio, songlist FROM bands WHERE id='1'
Result:
Result Array:
JSON: null
When I manually run the query SELECT id, bandname, members, bio, songlist FROM bands WHERE id='1' in the database (PHPmyadmin), it works fine and I get 1 row returned with the correct values.
The manual db query result:
(http://i.stack.imgur.com/d3ZPJ.png)
Any help would be most appreciated!!
*****EDIT*****
OK, i think i found the issue... My "successfully Connected" wasn't written correctly, and always came back looking good. It looks like after fixing that, i have db connection issues.
I'm going to go look up the db connection settings and try and fix that.
Thanks all for your help!
Your code seems to be ok on my localsystem http://www.awesomescreenshot.com/image/494275/c6c255cd6924d07196076b32489489de. There should be a connection problem . so you can do some try to check connection like
check the details in
// Connect to db
$con = mysqli_connect("HOSTNAME","USER","PASSWORD","DATABASE");
and then you can try to ping database
/* check connection */
if ($con->connect_errno) {
printf("Connect failed: %s\n", $con->connect_error);
exit();
}
/* check if server is alive */
if ($con->ping()) {
printf ("Our connection is ok!\n");
} else {
printf ("Error: %s\n", $con->error);
}
Your all code is correct, I have tested in my local just change your
HOSTNAME like "localhost", USER like "root", PASSWORD like "your password", DATABASE like "YOUR DATABASE NAME".
$con = mysqli_connect("HOSTNAME","USER","PASSWORD","DATABASE");
please, visit http://php.net/manual/en/function.mysqli-connect.php

Php web application can't process clearDB mysql service on bluemix

I'm trying to deploy a php web application on bluemix. So I have bound a clearDB mysql service to my application. The vcap_service variable are provided to me. but when I use those variable to perform simple sql query, the application page does nothing, while same code is doing well with xamp localhost.
please help me.
here is the code :
<?php
$servername = "us-cdbr-iron-east-02.cleardb.net";
$username = "b23807********";
$password = "********";
$dbname = "ad_70723170af1****";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "CREATE TABLE flybird (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
if ($conn->query($sql) === TRUE) {
echo "Table flybird created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
The following error is showing:
Got error 'PHP message: PHP Fatal error: Class 'mysqli' not found in /home/vcap/app/htdocs/table.php on line 8\n.
There is an issue with the php buildpack, you need to explicitly add the mysqli function in your application.
Create a file called .bp-config/options.json. You can customize the php buildpack extensions, check this out for more info.
The contents should contain the following.
{
"PHP_EXTENSIONS": ["mysqli"]
}
you should specify mysqli dependency on composer.json config.
{"require": {
"ext-mysqli": "*"
}
}
I think you need to explicitly add the mysqli function in your application
You have to enable the library in .bp-config/options.json file. Like the example below
EX:
{
"PHP_EXTENSIONS": ["mysqli"]
}
If you don't have this file in your aplication just create it, add the extension and push it to your Bluemix app. (link)
Check this page on developerworks for more information , i think it is the same issue you are having (link)

Table exists in PHPmyAdmin but does not appear using SHOW TABLES query in PHP

I am a new user to stackoverflow, I did do a search for similar questions and I found a many, but none were resolved in a way that helped me. So that's why I'm asking this even though it may be a duplicate. (This one for example seems to be the same problem I'm having: MySQL table exists on server but cannot access it from PHP)
I created a table (members) in my database (test) using PHPmyAdmin. If I do an SQL query there to SHOW TABLES FROM test, the table "members" is listed. However, PHP does not seem to be able to access it. This is my file access_test_table.php:
<html>
<body>
Testing.<br>
<?php
$host="localhost"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="test"; // Database name
$tbl_name="members"; // Table name
echo "The host is $host<br/>";
echo "The username is $username<br/>";
echo "The password is $password<br/>";
echo "The db name is $db_name<br/>";
echo "The table name is $tbl_name<br/>";
// Connect to server and select databse.
$con=mysqli_connect("$host","$username","$password","$db_name");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
echo "<br/>";
}
else {
echo "Connected to database.<br/>";
}
//Want to show the tables in the database
$query_1="SHOW TABLES FROM $db_name'";
$result_q1 = mysqli_query($con,$query_1);
if (!mysqli_query($con,$query_1))
{
echo("Errorcode: " . mysqli_errno($con));
echo "<br/>";
}
else {
echo "The following tables are in the database: " . $result_q1;
echo "<br/>";
}
mysqli_close($con);
echo "Connection closed.";
?>
</body>
</html>
I checked that "username" is the same user as was used to create the table and has the right permissions to access it. I also updated to using no mysql_* commands but rather mysqli_* ones. Finally, I tried using mysqli_multi_query, but the result is the same. This is the output of the code on the page:
Testing.
The host is localhost
The username is username
The password is password
The db name is test
The table name is members
Connected to database.
Errorcode: 1064
Connection closed.
Can someone suggest to me how I can fix this? Thanks!
Remove the ' from the Query:
$query_1="SHOW TABLES FROM $db_name'";
So it looks like this:
$query_1="SHOW TABLES FROM $db_name";
Credits to Fred (Posted as Community Wiki to close the Question)

Accesing XAMPP MySql Database from Another Computer

So a friend of mine and I are using both xampp on ubuntu, if that helps, to connect between each other's website, We both created the same php file to connect, so we use de IP of the other, but then it says an error
Warning: mysql_connect() [function.mysql-connect]: Host 'coke-laptop.local' is not allowed to connect to this MySQL server in /opt/lampp/htdocs/connection.php on line 2
Could not connect: Host 'coke-laptop.local' is not allowed to connect to this MySQL server
We have this code on the connection.php file:
<?php
$link = mysql_connect('10.100.161.37','root','');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//echo 'Connected successfully';
$db_selected = mysql_select_db('Prueba', $link);
if (!$db_selected) {
die ('Can\'t use Prueba : ' . mysql_error());
}
// This could be supplied by a user, for example
$firstname = 'fred';
$lastname = 'fox';
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT * FROM Agencia");
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
echo $row['ID'] . " ";
echo $row['Nombre'] . "\n\r";
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
mysql_close($link);
?>
If we use the IP just like that, we can enter each others xampp normal welcome page.
Check you have enabled remote access to the MySQL server. Open the my.cnf file (probably found inside xampp/etc/), go to the [mysqld] section and add the following (using your own ip address instead of the example)
bind-address=192.168.1.100
If there is a line that says skip-networking, comment that out so it looks like this:
# skip-networking
then restart the MySQL server
It looks like your MySQL database isn't allowing you to connect remotely with the credentials you provided. You will need to configure a remote user to connect. Try looking into MySQL Grants.
For Example:
GRANT SELECT, INSERT ON database.* TO 'someuser'#'somehost';

Categories