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

独自空忆成欢 提交于 2020-01-07 08:40:43

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!