无法在我的while循环之外访问SQL数据

When I save a result of a SQL query in a variable (in the code in $test2), the variable is empty outside the while loop. Why?

Generally defining varibales inside that loop works (see $test1). And the SQL query works too.

$connection = new mysqli($servername,$username,$password,$dbname) or die("Error: " . mysqli_error($connection));
$query = "SELECT * FROM Table ORDER BY `id` ASC";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_object($result)) {
    $test1 = "some text";
    $test2 = $row->id;
    echo $row->id // Output is the id -> works
}
echo $test1; // Output is "some text" -> works
echo $test2; // Output is nothing -> doesn't work. Why?

You are overwritting the variables in each loop itteration. Save them all to an array and look at the results:

while($row = mysqli_fetch_object($result)) {
    $test1[] = "some text";
    $test2[] = $row->id;
    echo $row->id // Output is the id -> works
}
print_r($test1); 
print_r($test2);

$row = mysqli_fetch_array($result) return an array

and you are using $test2 = $row->id; as object