mysqli_connect文件供重用

时间:2014-12-08 03:53:10

标签: php mysqli

我正在尝试创建一个mysqli_conncet文件以供重用。其他文件/功能无法运行该功能。谢谢。

db_connect.php

<?php
    define("DB_SERVER", "localhost");
    define("DB_USER", "***");
    define("DB_PASS", "");
    define("DB_NAME", "**");

    function connect2db(){
    global $connection;
    $connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
      if (mysqli_connect_errno()) {
        die("Database Connection failed!: " . 
            mysqli_connect_error() . 
             "(" .mysqli_connect_errno() . ")"
            );
    }   
    }
?>

我正在调用函数的其他文件:

<?php
    include_once ("../includes/db_connection.php");

    function insert_new_account(){

        $account_name = $_POST['acct_name'];
        $account_address1 = $_POST['acct_address1'];
        $account_address2 = $_POST['acct_address2'];
        $account_city = $_POST['acct_city'];
        $account_state = $_POST['acct_state'];
        $account_zip = $_POST['acct_zip'];
        $account_phone = $_POST['acct_phone'];
        //$account_fax = $_POST['account_fax'];

        $connect = connect2db();
        $query = mysqli_query($connection, "INSERT INTO accounts (account_name, account_address1, account_address2, account_city, account_state, account_zip, account_phone)
        VALUES ($account_name, $account_address1, $account_address2, $account_city, $account_state, $account_zip, $account_phone)");

        return "Account {$account_name} has been created successfully.";
    }


    if (isset($_POST['create-new-account'])) {
        insert_new_account();
    }

?>

1 个答案:

答案 0 :(得分:0)

a)$connect = ...没用,因为(void) connect2db()

b)$connection是全球性的。您必须在insert_new_account() global $connection;

中提及它

c)Stop using `global` in PHP