0

I've been using this code, and it's been working fine, but now I've put in a query that only returns one result, and suddenly $findproductsrow is NULL. How do I go about fixing this? (First $findproductsresult is not null, second one is.) Do I need to add a clause incase there is only one row returned?

$UserID = $_SESSION['userID'];
$findproductsstmt = mysqli_prepare($connection, "SELECT DISTINCT PID FROM prices WHERE UserID = ? and Manu = 0");
mysqli_stmt_bind_param($findproductsstmt, 'i', $UserID);
mysqli_stmt_execute($findproductsstmt);
$findproductsresult = mysqli_stmt_get_result($findproductsstmt);
if(mysqli_num_rows($findproductsresult) == 0) {
    echo('This user is not retailing any products.');
}
else{
    $findproductsrow = mysqli_fetch_array($findproductsresult, MYSQLI_ASSOC);
    var_dump($findproductsresult);
    while($findproductsrow = mysqli_fetch_array($findproductsresult, MYSQLI_ASSOC)){
        $_SESSION['PID'] = $findproductsrow['PID'];
        include '../includes/baseproductlist.php';
    }
}
James G.
  • 2,852
  • 3
  • 28
  • 52
  • Always use `mysql_fetch_assoc`. this returns a row as an associative array where the column names will be the keys storing corresponding value. – Yousha Aleayoub Aug 19 '17 at 12:21

1 Answers1

1

Your issue is in the ELSE statement.

Problem

else{
    $findproductsrow = mysqli_fetch_array($findproductsresult, MYSQLI_ASSOC); // this pulls the first record, remove this
    var_dump($findproductsresult);
    while($findproductsrow = mysqli_fetch_array($findproductsresult, MYSQLI_ASSOC)){ // causing this to try and pull the second record which doesn't exist
        $_SESSION['PID'] = $findproductsrow['PID'];
        include '../includes/baseproductlist.php';
    }
}

Solution

else{
    while($findproductsrow = mysqli_fetch_array($findproductsresult, MYSQLI_ASSOC)){
        $_SESSION['PID'] = $findproductsrow['PID'];
        include '../includes/baseproductlist.php';
    }
}
MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77
  • This is a fine answer to OP's question, but I take issue with the statement at the bottom regarding memory usage. PHP will store two different sets of *indexes* for the array, it does not store two separate copies of the *data* as you are implying. The memory difference is negligible in most cases, and is certainly not "double". – Sammitch Sep 17 '13 at 17:26
  • @Sammitch Thanks for clearing that up for me, I guess I never fully researched it before. I edited the answer so that I don't continue the misinformation :) – MonkeyZeus Sep 17 '13 at 18:06