0

I have two files:

cart_function.php

function get_product_name($pid){
    $result = mysql_query("SELECT product_name FROM product_table WHERE product_id='".$pid."'", $link);
    $row = mysql_fetch_array($result);
    return $row['product_name'];
}

cart.php

<?php
    include('cart_function.php');
    $pid = $_GET['product_id'];
    $pname = get_product_name($pid);
    echo $pname;
?>

After I execute the cart.php, it shows an error

supplied argument is not a valid MySQL-Link resource'

If I run the query directly in MySQL database it works perfectly. If I used the get_product_name() function directly in cart.php, again it's not working. But if I remove the function and use the code below, it works:

<?php
    $pid = $_GET['product_id'];
    $result = mysql_query("SELECT product_name FROM product_table WHERE product_id='".$pid."'",$link);
    $row = mysql_fetch_array($result);
    $pname = $row['product_name'];
    echo $pname;
?>

Why?

6
  • 2
    where is database connection query? Commented Oct 2, 2012 at 5:43
  • 2
    If you want to use the global variable $link, you have to define it as global in get_product_name: global $link; Commented Oct 2, 2012 at 5:44
  • Please learn the basics of PHP, in this case: variable scope. php.net/manual/en/language.variables.scope.php Commented Oct 2, 2012 at 5:45
  • Does your function get_product_name() has access to $link? Commented Oct 2, 2012 at 5:45
  • connection file is included perfectly okay in the top of the page.I didn't put it here.Please assume it it in the top. If you really want to see that let me know i will post it Commented Oct 2, 2012 at 5:46

2 Answers 2

5

The problem is here:

function get_product_name($pid){
    $result = mysql_query("SELECT product_name FROM product_table WHERE product_id='".$pid."'",
                          $link);

You have written $link, but its value is not supplied. You have to pass this value in the function argument as you are passing $pid value, like this:

function get_product_name($pid,$link){
Sign up to request clarification or add additional context in comments.

Comments

0

1) You are directly using your database connection link as $link into function so it should be consider as local variable and it doesn't have anything.

2) so you need to declare $link as global in your function.

function get_product_name($pid){
        global $link;
        $result=mysql_query("SELECT product_name FROM product_table WHERE product_id='".$pid."'",$link);
        $row=mysql_fetch_array($result);
        return $row['product_name'];
    }

3) Or you can pass $link as second argument of get_product_name($pid,$link)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.