I am using this code for mysql connection
$con = mysql_connect("localhost", "username" , "password");
if (!$con)
{
die('Could not connect: ');
}
else
{ echo "connection failed....";}
mysql_select_db("ManagersDatabase", $con);
mysql database are to be found in /var/lib/mysql/ManagersDatabase.
and my php pages are to be found in /var/www/html/.
It dosen't print anything. What is the wrong in my code?
This is how you should be connecting, by using PDO: and utilizing prepared query's when querying.
<?php
try{
$con = new PDO('mysql:host=127.0.0.1;dbname=your_database','root','password');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$con->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}catch (Exception $e){
die('Cannot connect to database. Details:'.$e->getMessage());
}
?>
Or mysqli and utilizing prepared query's when querying.
<?php
$con = new mysqli("127.0.0.1", "user", "password", "your_database");
if ($con->connect_errno) {
die("Failed to connect to MySQL: (".$con->connect_errno.") ".$con->connect_error);
}
print_r($con);
?>
Edit (Reply to comment):
If you add print_r($con); you should see the mysqli connection object like:
/*
mysqli Object
(
[affected_rows] => 0
[client_info] => mysqlnd 5.0.10 - 20111026 - $Id: b0b3b15c693b7f6aeb3aa66b646fee339f175e39 $
[client_version] => 50010
[connect_errno] => 0
[connect_error] =>
[errno] => 0
[error] =>
[error_list] => Array
(
)
[field_count] => 0
[host_info] => 127.0.0.1 via TCP/IP
[info] =>
[insert_id] => 0
[server_info] => 5.5.25a
[server_version] => 50525
[stat] => Uptime: 10 Threads: 1 Questions: 1 Slow queries: 0 Opens: 33 Flush tables: 1 Open tables: 26 Queries per second avg: 0.100
[sqlstate] => 00000
[protocol_version] => 10
[thread_id] => 1
[warning_count] => 0
)
*/
Other methods are outdated and soon tobe (thankfully) deprecated.
you should connect to your database in else block;
$con = mysql_connect("localhost", "username" , "password");
if (!$con)
{
die('Could not connect: ');
}
else // if connection is made, then select the DB
{
mysql_select_db("ManagersDatabase", $con);
}
Quote from your question:
if (!$con)
{
die('Could not connect: ');
}
else
{ echo "connection failed....";}
... you do notice it doesn't make much sense? it is saying if (something) { //could not connect } else { //connection failed } so your code thinks it is always failing.
What you should have is something like
$con = mysql_connect("localhost", "username" , "password");
if ($con === false)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ManagersDatabase", $con);
So it would actually print out anything.
Also, you should have either display_errors enabled to get the errors on screen or error_log in use so you would get the errors logged to somewhere.
In addition, please check you actually have the mysql extension enabled and in use, and mysql_connect() function available. phpinfo(); will tell what extensions you have, and function_exists() can tell you have the function available.
So, things to do:
Fix your code logic like listed above
Enable error printing or logging
Check that you have the mysql extension enabled
Check that mysql_connect() function actually is callable
Edit. as the missing mysql extension seems to be the problem ('call to undefined function mysql_connect'):
First of all, you need to have access to your PHP configuration. If this is your local installation or server, you should have that - if you are using someone elses hosting, they are the people who should change these things.
Given some assumptions, such as
you are using your local apache server
you are not using XAMPP or any other *AMP products, but vanilla installations
this is what you should do:
Find your php.ini configuration file or create one based on example files in the PHP folder if you don't have one
Find the lines below (.dll for windows, .so for linux, don't know about others)
;extension=php_mysql.dll
;extension=php_mysqli.dll
;extension=php_pdo_mysql.dll
Strip out the comment (the first ';') from the one you want to use. You are using the first one in your example, the others are for using other abstractions described in some of the other postings here, so if you want to go with the code you have, you'd uncomment the first one.
Enable "display_startup_errors" also if you want to see any configuration problems immediately
Check that "extension_dir" setting is correct, and is pointing to the folder where you have the above .dll extensions
Restart your apache server
This is Template file for your project connect.php. You can use it.
<?php
// Connecting, selecting database
$link = mysql_connect('localhost', 'root', '') or die('Could not connect: ' . mysql_error());
//echo 'Connected successfully';
mysql_select_db('procost') or die('Could not select database');
?>
Related
I have a WAMP installation with Windows Server 2012 R2 Datacenter Edition, Apache 2.4.23, PHP 7.0.10 (mysqlnd 5.0.12-dev - 20150407), MySQL 5.7.14.
I configured a connection with:
$host = 'wrong-server';
$dbase = 'db_name';
$user = 'my_user';
$pwd = 'my_pwd';
$connection='mysql: host='.$host.'; dbname='.$dbase;
$link = new PDO($connection , $user, $pwd);
where wrong-server doesn't exsist (it is for a test for catching errors).
When I execute the code the connection works using localhost as host (I know it because a query to db_name retrive datas).
I searched for some default behaviour or configuration without succes.
Some ideas?
Code update:
<?php
$host = '192.168.123.123'; //'localhost';
$dbase = 'db_name';
$user = 'my_user';
$pwd = 'my_pwd';
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_SILENT;
$connection='mysql: host='.$host.'; dbname='.$dbase;
try {
$link = new PDO($connection, $user, $pwd, $pdo_options);
$_SESSION['DB_INFO']=array( 'db'=>$link->getAttribute(PDO::ATTR_DRIVER_NAME),
'ver'=>$link->getAttribute(PDO::ATTR_SERVER_VERSION),
'cli'=>$link->getAttribute(PDO::ATTR_CLIENT_VERSION ),
'srv'=>$link->getAttribute(PDO::ATTR_SERVER_INFO ),
);
print_r($_SESSION['DB_INFO']);
}
catch(\PDOException $err) {
echo 'Error: '.$err->getMessage();
};
Server 192.168.123.123 doesn't exsist but I have these response:
Array ( [db] => mysql [ver] => 5.7.14 [cli] => mysqlnd 5.0.12-dev - 20150407 - $Id: 241ae00989d1995ffcbbf63d579943635faf9972 $ [srv] => Uptime: 20111 Threads: 1 Questions: 354 Slow queries: 0 Opens: 125 Flush tables: 1 Open tables: 118 Queries per second avg: 0.017 )
But if I set $pwd='wrong_pwd' the answer is:
Error: SQLSTATE[HY000] [1045] Access denied for user 'my_user'#'localhost' (using password: YES)
SOLUTION
As #MichaelBerkowski states, eliminating spaces in the DSN
mysql:host='.$host.';dbname='.$dbase.'
instead of
mysql: host='.$host.'; dbname='.$dbase.'
solves the problem, so an error came out.
I already have my database named als and I still got the error.
<?php
$mysql_host='localhost';
$mysql_user='root';
$mysql_password='';
$mysql_db='als';
$con = #mysql_connect($mysql_host,$mysql_user,$mysql_password) or die(mysql_error());
#mysql_select_db($mysql_db) or die(mysql_error());
?>
Not exactly an answer to your question but too long for a comment:
After establishing the database connection you could just query the existing databases via SHOW DATABASES
<?php
$mysqli = new mysqli('localhost', 'root', '');
if ($mysqli->connect_errno) {
trigger_error('query failed: '.$mysqli->connect_error, E_USER_ERROR);
}
$result = $mysqli->query('SHOW databases')
or trigger_error('connect failed: '.join(',', $mysqli->error_list), E_USER_ERROR);
foreach( $result as $row ) {
echo join(', ', $row), "<br />\r\n";
}
Does your database als show up?
Since you're using the default root account (with an empty password; you might want to look into that as well) there shouldn't be any permission related problems. So, if the database doesn't show up, it's just not there...
(almost) same script using PDO (my weapon of choice) instead of mysqli:
<?php
$pdo = new PDO('mysql:host=localhost;charset=utf8', 'root', '', array(
PDO::MYSQL_ATTR_DIRECT_QUERY => false,
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));
foreach( $pdo->query('SHOW DATABASES', PDO::FETCH_NUM) as $row ) {
echo $row[0], "<br />\r\n";
}
There you go. The mysql_ family has been deprecated for some time. Please change to the mysqli_ library. Another machine may work because it's using an older version of PHP in which it hasn't been deprecated OR where deprecated warnings have been globally supressed.
MySQLI Connect
In the wild
$mysql_host='localhost';
$mysql_user='root';
$mysql_password='';
$mysql_db='als';
$con= mysqli_connect($mysql_host,$mysql_user,$mysql_password, $mysql_db) or die("Error " . mysqli_error($con));
There's no need to arbitrarily select the database anymore. Now you can use $con as an argument to the mysqli_ family of procedural functions.
Last, but not least, never debug with the # symbol. This suppresses the error warnings from the function it precedes.
I have this simple code:
<?php
//Open the mySQL connection
$conn_string = "'localhost', 'Vale', 'test'";
$dbh = mysql_connect($conn_string);
//Check that a connection with the DB has been established
if (!$dbh)
{
die("Error in MySQL connection: " . mysql_error());
}
...
And I get the error: Error in MySQL connection: php_network_getaddresses: getaddrinfo failed: The requested name is valid, but no data of the requested type was found.
I cannot figure out what the problem is, I have been google-ing but all the suggestions have failed (tried 127.0.0.1 instead of localhost, 127.0.0.1:3306, etc.)
I have code that works with postgre, but I need to use mysql, and I am trying to modify it, but I cannot pass the first line and get a connection. Any suggestion, please? Thank you!
mysql_connect doesn't take a comma seperated string. It takes 3 individual strings.
Change it to this:
$dbh = mysql_connect($server, $mysql_user, $password);
If you absolutely have a comma separated string, and can't get around this, you can split the string like this:
$config = str_replace("'", '', $conn_string); // replace the quotes.
$config = preg_split('/,/', $conn_string); // split string on ,
if($config != $conn_string) { // make sure this returned an array
count($config) === 3 OR die("Invalid database configuration string");
$dbh = mysql_connect($config[0], $config[1], $config[2]);
if(FALSE === $dbh) {
die("Coult not connect: " . mysql_error());
}
}
You might want to consider MySQLi, instead of MySQL.
<?php
$dbh=mysqli_connect("localhost","Vale","Password","test"); /* Vale is your username? And the name of your database if test, right? And your Username's Password is blank? */
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
?>
As other users have pointed out mysql_connect expects the database, username, and password as separate arguments rather than a single string.
I think another highly important issue to point out is that this particular extension is deprecated.
Please see: http://uk1.php.net/function.mysql-connect
A better solution would be to use mysqli_connect: http://uk1.php.net/manual/en/function.mysqli-connect.php
$db = mysqli_connect( 'localhost', 'Vale', 'test', 'yourDatabaseName' );
mysql_connect requires three argument not single string
$dbh = mysql_connect('localhost', 'Vale', 'test');
Got a problem! Though I found almost similar threads but none helped :(
I've written a php script to fetch the number of registered users from my MySQL database. The script is working great in my localhost; it is using the given username,pass and host name which are "root", "root", and "localhost" respectively, but the script is not using the given username/pass/host rather using root#localhost (password: NO) in Live server.
In the Live server I created a MySQL user, set an different password, and hostname there is of course not localhost. I updated the script with my newly created mysql users data. BUT, whenever I run the script, I see that the script is still using "root", "root", and "localhost"!!
take a look at the script:
//database connection
$conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
$db = mysql_select_db ("regdb",$conn); //Oops, actually it was written this way in the script. I misstyped it previously. now edited as it is in the script.
//Query to fetch data
$query = mysql_query("SELECT * FROM regd ");
while ($row = mysql_fetch_array($query)):
$total_regd = $row['total_regd'];
endwhile;
echo $total_regd;
-- Some says to change the default username and pass in the config.ini.php file located in phpMyAdmin directory. Would this help?? I didn't try this because either my hosting provider didn't give me privilege to access that directory (because I am using free hosting for testing scripts) or I simply didn't find it :(
Please help....
Foreword: The MySQL extension is marked as deprecated, better use mysqli or PDO
Though you store the connection resource in $conn you're not using it in your call to mysql_query() and you're not checking the return value of mysql_connect(), i.e. if the connection fails for some reason mysql_query() "is free" to establish a new default connection.
<?php
//database connection
$conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
if ( !$conn ) {
die(mysql_error()); // or a more sophisticated error handling....
}
$db = mysql_select_db ("regdb", $conn);
if ( !$db ) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
//Query to fetch data
$query = mysql_query("SELECT * FROM regd ", $conn);
if (!$query) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
while ( false!=($row=mysql_fetch_array($query)) ):
$total_regd = $row['total_regd'];
endwhile;
echo $total_regd;
edit: It looks like you're processing only one row.
Either move the echo line into the while-loop or (if you really only want one record) better say so in the sql statement and get rid of the loop, e.g.
// Query to fetch data
// make it "easier" for the MySQL server by limiting the result set to one record
$query = mysql_query("SELECT * FROM regd LIMIT 1", $conn);
if (!$query) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
// fetch data and output
$row=mysql_fetch_array($query);
if ( !$row ) {
echo 'no record found';
}
else {
echo htmlspecialchars($row['total_regd']);
}
First of all:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
What is your mysql_error()? :)
With this code:
mysql_connect("mysql.webzdarma.cz", "octopus74", "*") or die ("Mysql connect Error>");
MySQL_Select_DB("octopus74") or die("Cant choose MySql database.");
It results in: "Mysql connect Error"
Change your die() calls to die(mysql_error()), which will output the ACTUAL reason for the error, which is of far more use than your fixed text.
Source : http://wallstreetdeveloper.com/php-database-connection/
I found a very useful code for connecting with mysql i posted below:
<?php
//Step-1 : Create a database connection
$connection=mysql_connect(“localhost”,”root”,”root”);
if(!$connection) {
die(“Database Connection error” . mysql_error());
}
//Step-2 : Select a database to use
$db=mysql_select_db(“widget_corp”,$connection);
if(!$db) {
die(“Database Selection error” . mysql_error());
}
?>
<html>
<head>
<title>Database</title>
</head>
<body>
<?php
//Step 3 : Perform database Queury
$result=mysql_query(“select * from subjects”,$connection);
if(!$result) {
die(“No rows Fetch” . mysql_error());
}
//Step 4 : Use returned data
while($row=mysql_fetch_array($result))
{
//echo $row[1].” “.$row[2].”<br>”;
echo $row["menu_name"].” “.$row["position"].”<br>”;
}
?>
</body>
</html>
<?php
//Step 5 : Close Connection
mysql_close($connection);
?>
first are you sure that your mysql username and password are correct?
The syntax for mysql connect is:
mysql_connect('your host server', 'mysql_username', 'mysql_password');
The syntax for mysql select db is:
mysql_select_db ('your_database_name');
Are you sure that your mysql username and mysql database name is the same : "octopus74".
I would recommend to do in this way:
$conn = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$conn) {
die('Not connected : ' . mysql_error());
}
// select db
$db_selected = mysql_select_db('mydbname', $conn);
if (!$db_selected) {
die ('Cannot use database mydbname : ' . mysql_error());
}
Open up the server's my.cnf and find this line:
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address = 127.0.0.1
If it's localhost (127.0.0.1) you won't be able to connect to it. Change it to 0.0.0.0 to allow the server to listen for external connections.
On the other hand, if it's 0.0.0.0 and you can't connect, check that:
Server is up (no laughing matter, I've seen these cases)
Service / Daemon is up
Port is open and you're connecting through the right one: it might have been reassigned.
If all else fails ... use fire and call your SysAdmin.