如何运行查询,直到找到一条记录?

This is what i am trying right now but no luck

$bid  = $next - 2;//This subtracts 2 from the number, this number is also auto generated 

    $preid = $bid;
    $query = "SELECT * FROM  images where imageid = '$preid'";
    $sql = mysqli_query($conn,$query) or die(mysqli_error($conn));

    while(mysqli_num_rows($sql) !=0) {
        $select_query = "SELECT * FROM  images where imageid = '$preid'";
        $sql = mysqli_query($conn,$select_query) or die(mysqli_error($conn));
        --$preid;
    } 

whats suppose to happen is that if a record does not exist it subtracts 1 from preid and runs the query again with the new preid and keeps happening until a record it found but cant figure out how to do it.

I am assuming that you are constantly checking database for new values. However, on a large scale application thi is an highly inefficient way to constantly ping the database. You have made a variable $preid but you are not using it anywhere.
This is how i would do it if i were to go according to your way

$bid  = $next - 2;//This subtracts 2 from the number, this number is also auto generated 

$preid = $bid;
$query = "SELECT * FROM  images where imageid = '$preid'";
$sql = mysqli_query($conn,$query) or die(mysqli_error($conn));

while(mysqli_num_rows($sql) !=0 || !$preid) { //notice here i added the condition for preid.
    $select_query = "SELECT * FROM  images where imageid = '$preid'";
    $sql = mysqli_query($conn,$select_query) or die(mysqli_error($conn));
    --$preid;
} 

now what happens is that the loop will run as long as either of the two condition stays true ie either a row is returned from the database or it will keep searching until preid is not 0.

If you want to test for an empty set, your while should run while mysqli_num_rows == 0

while(mysqli_num_rows($sql) == 0) {
        $select_query = "SELECT * FROM  images where imageid = '$preid'";
        $sql = mysqli_query($conn,$select_query) or die(mysqli_error($conn));
        $preid--; 
    } 

As @DarkBee has mentionend in his comment, this code is highly vulnerable for an infinite loop which will take down your script, as soon as there are no entries for anything.