2017-03-20 315 views
-1

我有連接的PHP代碼到MySQLPHP連接到MySQL

<?php 

$user = 'root'; 
$pass = ''; 
$db = 'testdb'; 

$db = new mysqli('localhost', $user, $pass, $db) or die("Unable to connect"); 
?> 

與數據庫中的每個驗證數據我必須鍵入的代碼,如登錄,註冊等讓我知道如果有另一種簡單的方法來在一個php文件中連接代碼,並且我們需要一個連接,我們可以調用該文件來獲得我需要的連接,非常感謝。

+0

的頂部在一個單獨的文件中添加此代碼,'require'要在其中創建連接該文件。爲了更好地去參加'OOPS'課程 –

回答

0

請與名稱的文件中像connection.php,把下面的代碼:

$con = mysqli_connect("localhost","my_user","my_password","my_db"); 

include它在需要時,如:

include 'connection.php'; 
0

文件1:mysqlConnection.php

<?php 
class mysqlConnection 
{ 
    public static $connection=null; 
    public static function connect() 
    { 
     if(is_null(self::$connection)) 
     { 
      $user = 'root'; 
      $pass = ''; 
      $db = 'testdb'; 

      self::$connection = new mysqli('localhost', $user, $pass, $db) or die("Unable to connect"); 
     } 
    } 
} 

文件2:test.php

<?php 

require_once 'mysqlConnection.php'; 
mysqlConnection::connect(); 
//use db connection like this 
mysqlConnection::$connection; 
?> 
1
<?php 
    $connection=mysql_connect("localhost","user_name","password") //code for connect to MySql 
    or die("Couldn't connect to the server"); 

    $db=mysql_select_db("database_name",$connection) //code for select a Database 
    or die("Couldn't select database"); 
    ?> 

有一個偉大的編碼哥們! ;)

1

建立一個文件connection.php或任何其他易於記憶的文件名。

<?php 
$username = 'root'; 
$pass = ''; 
$database = 'DATABASE_NAME_HERE'; 
$conn = mysqli_connect('localhost', $username, $pass, $database); 
if (!$conn) { 
    die("Connection failed: " . mysqli_connect_error()); 
    } 
?> 

然後在要使用mysql連接的頁面上包含該文件。 可以包括通過加入這一行對頁面

include_once('connection.php');