douzhang3356 2013-12-02 06:20
浏览 43
已采纳

使用mysqli不插入数据

I have a following main files:

index.php:

<?php
include_once("inc/config.php");
$view = $_GET["view"];
include_once "template.php";
?>

config.php:

define("HOST","localhost");
define("USER","root");
define("PASS","*******");
define("DATABASE","abc");

$mysqli = new mysqli(HOST,USER,PASS,DATABASE);

if (mysqli_connect_errno()) {
    printf("Connect failed: %s
", mysqli_connect_error());
    exit();
}

view/create_account.php:

<?php 
include_once(CLASS_PATH."create_account.php"); 
$acc = new account();

if((isset($_POST)) and ($_REQUEST['mode']=="insert"))
{
    $acc->insert_orginfo();
}
?>

class/create_account.php:

<?php
class account
{

    function __construct () {

    }

    /* ----  insert organization info into table  ---- */
    function insert_orginfo()
    {
        extract($_POST);

        $query  = "insert into `organisationinfo` 
                     (`org_name`, `addr1`, `addr2`, `city`, `state`, `country`, `pin`, `tax_number`, `url`) 
                   values 
                   ('$org_name', '$add1', '$add2', '$city', '$state', '$country', '$pincode', '$tax_no', '$url')";

        $mysqli->query($query);
        if (mysqli_connect_errno()) {
            printf("Connect failed: %s
", mysqli_connect_error());
            exit();
        }
        return $mysqli->insert_id;
    }
}
?>

index.php file include config.php and template.php file and using template.php file i include view file(exa. view/create_account.php). using view file i call the function of class.

now, the problem is data is not inserted.if i add config.php file in class/create_account.php then it is working.But this class file and view file is finally included in index.php and in index.php file config file is included.

means index.php file include template.php file. template.php file include view/create_account.php file and view/create_account.php file include class/create_account.php

so what is the problem here?
Thanks in advance.

  • 写回答

2条回答 默认 最新

  • dsh7623 2013-12-02 06:31
    关注

    This is a scope question. mysqli is not "in scope" in the insert function.

    Fastest solution is to make it "global". http://php.net/manual/en/language.variables.scope.php - see the section on the "global" keyword.

      function insert_orginfo()
      {
    
        $query  = "insert into `organisationinfo` (`org_name`, `addr1`, `addr2`, `city`, `state`, `country`, `pin`, `tax_number`, `url`) values ('$org_name', '$add1', '$add2', '$city', '$state', '$country', '$pincode', '$tax_no', '$url')";
    
        global $mysqli;   // bring MySQL into scope.
    
        $mysqli->query($query);
        if (mysqli_connect_errno()) {
            printf("Connect failed: %s
    ", mysqli_connect_error());
            exit();
        }
        return $mysqli->insert_id;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?