How to connect to mysql database with php? - php

I'm using Jetbrains and Mysql to work on this practical project, but when I connect to the mysql
database it gives me the following error:
C:\wamp64\bin\php\php5.6.40\php.exe C:\wamp64\www\Social_Network\Includes\connection.php
Connection failed: SQLSTATE[HY000] [1049] Unknown database 'social_network'
Process finished with exit code 0
I made sure several times that the database name is the same name and there are
no spelling errors at all (I copy pasted it from the database)
Here's my code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=social_network", $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();
}
//?>

Welll, there's little that can be done about it. MySQL thinks that the database does not exist.
is the server the correct one?
is the case sensitivity set correctly? "Social_Network" and "social_network" might be considered different.
can you access the database with those parameters using a different tool (e.g. HeidiSQL, SQLYog, SQLterm, in a pinch even phpMyAdmin)?
Actually, JetBrains PHPStorm has a SQL terminal utility that can diagnose the connection. You may want to use it (once it knows what database you're connecting to, it will also warn you of several possible errors such as using the wrong table name or column name).

Related

PHP Read local .sq3 file for use on webpage

I have a local file (tf2stats.sq3) stored on my web server that includes name and points of players like so: https://i.imgur.com/u42zxha.png
My intention is to get the top 10 entries for POINTS and display them on a webpage as a leaderboard.
I can't find any examples on reading a .sq3 database without first connecting to a server.
Here's one of them:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $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();
}
?>
The problem is that the game server with the database does not have mySQL set up, so I planned on periodically downloading the file over FTP and reading it locally.
Right now I have the files stored on a directoy of my website: https://i.imgur.com/yPHbWIm.png
I have php-mysql and php7.0-mysql packages installed on my web server which is using php7.0 - so far every attempt I've made to read the db gives me "No such file or directory"
I'm very new to php and sql, any help is greatly appreciated.

Cant get php to connect to sql. Get error Connection failed: php_network_getaddresses: getaddrinfo failed: No such host is known.

I have scoured google, and stackover flow, and just cant get to the bottom of this issue. I cannot get the following php code to connect to SQL. Its a simple php web document, that i am using to test out some things. SQL is sqlexpress 2016, and its running on IIS with php 7.x installed. PHP code executes fine, so its something with the code or the database is my guess. Things I've tried:
I've ran an echo in php to resolve the name, and it resolves it fine.
I've connected from a separate server to the sql server using tcp, and it connects fine.
I've tried both PDO connection, and mysqli and both come back with same error.
The PDO code ive used is:
<?php
$servername = 'RemoteServerName\SqlInstance';
$username = 'iislogon';
$password = 'password';
try {
$conn = new PDO("mysql:host=$servername;dbname=netdata", $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();
}
?>
The mysqli code is:
<?php
$servername = 'RemoteServerName\SqlInstance';
$username = 'iislogin';
$password = 'password';
$dbname = 'netdata';
?>
<?php $conn = new mysqli($servername, $username, $password, $dbname); ?>
<?php
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";?>
Both return the same error of host not found. What other issues could be causing this? Im new to coding php so any help would be appreciated.
mysqli and PDO starting with mysql: are supposed to connect to MySQL, not SQLExpress.
If you want to use SQLExpress you should use something like sqlsrv_connect or adjust your pdo string to a SQLExpress compatible one.
Take a look at this thread too.
Look at this description http://php.net/manual/en/pdo.construct.php and specifically:
In general, a DSN consists of the PDO driver name, followed by a colon, followed by the PDO driver-specific connection syntax. Further information is available from the PDO driver-specific documentation.
Are you sure your dsn is correct and you have the PHP module enabled? See http://php.net/manual/en/ref.pdo-mysql.php
I think you didn't escape your backslash with another backslash. Try this:
<?php
$servername = 'RemoteServerName\\SqlInstance';
?>

How to connect to sql database through php/pdo that has been exported from mysql/phpmyadmin as mydatabase.sql?

I have searched on many different sites and cannot find an answer that specifically answers this question:
I have WAMP Server installed, which installed phpmyadmin as well as MySQL. I can easily connect to the database through php/pdo by using localhost as my hostname.
But my problem is I am trying to connect to a database that I have exported from phpmyadmin as "mydatabase.sql". So now lets say I placed this file on my pc at "C:\Users\Username\Desktop\MyFolder\mydatabase.sql". How would I connect to this database (if this is possible)?
The reason is that I cannot install WAMP Server on all the pcs that would use this program. so would like to be able to connect to the database without having to install any type of servers, etc...
My php at the moment is:
<?php
$dsn='mysql:C:\Users\Username\Desktop\MyFolder\mydatabase.sql';
$username='username';
$password='pass';
try
{
$dbh = new PDO("$dsn",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Connected to Database<br/>';
$sql = "SELECT * FROM users";
foreach ($dbh->query($sql) as $row)
{
echo $row["ID"] ." - ". $row["Name"] ."<br/>";
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Also, if this is possible, would username and password be necessary to connect to an "off server database"?
If I try:
$dsn='sqlite:C:\Users\Optique\Desktop\optique.sql';
I get:
"Connected to Database
SQLSTATE[HY000]: General error: 26 file is encrypted or is not a database"
But I think that is because SQLite uses a different database format than MySQL (stand to be corrected). So what I need is something similar to the SQLite driver for MySQL.
Thanks in advance!
You cannot find an answer simply because it doesn't exist: it's impossible to connect to an SQL dump through PDO, and it makes no sense anyway: a dump is not a database but simply a collection of INSERT queries. Unlike sqlite, for mysql you need a server to connect with.
To be able to connect, you should import that dump into mysql database first and then connect to that database with PDO.

Trying to connect with sql server database

I'm trying to connect sql server with php, i'm trying to get info from the database..
Now, here is what i got:
try {
$user = '';
$pass = '';
$objDb = new PDO('mysql:host=192.168.10.250;dbname=WEB_POROSIA',
'$user', '$pass');
$objDb->exec('SET CHARACTER SET utf8');
$sql = "SELECT *
FROM 'WEB_POROSIA'
";
$statement = $objDb->query($sql);
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo $e->getMessage();
}
I receive this error:
SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it.
This is my first attempt to connect php with sql server, and i don't know what this output means, i mean i don't know what might cause it!
I'm using xampp.
Thanks
It appears that you are trying to connect using the wrong driver.
For Sql Server you might want to use PDO ODBC driver not the mysql method you are trying to use.
You need to use a different DBO driver.
Check out other ODBC drivers, i.e PDO.
The code you have written tries to connect to a MySQL database rather than a MSSQL one.
You'll want to do something like this:
$db_connection = new PDO("dblib:dbname=$db_name;host=$host", $username, $password);
You can find more information here: http://grover.open2space.com/content/use-php-and-pdo-connect-ms-sql-server

Access denied for user 'www-data'#'localhost - how to deal with that?

I face with a strange problem yesterday. I have server running Debian with installed PHP 4.4.4-8 and mysql 5.5.9. That server serves a several websites.
For some reason randomly I get that error "Access denied for user 'www-data'#'localhost' (using password: NO)" when I try to load the webpage.
If I hit refresh the page loads normally, but afer several clicks that message appears again. Username which that page use to connect to mysql server is not www-data.
Does anyone has faced similar problem ?
www-data is the Debian user that runs apache and php. If you attempt a query when you don't have a valid connection, php/mysql will attempt to create a connection using <unix-user>#localhost with no password. This is where www-data#localhost (using password:NO) is coming from.
The most likely reason that this has started happening now (though it has been running fine for 2-years prior) is that your db load has increased to the point where some connections are unable to succeed (probably due to max_connections, or max_user_connections; though this can also result from other limits like memory, threads, etc). When this happens, your call to mysql_connect will emit an error message, and return FALSE. If you fail to detect this failure, then your next mysql call (probably mysql_query, or mysql_select_db) will attempt the connection to www-data#localhost -- thus causing the problem you're seeing.
I suggest enabling error reporting, and error display (as suggested by #DarkMantis) :
ini_set('error_reporting', E_ALL|E_STRICT);
ini_set('display_errors', 1);
Also, be sure that your call to mysql_connect is not preceded by a # sign; and make sure to check the return value. It should look something like this:
$cxn = mysql_connect('localhost','yourusername','yourpassword');
if( $cxn === FALSE ) { die('mysql connection error: '.mysql_error()); }
It sounds like the query that is causing the error happens when something specific is called. This could mean that when the query is called, you aren't connected to the database with the correct username/password.
Try to ensure that you are definatly connected, use or die(mysql_error()); at the end of all your query variables to debug them.
Also, use the following two lines at the top of your php file:
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
That will show you any little php errors that may occur within your class/file which you may not have picked up before.
If your still having a problem after this, please post your PHP code and I will take a look at it directly.
Thanks!
i faced the same problem.
The problem was in my config.php!
I simply changed the $dbserver from
"127.0.0.1" -> "localhost".
Now the connection works again!
For absent-minded people, this error may happen when mysql_query() is called after mysqli_connect(), when it should be mysqli_query().
Use password 'NO'
(MySQLi Object-Oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Deactivating safe mode fixed it for me:
Notice: mysql_connect(): SQL safe mode in effect - ignoring host/user/password information in /var/www/html/test.php on line 4
For solve this problem. I had to change the connection script Using
(MySQLi Object-Oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

Categories