如果语句只需要一次加载页面就可以工作

Here is the code I'm using at present:

if ( !isset($id)) {
    $id = rand (1, 3);
}

$con = mysql_connect("localhost","root","");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mycompany", $con);


$result = mysql_query("SELECT * FROM database WHERE id = '$id'");

if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}

$row = mysql_fetch_array($result);
echo "{$row['question']}" ;

I want the rand function will only work one time when page will be loaded. If anyone refresh the page, the rand function won't work so visitors will get the same question again.

I'm a newbie to PHP. Anyone please help me how to do it. Any kind of help is much appreciated.

I have also adapted your code because mysql()-functions are deprecated. I recommend to replace these methods into mysqli()-methods.

Now, your issue is that your random range is/could be too small that it would return with same question. The browser is not aware of the previous question id. You have to pass it by using session.

// store current question id in the session
session_start();
$id = 0;

if ( !isset($id)) {
    $oldID = 0;
    if(isset($_SESSION['questionID']) $oldID = $_SESSION['questionID'];

    // loop random
    do {
        $id = rand (1, 3);
    } while($id == $oldID);
    // store new id to session
    $_SESSION['questionID'] = $id;
}

$con = mysqli_connect("localhost","root","") or die ('Could not connect: ' . mysqli_error());
// when publishing i don't recommend to post the mysql error, don't forget to change it.
mysqli_select_db("mycompany", $con);

$result = mysqli_query("SELECT * FROM database WHERE id = '$id'");

if (!$result) {
    echo 'Could not run query: ' . mysqli_error();
    exit();
}


$row = mysqli_fetch_array($result);
echo "{$row['question']}" ;