I have the following code:
<?php
//Step1
$db = mysqli_connect('localhost','root','[mypassword]','users')
or die('Error connecting to MySQL server.');
?>
<html>
<head>
</head>
<body>
<h1>PHP connect to MySQL</h1>
</body>
</html>
I am just trying to connect to my MySQL database. It is administered using phpMyAdmin. I am very unfamiliar with MySQL and I have never used it before. [mypassword] is the password I use to successfully connect to mySQL from the Mac terminal. “users” is a name of a table I have created in phpMyAdmin. I am using cPanel. I keep on getting the error:
Error connecting to mySQL server.
In phpMyAdmin it says Server: localhost:3306.
I have tried for a very long time to fix this problem but with no results. What am I doing wrong?
I have also tried the following:
<?php
$servername = "localhost";
$username = "root";
$password = "[myPassword]";
try {
$conn = new PDO("mysql:host=$servername;dbname=users", $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();
}
?>
After visiting the webpage it says
Connection failed: SQLSTATE[28000] [1045] Access denied for user
‘root’@’localhost’ (using password: YES)
3
Answers
Use a try catch to handle errors on the connection proccess, but i strongly advise you to use PDO by alternative from mysqli PDO Book
Use something like this:
And check if the code print some connection error.
Reference: how to use throw exception in mysql database connect
Be sure that your mySql instance is up. You can download sequelpro and use that to connect to your mySQL. If that doesn’t work then its a mysql setting/config that is wrong.
You can try this code
How to Connect to mysql using php