Page 1 of 1

Randomly producing True or False - how?

Posted: Thu May 19, 2011 4:35 pm
by simonmlewis
Hi
I need to be able to randomly have one of two responses that product an SQL query code.

So random result one will give a "no", and random result two will product the query.

How would I do this?

Re: Randomly producing True or False - how?

Posted: Thu May 19, 2011 6:13 pm
by flying_circus

Code: Select all

<?php
  $random = rand(0,1);

  if($random == 0) {
    echo 'No';
  } else {
    echo 'Query';
  }
?>

Re: Randomly producing True or False - how?

Posted: Thu May 19, 2011 9:34 pm
by Jonah Bron

Code: Select all

$var = rand(0,1) ? 'No' : 'SELECT ...';
:)

Re: Randomly producing True or False - how?

Posted: Fri May 20, 2011 2:04 am
by simonmlewis
I understand flying_circus's, but not Jonah's.... Jonah can you explain how yours operates?

This is the sql that would need to be placed in there:

Code: Select all

$sqlconn=@mysql_connect("localhost","root","");
$rs=@mysql_select_db("dbname",$sqlconn);

Re: Randomly producing True or False - how?

Posted: Fri May 20, 2011 2:06 am
by simonmlewis

Code: Select all

<?php 

  $random = rand(0,1);

  if($random == 0) {
    echo 'Sorry there is a fault';
  } else {
    $sqlconn=@mysql_connect("localhost","root","");
$rs=@mysql_select_db("db_name",$sqlconn);
  }
?>
This works real nice. But if the other one is meant to be slicker, still interested it......

Re: Randomly producing True or False - how?

Posted: Fri May 20, 2011 2:09 am
by Apollo
simonmlewis wrote:I understand flying_circus's, but not Jonah's.... Jonah can you explain how yours operates?
See ternary operator.
This is the sql that would need to be placed in there:
That's no SQL, just some php code to create a connection to an SQL server ;)

Re: Randomly producing True or False - how?

Posted: Tue May 24, 2011 2:30 pm
by pickle
Jonah Bron wrote:

Code: Select all

$var = rand(0,1) ? 'No' : 'SELECT ...';
:)
Ternary operator is basically:
some variable = (condition) ? (result if condition == TRUE) : (result if condition == FALSE)

rand(0,1) will produce either a 0 or a 1. PHP interprets 1 as equivalent to boolean TRUE, so the first result will be used. PHP interprets 0 as equivalent to boolean FALSE, so the second result will be used.