PHP - Trouble With Rand() In If-clause
Hey guys,
I don't know what to do. I've got a script used for gamble: $gamble_rand = rand($number_of_tickets,$gamble_chance); if($gamble_chance == $gamble_rand){ If $number_of_tickets is set by 99 and $gamble_chance is set by 100 the chance is 1:100 that the If-Clause is not true. But it seems to me that PHP is making its on "random". Independent of the values PHP is interpreting that 20 times of 100 times the correct logic is false... If $number_of_tickets is set by 1 there's no big different. Its just a little bit less, but not the chance that it has to be. Thanks for helping and Merry Christmas :-) Similar TutorialsHello everybody, I just have a quick question. I am trying to develop a webpage for dice rolling (to use for myself when i play dnd) Now, I know a lot of the random functions is computer languages are not truly random, and thus have some areas that the value will be the result more than others. What would be a good way to try to make it as "random" as possible, or am I just over-thinking it? what am i doing wrong? I can't see it... I want to catch the rand variable but it doesn't. So I print an extra print at the bottom. So there should be two rand prints. Here's the code.
<html> <head><title></title> </head> <body> <form action='random.php' method='post'> <?php if(isset($_REQUEST['rand'])){ $rand = $_REQUEST['rand']; print $rand . "<br /><br />"; } else { print "rand: empty<br /><br />"; } $rand = rand(1,1000); print $rand."<br /><br />"; print "<input type='hidden' value='$rand' />"; ?> <input type='submit' value='scramble' /> </form> </body> </html>I forgot to tell ya that the if statement returns rand: empty. Help... Hi,
I basically want a function that takes a parameter which is a percentage chance of the functioning returning true.
A user can move from tier 1->10 and at tier 1 there's a 70% chance to move to tier 2, from tier 2 there's a slightly less chance to move up, and so on.
I tried with the following piece of code:
public function rollTheDice($winnerPercentage) { $number = rand(1, 100); if ($number <= $winnerPercentage) return true; return false; }The above code makes logical sense to me: 1. Pick a random number between 1 and 100. 2. If that number is less than or equal to the percentage, then we passed (example, if the random number is less than or equal to 70.. there must be a 70% chance of this?) This however does not seem to work, in fact it appears that when simulating a roll, 70% fails at the very first step (where there is a 70% chance of winning..) To actually make it to tier 10, has yet to be accomplished, so by simulating this with unlimited attempts for 120 seconds straight doesn't seem to "win". I tried (just for fun) and change the if-statement so: if ($number >= $winnerPercentage) This seems to be working quite well, as the simulator quickly reaches tier 10 this way. Any suggestions to code changes, or can someone explain why it is working way better when exchanging less than with greater than? Really need a hand from someone mysql query is pretty basic. I have been ask to add a random order to this query. $query = "SELECT rd.user_id FROM {$regions_data_table} rd WHERE rd.field_id = {$regions_field_id} AND rd.value LIKE %s AND rd.user_id NOT IN (SELECT um.user_id FROM {$wpdb->base_prefix}usermeta um WHERE ((um.meta_key='wp_ul_disabled' AND um.meta_value=1) OR (um.meta_key='wp_ul_inactive' AND um.meta_value=1)) GROUP BY um.user_id)"; I have tried so many options but cannot seem to get it to work i am trying to insert order by rand(). Any help please? Hi there, I have one question about the function rand(), What if i want to have an number between 0 and 360 Without 90 to 180 so 91,92,93,94.....180 can't be the number how can i do that? btw, I know its possible through if,while,for and so on. But is there an other way to do this? Hey, This is my [faulty] PHP $input3 = array("BB, BB, BB, BB, BB, BB, BB, BB, BB, bb"); $rand_keys3 = array_rand($input3, 2); $BB1 = $input3[$rand_keys3[0]] . "\n"; $BB2 = $input3[$rand_keys3[1]] . "\n"; $input4 = array("HD, HD, HD, HD, HD, hd"); $rand_keys4 = array_rand($input4, 2); $HD1 = $input4[$rand_keys4[0]] . "\n"; $HD2 = $input4[$rand_keys4[1]] . "\n"; $input5 = array("DD, DD, DD, DD, DD, DD, DD, dd"); $rand_keys5 = array_rand($input5, 2); $D1 = $input5[$rand_keys5[0]] . "\n"; $D2 = $input5[$rand_keys5[1]] . "\n"; $input6 = array("CC, CC, CC, CC, CC, cc"); $rand_keys6 = array_rand($input6, 2); $C1 = $input6[$rand_keys6[0]] . "\n"; $C2 = $input6[$rand_keys6[1]] . "\n"; $input7 = array("HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, hg"); $rand_keys7 = array_rand($input7, 2); $HG1 = $input7[$rand_keys7[0]] . "\n"; $HG2 = $input7[$rand_keys7[1]] . "\n"; And this is the error I'm getting: Warning: array_rand() [function.array-rand]: Second argument has to be between 1 and the number of elements in the array in /home/content/91/6351791/html/dogtrader.php on line 48 Warning: array_rand() [function.array-rand]: Second argument has to be between 1 and the number of elements in the array in /home/content/91/6351791/html/dogtrader.php on line 54 Warning: array_rand() [function.array-rand]: Second argument has to be between 1 and the number of elements in the array in /home/content/91/6351791/html/dogtrader.php on line 60 Warning: array_rand() [function.array-rand]: Second argument has to be between 1 and the number of elements in the array in /home/content/91/6351791/html/dogtrader.php on line 66 Warning: array_rand() [function.array-rand]: Second argument has to be between 1 and the number of elements in the array in /home/content/91/6351791/html/dogtrader.php on line 72 I've checked back over it all and looked up the function in various places to check what they say about it, but can't see which bit I'm going wrong wit! :[ If anybody has any advice as to what to do to fix it, it would be much appreciated. Cheers. I have this in my code: $dr =rand(0, 100); echo $dr; Here are the last 5 refreshes: 997 6336 6144 1110 2914 similar results when I use mt_rand()... Hi,
I'm having a bit of trouble. I want to order the same 9 results by RAND(). Currently I have them ordered by 'avg' (average views) and that's working fine, but when I add a sub query to make those 9 results scatter by random it's causing some trouble.
Code I currently have that works:
$sql = "SELECT *, views / HOUR(TIMEDIFF(NOW(), date)) as avg FROM content WHERE date BETWEEN CURDATE() - INTERVAL 30 DAY AND NOW() - INTERVAL 2 HOUR AND views > 600 AND live = '0' ORDER BY avg DESC LIMIT 9"; This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=326563.0 I have 2 sites here that does what i need them to do but i dont know how to put the 2 codes together i got it to upload all files and used rand() to give the files a # but it ends up giving them all the same # lol so they overwrite them selfs lol This site shows how to upload mltiple fiels with php. http://www.ehow.com/how_6345068_upload-multiple-files-php.html This site shows how to rename only 1 file uploaded with rand() http://php.about.com/od/advancedphp/ss/rename_upload.htm i pray this is not to hard to do and if any one gets bored after words can you show how to block a file type from being uploaded ? like php/exe types PS)i would call my self a php newbe lol and ty you for your time and help Code from http://php.about.com/od/advancedphp/ss/rename_upload.htm Code: [Select] <form enctype="multipart/form-data" action="upload.php" method="POST"> Please choose a file: <input name="uploaded" type="file" /><br /> <input type="submit" value="Upload" /> </form> //This function separates the extension from the rest of the file name and returns it function findexts ($filename) { $filename = strtolower($filename) ; $exts = split("[/\\.]", $filename) ; $n = count($exts)-1; $exts = $exts[$n]; return $exts; } //This applies the function to our file $ext = findexts ($_FILES['uploaded']['name']) ; //This line assigns a random number to a variable. You could also use a timestamp here if you prefer. $ran = rand () ; //This takes the random number (or timestamp) you generated and adds a . on the end, so it is ready of the file extension to be appended. $ran2 = $ran."."; //This assigns the subdirectory you want to save into... make sure it exists! $target = "images/"; //This combines the directory, the random file name, and the extension $target = $target . $ran2.$ext; if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) { echo "The file has been uploaded as ".$ran2.$ext; } else { echo "Sorry, there was a problem uploading your file."; } The code from http://www.ehow.com/how_6345068_upload-multiple-files-php.html Code: [Select] <form action="upload.php" method="post" enctype="multipart/form-data"> File: <input type="file" name="file[]"/><br/> File: <input type="file" name="file[]"/><br/> File: <input type="file" name="file[]"/><br/> <input type="submit" name="submit" value="Upload"/> </form> $destpath = "upload/" ; while(list($key,$value) = each($_FILES["file"]["name"])) { if(!empty($value)){ f ($_FILES["file"]["error"][$key] > 0) { echo "Error: " . $_FILES["file"]["error"][$key] . "<br/>" ; } else { $source = $_FILES["file"]["tmp_name"][$key] ; $filename = $_FILES["file"]["name"][$key] ; move_uploaded_file($source, $destpath . $filename) ; echo "Uploaded: " . $destpath . $filename . "<br/>" ; } } } I want to use the following code to upload images to my server (below code works great) Code: [Select] <?php $rand = rand(1,99999999999999); $member_id = $_SESSION['SESS_MEMBER_ID']; if(isset($_FILES['uploaded']['name'])) { $target = "gallery/"; $allowed_filetypes = array('.jpg','.gif','.bmp','.png'); $max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB) $fileName = basename($_FILES['uploaded']['name']); $target = $target . $fileName; $errors = array(); // Get the extension from the filename. $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Check if the filetype is allowed. if(in_array($ext,$allowed_filetypes)) { $errors[] = "The file you attempted to upload is not allowed."; } // Now check the filesize. if(filesize($_FILES['uploaded']['tmp_name']) > $max_filesize) { $errors[] = "The file you attempted to upload is too large."; } // Check if we can upload to the specified path. if(is_writable($target)) { $errors[] = "You cannot upload to the specified directory, please CHMOD it to 777."; } //Here we check that no validation errors have occured. if(count($errors)==0) { //Try to upload it. if(!move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) { $errors[] = "Sorry, there was a problem uploading your file."; } } //If no errors show confirmation message if(count($errors)==0) { echo "<div class='notification success png_bg'> <a href='#' class='close'><img src='img/cross_grey_small.png' title='Close this notification' alt='close' /></a> <div> The file {$fileName} has been uploaded<br>\n </div> </div>"; //echo "The file {$fileName} has been uploaded"; echo "<br>\n"; echo "<a href='gallery.php'>Go Back</a>\n"; } else { //show error message echo "<div class='notification attention png_bg'> <a href='#' class='close'><img src='img/cross_grey_small.png' title='Close this notification' alt='close' /></a> <div> Sorry your file was not uploaded due to the following errors:<br>\n </div> </div>"; //echo "Sorry your file was not uploaded due to the following errors:<br>\n"; echo "<ul>\n"; foreach($errors as $error) { echo "<li>{$error}</li>\n"; } echo "</ul>\n"; echo "<br>\n"; echo "<a href='gallery.php'>Go Back</a>\n"; } } else { //Show the form echo "Use the following form below to add a new image to your gallery;<br />\n"; echo "<form enctype='multipart/form-data' action='' method='POST'>\n"; echo "Please choose a file: <input name='uploaded' type='file' /><br />\n"; echo "<input type='submit' value='Upload' />\n"; echo "</form>\n"; //Echo Tests! echo "<br /><br />Random FileName: "; echo $rand; echo "<br />"; echo "member ID: #"; echo $member_id; } ?> i then want it to rename the files for example: "test.png" is uploaded and name changed to "92997863_321.png" (where first number is using my $rand then the "_" then second number is my $member_id) the script already got these pieces of information and also gets the file extension using the $ext code. can this be done, and can i also upload the new filename to my sql table? Okay, so I'm kind of a PHP noob.
But out of context, for this site that I'm designing, it's easiest if I make a directory in the temporary folder PHP uses. In my case, /tmp/ because I am on Linux.
I want to use rand() to generate a random name for the page. But I then realized something, rand() could produce duplicates. How do I prevent PHP from trying to make the same directory at the same time? I know there are functions that will check if a file exists but I'm assuming it'll fail if that directory is currently being created, right?
How do I assure thread safety?
I willing to change my idea and not use rand(). Is there a way to get a unique key for each anonymous user on my site?
hi, how can I add more than one ID to a WHERE clause? Code: [Select] "SELECT * FROM t_mytable WHERE id_product = 1 "; I need to select products with different id's i.e Code: [Select] "SELECT * FROM t_mytable WHERE id_product = 1,2,3,4,5 "; Thanks This may be super simple, but it's stumping me. Is this an If/Then clause: Code: [Select] ($month != 1 ? $month - 1 : 12) Is it saying if $month does not equal 1 then $month-1; if so, then what does the colon mean? If not, then what is this piece of code doing? Hi. I am building an update table form. In this table there are only two fields, Header and Intro. Now I have the form and currently it displays whats already in the database. Now when the user edits these two fields and presses edit. Obviously I want it to update these fields. I have the code here but there is an issue with it. At the end of the update I believe I need a update fields WHERE....... which would be used if there was more than one entrance in the table but there is and only ever will be one entry. WHERE what? I dont have a where anything. Do I need this or can it be omitted somehow? <?php if(isset($_POST['edit'])){ //Process data for validation $header = trim($_POST['header']); $intro = trim($_POST['intro']); //Perform validations next //Prepare data for db insertion $header = mysql_real_escape_string($header); $intro = mysql_real_escape_string($intro); //insert $qUpdateDetails = "UPDATE index SET `header` = '".$header."', `intro` = '".$intro."', WHERE ???????='".?????????."'"; $rUpdateDetails = mysql_query($qUpdateDetails) or die(mysql_error()); //next page $page_edit = "Index page has been edited"; $url = "signed.php?edit='".$page_edit."'" or die(mysql_error()); header("Location: ".$url."") or die(mysql_error()); exit(); } } ?> Hi
I am now on to viewing listings but want to to show listings that are just submitted by that user and display them on their profile page but can't get the WHERE clause working
Below is the coding for what I have
Profile page
echo "<p><a href='view-private-listings.php?id={$_SESSION['user_id']}'>View Listings</a></p>";Add Listing page HTML Submitted By: <input type="text" name="submittedby">View Listings Page <?php ini_set('display_startup_errors',1); ini_set('display_errors',1); error_reporting(-1); ?> <?php $title = "Private Seller Listings"; include ( 'includes/header.php' ); ?> <?php require_once("functions.php"); $con=mysqli_connect("host","username","password","database"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } // Start a session for error reporting session_start(); $submittedby=$_POST['submittedby']; $listingtitle=$_POST['listingtitle']; $query = mysqli_query($con,"SELECT listingtitle FROM privatelistings WHERE item LIKE '%$submittedby%'"); echo "<p>Title: {$listingtitle['listingtitle']}</p>"; mysqli_close($con); ?> <?php include( 'includes/footer.php' ); ?>All I get is the following error Notice: Undefined index: listingtitle in /zacs-car-site/view-private-listings.php on line 26 Thank you in advance Kind regards Ian I am brand new to mysql and php but I have created a database and loaded two tables using cPanel and phpMyAdmin. Now I need some programs to access my data. I have a couple of simple ones that work, but I can't figure out what I really need, I am trying to Select a table Where the Value is a $variable, not a fixed value. Of course the end result will be to pass the value from a Form, but I have to get this to work first. <?php // Connect to database============================= include("connect_db.php"); $table='airplanes'; $amano='123456' $iden='1' // Send query =========================================================== // $result = mysql_query("SELECT * FROM {$table} where ama='123456'"); == this works // $result = mysql_query("SELECT * FROM {$table} where ama='940276'"); == this works // $result = mysql_query("SELECT * FROM {$table} where id='1'"); // this works // $result = mysql_query("SELECT * FROM {$table} where id = '{$iden}'"); == doesnt work // $result = mysql_query("SELECT * FROM {$table} where id = $iden"); == doesnt work // $result = mysql_query("SELECT * FROM {$table} where id = ($iden)"); // == doesnt work // $result = mysql_query("SELECT * FROM {$table} where id = $iden"); // == doesnt work // $result = mysql_query("SELECT * FROM {$table} where ama='$amano'"); // == doesnt work $result = mysql_query("SELECT * FROM {$table} where ama=($amano)"); // == doesnt work Thanks Code: [Select] $search = "`title` LIKE '%Silvin AND wts%'"; I want to search for both of those keywords why not work? Hi, I have an empty array and i populated the array through code and i printed to check if everything ok. So far so good. I now have an array say $ids = ('123','456'). Now, i have a table in db that has ids as well, I need to make a query to check for id's that are not inside the array, so if the db table have '123','456','789' i want the result of the query to be only the last one '789'. $arr = array(); array_push($arr,$previd2); print_r ($arr); I get the result as follows: Array ( [0] => 533349 [1] => 533355 ) so what query i can use to get the other id's from db table that is not part of that array? here is what i tried: $qry = "select staffname, joindate from staff WHERE OracleID NOT IN ($arr)"; $answ = mysqli_query($con, $qry); I get error: Notice : Array to string conversion in C:\xampp\htdocs\AttendanceSystem\login\reportsforallid.php Edited March 30, 2020 by ramiwahdan more info Hi, I have a SQL statement: $sql='SELECT PROPID, ADDRESS_1, ADDRESS_2, TOWN, POSTCODE1, POSTCODE2, BEDROOMS, BATHROOMS, RECEPTIONS, PRICE, TRANS_TYPE_ID FROM properties WHERE TRANS_TYPE_ID=2 AND BEDROOMS =3 AND PROP_SUB_ID IN (1,2,3,4,5,6,21,22,23,24,27,30,95,128,131) ORDER BY DATE_ADDED, PROPID DESC'; I want to be able to get the fields and their corresponding values as such: $result['TRANS_TYPE_ID']=2; $result['BEDROOMS']=3; And then capture the values in PROB_SUB_IN IN(*) How can I do this? Any help will be greatly appreciated. Thanks |