如何使数据库对象失去功能

时间:2016-01-17 20:26:57

标签: php database mysqli

我有一个连接数据库的函数。在我调用该函数之后,我希望它返回数据库/连接对象,以便我能够使用该对象并对数据库执行查询。如何从函数$mysqli返回test()下面的对象,以便我可以在函数外部使用$mysqli,甚至可以在不同的脚本中使用function test($user, $pass, $db, $host){ $mysqli = new mysqli($host, $user, $pass, $db); if ($mysqli->connect_error) { die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error); } else { echo 'Checkpoint 1 <br>'; return $mysqli; } } test($user, $pass, $db, $host); $sql = "SELECT * FROM `vive_user` WHERE `username` LIKE"."'$name'"; $result = $mysqli->query($sql); 。或者我应该为每个查询编写特定的函数吗?

DataGridView

2 个答案:

答案 0 :(得分:1)

我用于编写大型项目的内容如下:

sessionInfo()
R version 3.2.3 (2015-12-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

//Training svm model
svm.model <- train(as.factor(label) ~., 
                data = dtm, 
                method = "svmRadial",
                preProc = c("center", "scale"),
                trControl = trainControl(method = "cv", number = 5),
                tuneLength = 8)

//prediction on test data - gives warning and returns "NA"s
svm.pred <- predict(svm.model, testData)

答案 1 :(得分:-1)

您只需使用全局变量

即可
$mysqli = null;

function test($user, $pass, $db, $host){
    // Here you define variable in function to global
    global $mysqli;

    $mysqli = new mysqli($host, $user, $pass, $db);

    if ($mysqli->connect_error) {
        die('Connect Error (' . $mysqli->connect_errno . ') '
            . $mysqli->connect_error);
    }
    else{
        echo 'Checkpoint 1 <br>';
        return $mysqli;
    }
}

test($user, $pass, $db, $host);
$sql = "SELECT * FROM `vive_user` WHERE `username` LIKE"."'$name'";
$result = $mysqli->query($sql);