skip to Main Content

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


  1. 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:

    <?php
        try
        {
            if ($db = mysqli_connect($hostname_db, $username_db, $password_db))
            {
                //do something
            }
            else
            {
                throw new Exception('Unable to connect');
            }
        }
        catch(Exception $e)
        {
            echo $e->getMessage();
        }
    

    And check if the code print some connection error.

    Reference: how to use throw exception in mysql database connect

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. You can try this code

    <?php
       $servername = "localhost";
       $username = "username";
       $password = "password";
    
       // Create connection
       $conn = mysqli_connect($servername, $username, $password);
    
       // Check connection
      if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
       }
       echo "Connected successfully";
      ?>
    

    How to Connect to mysql using php

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search