问题
So this method works in inserting values to the table:
$link = mysqli_connect("example.com","a","b","c");
$sql = 'INSERT INTO `table` (`field1`, `field2`) VALUES ("foo", "bar");';
mysqli_query($link, $sql);
However, this method fails:
$link = mysqli_connect("example.com","a","b","c");
function foobar(){
$sql = 'INSERT INTO `table` (`field1`, `field2`) VALUES ("foo", "bar");';
mysqli_query($link, $sql);
}
And this gives the error:
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in foo/bar/example.php
I need to use the mysqli query inside a function as I am looping through multiple values. How do I fix this?
回答1:
It is because you don't have $link variable in the function scope. (Meaning $link is null) You can pass your connection resource to your function as a parameter (which is $link variable in your case) or use global.
passing connection resource as a parameter will be like :
$link = mysqli_connect("example.com","a","b","c");
function foobar($link){
$sql = 'INSERT INTO `table` (`field1`, `field2`) VALUES ("foo", "bar");';
mysqli_query($link, $sql);
}
回答2:
$link = mysqli_connect("example.com","a","b","c");
function foobar($link){
$sql = 'INSERT INTO `table` (`field1`, `field2`) VALUES ("foo", "bar");';
mysqli_query($link, $sql);
}
来源:https://stackoverflow.com/questions/24294450/inserting-values-into-a-table-within-a-function-receives-an-error-but-when-tryi