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";
?>
Related
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.
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
Can any one explain the connection string from the parameters below:
server IP : 192.168.137.4
Windows Authentication : Windows Authentication
UserName : DELL-M102Z\dell
Database : DataProd
Network Protocol : <default>
Product Name : Microsoft SQL Server Express Edition
Server Name : DELL-M102Z\SQLEXPRESS
Instance Name : SQLEXPRESS
Computer Name : DELL-M102Z
I tried:
$serverName = "DELL-M102Z\SQLEXPRESS"; //serverName\instanceName
$username = "DELL-M102Z\dell"; //serverName\instanceName
$conn = mssql_connect( $serverName,$username,'');
...but the result I got was:
Warning: mssql_connect() [function.mssql-connect]: Unable to connect to server: DELL-M102Z\SQLEXPRESS in C:...\index.php on line 17
Connection could not be established.
Can anyone tell me what is the problem here?
trying to follow this step:
http://michaelellerbeck.com/2010/03/31/cant-connect-remotely-to-sql-server-2008/
i know that i miss to activate sql browser service, and that's why i cannot connect by remote IP,
I got conclusion from that site and i must make sure that:
1. make sure you have allow network connection from sql server configuration tool
2. allow connection for this port in firewall
3. activate sql browser service
4. make sure port is listen as the the service provide
i got problem for no.3 and i'm stuck on it, this site solve the problem:
http://www.wikihow.com/Enable-Remote-Connections-SQL-2008-Express
<?php
$myServer = 'xxx.xxx.xxx.xxx:yyyy';
$myUser = 'sa';
$myPass = 'xxxxx';
$con = mssql_connect($myServer, $myUser, $myPass) or die("Could not connect to database: ".mssql_get_last_message());
if($con){
echo "connected";
}
// Select a database:
mssql_select_db('new')
or die('Could not select a database.');
// Example query: (TOP 10 equal LIMIT 0,10 in MySQL)
$SQL = "SELECT TOP 10 * FROM Table";
// Execute query:
$result = mssql_query($SQL)
or die('A error occured: ' . mysql_error());
// Get result count:
$count = mssql_num_rows($result);
print "Showing $count rows:<hr/>\n\n";
// Fetch rows:
while ($Row = mssql_fetch_assoc($result)) {
print $Row['BillNo'] . "\n";
}
mssql_close($con);
$myServer = 'IP_Address:PORT';
Here semicolon is need to ip and port
and
Mssql is enbaled at your cpanel
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';
Why do I get a "mysql_query(): supplied argument is not a valid" for the first...
$r = mysql_query($q, $connection);
In the following code...
$bId = trim($_POST['bId']);
$title = trim($_POST['title']);
$story = trim($_POST['story']);
$q = "SELECT * ";
$q .= "FROM " . DB_NAME . ".`blog` ";
$q .= "WHERE `blog`.`id` = {$bId}";
$r = mysql_query($q, $connection);
//confirm_query($r);
if (mysql_num_rows($r) == 1) {
$q = "UPDATE " . DB_NAME . ".`blog` SET
`title` = '{$title}',
`story` = '{$story}'
WHERE `id` = {$bId}";
$r = mysql_query($q, $connection);
if (mysql_affected_rows() == 1) {
//Successful
$data['success'] = true;
$date['errors'] = false;
$date['message'] = "You are the Greatest!";
} else {
//Fail
$data['success'] = false;
$data['error'] = true;
$date['message'] = "You can't do it fool!";
}
}
I also get an "mysql_num_rows(): supplied argument is not a valid MySQL result resource" error too.
Side notes: I am using 1&1 Hosting (worst hosting ever), custom .htaccess file with one line text to enable PHP 5.2 (only way with 1&1 Hosting).
Extra stuff add after the questions was posted...
Here is how $connection is defined. It is on its own page called connection.php that is called up using the require_once function. It it is called up on every page that require a database connection including the one in question...
$connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
die("Database Connection Failed: </br>" . mysql_error());
}
$db_select = mysql_select_db(DB_NAME,$connection);
if (!$db_select) {
die("Database Selection Failed: </br>" . mysql_error());
}
... I know it is working because this the same connect that I use for the page I have and I have no problems with it. I havent testing on my home server yet, but I am going to later to see if it is related to a 1&1 Hosting issue.
UPDATE: I am in the process of moving from 1&1 Hosting to HostMoster. 1&1 runs a PHP as CGI and runs PHP4 instead of PHP5 (you can make a custom .htaccess file to make it run PHP5). I will update you later.
The first would be because it's not a connection, and the second would be because it's not a query result because it wasn't a connection. Use mysql_error() to figure out what went wrong in the connection.
My guess is that $connection has not been properly opened. You should have a line like:
$connection = mysql_error($server, $user, $pass);
Also check mysql_error() to see the reason why it's failing.
I think that cletus meant to suggest that you need to have a mysql_connect() instead of mysql_error() before you attempt to perform a mysql_query(). It will probably look like this (with the exception that 1and1 may have given you a specific hostname to connect to for your database which you should use in place of localhost below):
//Make sure this goes before any of your other mysql_* functions
$connection = mysql_connect('localhost', 'yourUserName', 'yourPassword');
Passing $connection around for each of your queries isn't really necessary unless you have multiple database connections open concurrently that you are using and need to make sure to differentiate between the two when making query calls. Otherwise, mysql_query assumes that you are using the last database that you connected to.
Also, for security purposes as mentioned by Frank you should use mysql_real_escape_string() like so:
$q = "SELECT * ";
$q .= "FROM " . DB_NAME . ".`blog` ";
$q .= "WHERE `blog`.`id` = ".mysql_real_escape_string($bId).";
Tested on my local system (via WAMP), I had no problems. At the time when I had problems, I was using 1&1 Hosting. 1&1 Hosting run PHP as CGI, which probably cause my problems. I couldnt handle allof the crap with 1&1 and switch to HostMonster. Now, I don't any issues. Plus, I rather use cPanel over 1&1's admin panel.