tazboy
tazboy

Reputation: 1754

MySQL PHP database connection

Here is my index.html file. I load the page and nothing happens. Shouldn't it print "Please try again" on the webpage if my info is incorrect?

 <html>
    <body>
      <h1>mySQL</h1>

      <?php

      $server = "mysql.blah.com"; 
      $username = "my_username";
      $password = "my_password";
      $database = "my_database";

      $mysqlConnection = mysql_connect($server, $username, $password);
      if (!$mysqlConnection){
        echo "Please try later.";
      }
      else {
        echo "All good";
        mysql_select_db($database, $mysqlConnection);
      }

      ?>

    </body>
</html>

Upvotes: 0

Views: 41

Answers (2)

Francis Sunday
Francis Sunday

Reputation: 77

change the file to the .php extension and use this refactored version

<html>
    <body>
      <h1>mySQL</h1>

      <?php

     try 
     {
        $server = "mysql.blah.com"; 
        $username = "my_username";
        $password = "my_password";
        $database = "my_database";

        $mysqlConnection = new PDO('mysql:host={$server};dbname={$database};', '{$username}', '{$password}');
        $mysqlConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      }
      catch(PDOException $e)
      {
        echo ('Please try later.');
        echo $e->getMessage();
      }
      ?>

    </body>
</html>

Upvotes: -1

Alex
Alex

Reputation: 38499

This is because your file has the .html extension.
Change it to .php and run it again.

Be sure to run it on a web server, that has PHP installed

Upvotes: 5

Related Questions