关于检索和处理的通知

This is my table:

enter image description here

I want a query that will retrieve the maximum QID from the table where I specify a Pid. Then I want to take the selected value and add 1 to it. I want this to work even if there is no value on qid where Pid is for example 1 or 2.

For example if the max qid is 1 where pid is 1, I want a code to retrieve the value qid=1 and add 1 to it. Then the new value, "2" in this case, should be stored in a hidden input field. If I, for example, put "WHERE pid=4" in my query and there is no pid=4 in my table, which retrieves a null value from qid, that should also work and the new value should be 1(null + 1 = 1).

I have this but I don't know if it is right. I'm maybe doing something wrong in the query.

<?php
$qu = "SELECT coalesce(max(qid),1) AS id FROM answer_det WHERE pid = '1' ";
 $result = $mysqli->query($qu);

if ($result->num_rows > 0) {
    while($row = $result->fetch_array()) {   
        
        echo "
            <form action='insertdilemma.php' method='post'>
            <input type='text' name='ans1'>
            <input type='hidden' name='qidsend' value='". $row["id"]. "'>
            <input type='submit' name='submit' value='Send'>   
            </form>";
}}
  else {
    echo "0 results";
}

mysqli_close($mysqli);
          
?>

I get this error message: Notice: Trying to get property of non-object in C:\xampp\htdocs\wildfire\dilemman.php on line 132

This is on line 132: if ($result->num_rows > 0) {

</div>

simply remove the second where

   $qu = "SELECT ifnull(max(qid)+1,1) AS id FROM answer_det  WHERE pid = '1' ";

and you should submit the new qid but also the id .

    echo "
        <form action='insertdilemma.php' method='post'>
        <input type='text' name='ans1'>
        <input type='hidden' name='pidsend' value='". $row["pid"]. "'>
        <input type='hidden' name='qidsend' value='". $row["id"]. "'>
        <input type='submit' name='submit' value='Send'>   
        </form>";