在函数内向表中插入值会收到一个错误,但是当试图在函数外向表中插入值时,它会正常工作


Inserting values into a table within a function receives an error, but when trying to insert values into the table outside of a function it works fine

所以这个方法可以在表中插入值:

$link = mysqli_connect("example.com","a","b","c");
$sql = 'INSERT INTO `table` (`field1`, `field2`) VALUES ("foo", "bar");';
mysqli_query($link, $sql);

但是,这个方法失败了:

$link = mysqli_connect("example.com","a","b","c");
function foobar(){
    $sql = 'INSERT INTO `table` (`field1`, `field2`) VALUES ("foo", "bar");';
    mysqli_query($link, $sql);  
}

这就给出了错误:

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in foo/bar/example.php

我需要在函数内使用mysqli查询,因为我正在循环多个值。我该如何解决这个问题?

这是因为在函数作用域中没有$link变量。(意思是$link为空)你可以把你的连接资源作为参数传递给你的函数(在你的例子中是$link变量),或者使用global。

将连接资源作为参数传递,如:

$link = mysqli_connect("example.com","a","b","c");
 function foobar($link){
    $sql = 'INSERT INTO `table` (`field1`, `field2`) VALUES ("foo", "bar");';
    mysqli_query($link, $sql);
}
$link = mysqli_connect("example.com","a","b","c");
function foobar($link){
    $sql = 'INSERT INTO `table` (`field1`, `field2`) VALUES ("foo", "bar");';
    mysqli_query($link, $sql);  
}