0

I have seen similar questions but none of them actually fix this problem. I am trying to have a query in a function:

function retrieve() {
    try {
    $resultsall1 = $conn->prepare("SELECT productName, productVendor, SUBSTRING(productDescription, 1, 150), quantityInStock, buyPrice, productcat, MSRP FROM products LEFT JOIN productlines ON products.productLine = productlines.productLine");

    $resultsall1->execute();
    } catch (exception $e) {
        echo "Unable to retrieve results";
    }
    $productsAll1 = $resultsall1->fetchAll();
    return $productsAll1;
}

And the problem comes when I need to call this function to retrieve the information, what do I do? I have seen the following, which I tried, but I cant find the answer. Using this without a function does work.

$productAll2 = retrieve();
        foreach ($productAll2 as $Pitem) {
            if ($Pitem['productcat'] == $_GET["cat"]) {
                echo "<div class='Pitem'><img src='Assets/Images/products/"
                .$Pitem['productName']
                .".jpg'><h2>"
                . $Pitem['productName']
                . "</h2><p><b>Description: </b>"
                . $Pitem['SUBSTRING(productDescription, 1, 150)']
                . "...</p><p><b>Product Vendor: </b>"
                .$Pitem['productVendor']
                . "<p><b>Quantity in Stock: </b>"
                .$Pitem['quantityInStock']
                . "<p><b>Price: </b>"
                .$Pitem['buyPrice']
                . "k$<p><b>MSRP: </b>"
                .$Pitem['MSRP']
                ."</p></div>";
            }
        }

Thank you for the help. Also, What is the difference between $conn->prepare and $pdo->prepare ? Thank you for all your help. Keep in mind that I am new to this PHP and PDO so go easy on me :)

Carlino Gonzalez
  • 189
  • 1
  • 11

1 Answers1

1

In this function of yours, you refer to $conn which you have not bothered to define inside that function:

function retrieve() {
    try {
    $resultsall1 = $conn->prepare("SELECT productName, productVendor, SUBSTRING(productDescription, 1, 150), quantityInStock, buyPrice, productcat, MSRP FROM products LEFT JOIN productlines ON products.productLine = productlines.productLine");

    $resultsall1->execute();
    } catch (exception $e) {
        echo "Unable to retrieve results";
    }
    $productsAll1 = $resultsall1->fetchAll();
    return $productsAll1;
}

You must either pass the variable $conn in as a parameter or declare it as a global variable using the global keyword inside the function:

global $conn

See the docs on variable scope.

S. Imp
  • 2,833
  • 11
  • 24
  • $conn is the name of the connection to the database, it was defined before. I was confused with something else. The problem I have is the thing with the function and accessing it. – Carlino Gonzalez Jan 06 '17 at 22:51