This query works fine when I call it in in my php page without surrounding it with a function and a name
//MAKE DATABASE CALL TO GET PRODUCT
$product_id = $line_value['productId'];
$product_query = "SELECT *
FROM products
WHERE id = '$product_id'
LIMIT 1";
$product_result = pg_query($con, $product_query);
while ($product_row = pg_fetch_assoc($product_result)){
$product = $product_row['product'];
}
//works
echo $product;
But I get an error when I try to put it within a function
$product = _get_product($product_row['product']);
echo $product'
function _get_product($product_id){
//prints 1
echo $product_id
//MAKE DATABASE CALL TO GET PRODUCT
$product_id = $line_value['productId'];
$product_query = "SELECT *
FROM products
WHERE id = '$product_id'
LIMIT 1";
$product_result = pg_query($con, $product_query);
while ($product_row = pg_fetch_assoc($product_result)){
$product = $product_row['product'];
}
return $product;
}
Warning: pg_query() expects parameter 1 to be resource, null given in
/home/www.site.com/file.php on line
263
I thought perhaps that the function didn’t have access to the included db connection file at the top of the page, but when I put that within the function, I got this error
Warning: pg_query() [function.pg-query]: Query failed: ERROR: invalid
input syntax for integer: “” LINE 3: WHERE id = ” ^ in
/home/www.site.com/file.php on line 265
What have I done wrong? Thanks!
The issue is variable scope. The scope of the function does not include variables declared outside of it.
Don’t use global variables, instead allow the function access by passing $con as a parameter:
And use this to call it: