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';
    }
}
1
  • Always use mysql_fetch_assoc. this returns a row as an associative array where the column names will be the keys storing corresponding value. Commented Aug 19, 2017 at 12:21

1 Answer 1

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';
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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 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 :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.