Zachary Toney Zachary Toney - 1 month ago 5
PHP Question

(PHP) How can I assign a variable with a random function and only do it one time? My variable keeps changing anytime I reference it

The problem I seem to be having is that anytime I reference the $j variable it switches which makes sense since it literally is assigned to a function that does that. I may be just having a programmers block but, how do I make it so it generates a random number one time and I can assign it to a variable that won't change?

Thanks in advance!

global $wpdb;

$j = rand();

$table_name = 'quiz';
if(isset($_POST["nextpage"]) && $_POST["nextpage"]!="") {

$j = rand();
$nextpage = mysql_real_escape_string($_POST["nextpage"]);

switch ($nextpage) {
case '2':
$wpdb->insert($table_name, array('Q1score'=>$_POST[Q1],'Q2score'=>$_POST[Q2],'Q3score'=>$_POST[Q3],'ID'=>$j));

$_SESSION['page'] = 2;

break;
case '3':
$wpdb->update($table_name, array('Q4score'=>$_POST[Q4],'Q5score'=>$_POST[Q5],'Q6score'=>$_POST[Q6],'Q7score'=>$_POST[Q7]), array('ID'=>$j));
$_SESSION['page'] = 3;
break;

case '4':
$_SESSION['page'] = 4;

break;
}

} else {

if (!isset($_SESSION["page"])) {
$_SESSION["page"] = "1";
} else {
/* do nothing */
}

}

Answer

Use isset() to see if it's already been defined in this scope.

if ( !isset( $j ) ) $j = rand();

Populate a $_SESSION[] variable if you want to maintain across multiple page loads during one session.

if ( !isset( $_SESSION['j'] ) ) $_SESSION['j'] = rand(); // expects session_start() to be called somewhere above
$j = $_SESSION['j'];

Pick one or the other.

global $wpdb;

if ( !isset( $_SESSION['j'] ) ) $_SESSION['j'] = rand(); // expects session_start() to be called somewhere above
$j = $_SESSION['j'];

$table_name = 'quiz';
if(isset($_POST["nextpage"]) && $_POST["nextpage"]!="") {

    /* $j = rand(); remove this assignment */
    $nextpage = mysql_real_escape_string($_POST["nextpage"]);

  switch ($nextpage) {
    case '2':
      $wpdb->insert($table_name, array('Q1score'=>$_POST[Q1],'Q2score'=>$_POST[Q2],'Q3score'=>$_POST[Q3],'ID'=>$j));

      $_SESSION['page'] = 2;

      break;
    case '3':
      $wpdb->update($table_name, array('Q4score'=>$_POST[Q4],'Q5score'=>$_POST[Q5],'Q6score'=>$_POST[Q6],'Q7score'=>$_POST[Q7]), array('ID'=>$j));
      $_SESSION['page'] = 3;
      break;

    case '4':
      $_SESSION['page'] = 4;

      break;
  }

} else {

  if (!isset($_SESSION["page"])) {
    $_SESSION["page"] = "1";
  } else {
    /* do nothing */
  }

}