简体   繁体   中英

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>

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM