Tuesday, 15 March 2011

php - 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 -



php - 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 -

so method works in inserting values table:

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

however, method fails:

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

and gives error:

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

i need utilize mysqli query within function looping through multiple values. how prepare this?

it because don't have $link variable in function scope. (meaning $link null) can pass connection resource function parameter (which $link variable in case) or utilize global.

passing connection resource parameter :

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

php mysql sql mysqli

No comments:

Post a Comment