MySQL PHP 数据库连接



这是我的索引.html文件。我加载页面,但没有任何反应。如果我的信息不正确,它不应该在网页上打印"请重试"吗?

 <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>

这是因为您的文件具有.html扩展名。
将其更改为.php,然后再次运行。

确保在安装了PHP的Web服务器上运行它

文件更改为.php扩展名并使用此重构版本

<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>

最新更新