I am new to PHP, I am trying to implement network communication with mysql database which I made through phpmyadmin over my Bluehost account. Now I have written the following php script to check whether I can connect but I am not able to connect:
<?php
$mysql_host='localhost';
$mysql_user='xxx';
$mysql_pass ='xxx';
mysql_connect ('localhost', '$mysql_user', '$mysql_pass')
or die ('I cannot connect to the database.');
//echo 'hello';
?>
Try this:
mysql_connect ('localhost', $mysql_user, $mysql_pass)
Instead of:
mysql_connect ('localhost', '$mysql_user', '$mysql_pass')
You do not need single quotes here.
Variables between single quotes are not evaluated
mysql_connect ('localhost', '$mysql_user', '$mysql_pass')
Try this:
mysql_connect ('localhost', $mysql_user, $mysql_pass)
the quotes make your vars to a string! and never post you pass and user... even its local use
mysql_connect ( $mysql_host, $mysql_user, $mysql_pass);
dont use die()
, use a error log.
better would be a pdo connection, it give you more comfort and securety.
make shure pdo is enadbled in mysql config, mostly it is enabled by default.
you can set up a pdo connection like
$dsn = 'mysql:dbname=<databasename>;host=<hostname>';
$user = '<user>';
$password = '<passwd>';
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
$_SESSION['error'] .= 'Verbindung fehlgeschlagen: ' . $e->getMessage();
}
You have to remove quotes around variables in mysql_connect
:
mysql_connect ('localhost', $mysql_user, $mysql_pass)
You should understand diff bet single quotes and double quotes in php. single quotes output string as it is. and double quotes parse string before outputting.