PHP - Random Function
I'm just searching for some input on a function I saw and wanted someone who could explain to me what this function would mean. As I have the same db structure and was curious specifically to know what sort of values I should have inside of the fields for varcharfield and textfield.
function customfieldinput($fedid,$id,$groupid,$styleid) { $query = "SELECT field.id as getfieldid, field.is_custom as getiscustom, field.fullname as getfullname, customfields.id as getcustomfieldid, customfields.varcharfield as getvarchar, customfields.textfield as gettext FROM efed_list_fields as field LEFT JOIN efed_content_customfields as customfields ON ( field.id = customfields.field_id and customfields.character_id = '$id' ) WHERE field.fed_id = '$fedid' and field.style_id = '$styleid' and field.group_id = '$groupid' and field.enabled = '1' and field.is_custom > '0' ORDER BY field.is_custom,field.fullname"; $result = mysql_query ($query); while ($row = mysql_fetch_assoc($result)) { $fieldarray=array('getfieldid','getiscustom','getfullname','getvarchar','gettext','getcustomfieldid'); foreach ($fieldarray as $fieldlabel) { if (isset($row[$fieldlabel])) { $$fieldlabel=$row[$fieldlabel]; $$fieldlabel=cleanquerydata($$fieldlabel); } } if ((isset($getcustomfieldid)) && ($getcustomfieldid > "0")) { $update = "update"; } else { $update = "new"; } if ($getiscustom == "1") { print "<tr>\n"; print "<td width=120 class=rowheading>".$getfullname.":</td>"; print "<td class=row3><textarea name=\"custom".$getfieldid.$update."\" class=\"textarea490x100\">"; if ((isset($gettext)) && ($gettext != "")) { print $gettext; } print "</textarea></td>\n"; print "</tr>\n\n"; } else { print "<tr>\n"; print "<td width=120 class=rowheading>".$getfullname.":</td>"; print "<td class=row3><input type=text name=\"custom".$getfieldid.$update."\" class=fieldtext490"; if ((isset($getvarchar)) && ($getvarchar != "")) { print " value=\"".$getvarchar."\""; } print "></td>\n"; print "</tr>\n\n"; } if (isset($getcustomfieldid)) { unset ($getcustomfieldid); } if (isset($getvarchar)) { unset ($getvarchar); } if (isset($gettext)) { unset ($gettext); } } } Similar TutorialsAs above, I have a lottery style site that picks a random number between 1-8 but my users complain for some reason that this is not enough. So i was told to look into using fopen and random.org to generate a random number. Anyone have experience of this and perhaps a code snippet for me to look at and possibly use? help will be appreciated. Hello all, I have some piece of code that is nested like this $variable = 'This is a global argument'; function parentFunction($variable) { function childFunction() { echo 'Argument of the parent function is '.$GLOBALS['variable']; } childFunction(); } parentFunction(5); What I want to know is - Is there a way to access a variable from the parent function without passing arguments to the child function? (Something like how classes have parent::?). I don't want to use $GLOBALS because it might cause some variable collision, and I didn't want to pass arguments because incase I decide to change the arguments in the parent function I'd have to do it in the child function aswell. From my searching around in the Internet it seems like this is not possible, but if theres a slight chance that there might be something out there, i'm willing to give it a shot . Thanks in advance I have this function completely written in my class file that I am working on. The point to this function is to be able to check the login of a user or administrator for either of the control panels associated with my site. It will check the session intime as well as the page / module referenced. Once it passes all those checks, it will check and ensure the emailaddress/password stored in the current session still holds true and the account is still active... if the account is still active it will update the lastActivity as well as update all of the session variables with what is currently in the database. What I am looking for is basically a look at the function, see if it looks good.. If there is any part to it that could create security holes for the site just off the login function itself... Usage: $q->validUser($_SESSION['user'], $_mod); <?php function validUser($sess, $p) { if ($sess['inTime'] == '' && $p != 'login' && $p != 'logout') { session_destroy(); $login = '0'; $_int = ''; return $login; } else if ($sess['inTime'] < time()-3600 && $p != 'login') { $sess['inTime'] = ''; session_destroy(); $this->check_login($sess, $p); } else { $this->user = $sess['emailAddress']; $this->pass = $sess['password']; $login = $this->sql_query("SELECT * FROM users WHERE emailAddress = '".$this->user."' AND password = '".$this->pass."' AND status = '1' LIMIT '1'"); if ($login = $this->sql_numrows($login) < 1) { $sess['inTime'] == ''; session_destroy(); $login = '0'; } else { // logged in, lets update the database for last_activity AND the session. $this->sql_query("UDATE users SET lastActivity = '".now()."' WHERE emailAddress = '".$this->user."'"); $login = $this->sql_query("SELECT * FROM users WHERE emailAddress = '".$this->user."' AND password = '".$this->pass."' AND status = '1' LIMIT '1'"); $login = mysql_fetch_assoc($login); foreach ($login as $key => $value) { $sess[$key] = $value; } $sess['inTime'] = time(); $login = '1'; } return $login; } } ?> That is the main function, sql_query and sql_numrows is: <?php function sql_query($query = "", $transaction = FALSE) { unset($this->query_result); if ($query != "") { $this->num_queries++; if ($transation == BEGIN_TRANSACTION && !$this->in_transation) { $result = mysql_query("BEGIN", $this->db_connect_id); if (!$result) { return false; } $this->in_transaction = TRUE; } $this->query_result = mysql_query($query, $this->db_connect_id); } else { if ($transaction == END_TRANSACTION && $this->in_transaction ) { $result = mysql_query("COMMIT", $this->db_connect_id); } } if ($this->query_result) { unset($this->row[$this->query_result]); unset($this->rowset[$this->query_result]); if ($transaction == END_TRANSACTION && $this->in_transaction ) { $this->in_transaction = FALSE; if (!mysql_query("COMMIT", $this->db_connect_id)) { mysql_query("ROLLBACK", $this->db_connect_id); return false; } } return $this->query_result; } else { if ($this->in_transaction ) { mysql_query("ROLLBACK", $this->db_connect_id); $this->in_transaction = FALSE; } return false; } } function sql_numrows($query_id = 0) { if(!$query_id) { $query_id = $this->query_result; } return ($query_id) ? mysql_num_rows($query_id) : false; } ?> Any insight that can help to benefit these functions would be appreciated. Question 1) Is the only and proper way to call a parent function "parent::function()"? Are there other/better ways from within a child function? Question 2) What are the deciding factors for when to make a function or attribute static? How do you make that decision? Assuming 5.3... Thanks. I need to call usort from a class function, and I'm puzzled about how to define the comparison function. I've tried to define the comparison function in the same class, but I can't get usort to call it. I found one hint that it will work if I make the comparison function static, but I tried that, and it didn't work for me. If I define the comparison function outside the class, it won't have access to object properties that it needs to operate. The only solution I can think of is to define the comparison function outside the class and put the object properties it needs in globals. Is there a cleaner way to do this? I know this is not coding.. However... How tolerant is PHP from generating a random output from 1000s of entry columns in a mysql database. I would like to make a script that would potentially pick one of a 1000 results at random. is this a problem with being ran multiple times? It's working great, but at some points after one of the random events goes through, I reload the page and it either gives me or takes away some starpoints without showing the message.. but it shows the message all the other times. Could someone help me debug this and see why it's doing that? Code: [Select] <?php include("config.php"); //To change the odds, change the second number in the rand() function. $rand = rand(1,3); if($rand == 1) { $sql = "SELECT * FROM randomevents WHERE rarity <= '10'"; $result = mysqli_query($cxn, $sql); //Write the events in here with the opener: $event[] = "#your event#"; while ($row = mysqli_fetch_assoc($result)) { $event[] = $row['phrase']; } //This will pick a random event and show it $renum = rand(0,count($event)); $display = $event[$renum]; if ($display == "") { $eventdisplay = ""; } else { $eventdisplay = "<table cellspacing=\"0\" class=\"events\" align=\"center\"><br> <tr><br> <td><center><b><h1>Random Event</h1></b></center></td><br> </tr><br> <tr><br> <td><img src=\"".$_SERVER['SCRIPT_NAME']."\"> <p><center>".$display."</center></p><br> </td><br> </table><br>"; $sql = "SELECT type FROM randomevents WHERE phrase='".$display."'"; $result = mysqli_query($cxn, $sql); $row = mysqli_fetch_assoc($result); if ($row['type'] == "gainsp") { $rand = rand(200,500); $sql = "UPDATE members SET starpoints = starpoints+$rand WHERE userid='".$_SESSION['userid']."'"; mysqli_query($cxn, $sql) or die("Query died: updating starpoints"); } elseif ($row['type'] == "losesp") { $rand = rand(50,100); $sql = "UPDATE members SET starpoints = starpoints-$rand WHERE userid='".$_SESSION['userid']."'"; mysqli_query($cxn, $sql) or die("Query died: updating starpoints"); } else {} } } else { $eventdisplay = ""; } ?> how do I pull out two random integers at the same time without ever possibly choosing the same integer twice? Hi, I'm having trouble generating random string with 8 characters, when I refresh I sometimes get 6 characters and sometimes 8. "-" not included as character. Wrong: 6JW-F7W Correct: (should always generate random like this) DVMF-F36V I know I'm trying to achieve this in wrong methods but it's the only way I know. Hope someone can help. function getReference() { $length = 8; $characters = "0123456789abcdefghijklmnopqrstuvwxyz"; for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, strlen($characters))]; } return strtoupper(substr($string, 0, -$length/2)."-".substr($string, $length/2-1, -1)); } Hi Guys I need some help this is my first real php website. Im trying to retrieve results from an accommodation database, to make the results fair I need to return a random set of results so each accommodation get a fair viewing and nobody is always at the bottom. The problem arises when i paginate the results, because each page executes a separate randomly ordered offset mysql query I can end up showing the some of the same results over and over on multiple pages. This is going to confuse and irritate searchers. How can i achieve results and paginate them where each accommodation gets a fair chance at the first page each time the database is searched? is there a way to make a random number input into mysql? like if i add a new customer to a table, i want to assign a random number to that customer. Hi Everyone, I was wondering if anyone could help me make this code I wrote better and a bit more readable and shorter. I have 8 images on the home page so the php code is like this: Code: [Select] <?php $images = array('image1', '8', 'image2', 'image7', 'image5', 'image4', '9', 'image6'); $i = rand(0, count($images)-1); $selectedImage1 = "_images/showreel/{$images[$i]}.jpg"; ?> <?php $images = array('image1', '8', 'image2', 'image7', 'image5', 'image4', '9', 'image6'); $i = rand(0, count($images)-1); $selectedImage2 = "_images/showreel/{$images[$i]}.jpg"; ?> <?php $images = array('image1', '8', 'image2', 'image7', 'image5', 'image4', '9', 'image6'); $i = rand(0, count($images)-1); $selectedImage3 = "_images/showreel/{$images[$i]}.jpg"; ?> <?php $images = array('image1', '8', 'image2', 'image7', 'image5', 'image4', '9', 'image6'); $i = rand(0, count($images)-1); $selectedImage4 = "_images/showreel/{$images[$i]}.jpg"; ?> <?php $images = array('image1', '8', 'image2', 'image7', 'image5', 'image4', '9', 'image6'); $i = rand(0, count($images)-1); $selectedImage5 = "_images/showreel/{$images[$i]}.jpg"; ?> <?php $images = array('image1', '8', 'image2', 'image7', 'image5', 'image4', '9', 'image6'); $i = rand(0, count($images)-1); $selectedImage6 = "_images/showreel/{$images[$i]}.jpg"; ?> <?php $images = array('image1', '8', 'image2', 'image7', 'image5', 'image4', '9', 'image6'); $i = rand(0, count($images)-1); $selectedImage7 = "_images/showreel/{$images[$i]}.jpg"; ?> <?php $images = array('image1', '8', 'image2', 'image7', 'image5', 'image4', '9', 'image6'); $i = rand(0, count($images)-1); $selectedImage8 = "_images/showreel/{$images[$i]}.jpg"; ?> And the HTML is like this: Code: [Select] <div id="slider1" class="nivoSlider"> <img src="<?php echo $selectedImage1; ?>" alt="John Richard Cleckheaton West Yorkshire" /> <img src="<?php echo $selectedImage2; ?>" alt="John Richard Cleckheaton West Yorkshire" /> <img src="<?php echo $selectedImage3; ?>" alt="John Richard Cleckheaton West Yorkshire" /> <img src="<?php echo $selectedImage4; ?>" alt="John Richard Cleckheaton West Yorkshire" /> <img src="<?php echo $selectedImage5; ?>" alt="John Richard Cleckheaton West Yorkshire" /> <img src="<?php echo $selectedImage6; ?>" alt="John Richard Cleckheaton West Yorkshire" /> <img src="<?php echo $selectedImage7; ?>" alt="John Richard Cleckheaton West Yorkshire" /> <img src="<?php echo $selectedImage8; ?>" alt="John Richard Cleckheaton West Yorkshire" /> </div> I no this code is terrible but I am still learning. Just a few months ago I had never touched PHP. Any help would be greatly appreciated. Regards Barry Is there anyway in MySQL you can select a random record in a table? I normally do this by generating a random number first and then using that number to find a record but was wondering if there is an easier way. Thanks for any help. Okay, minor issue, but not sure how to resolve. I have a form that processes through PHP and has it's fields validated with JS and sends the data to an e-mail address and a database. It works fine, but there are random times where a submitted entry will show up blank in the e-mail and not be in the database at all, any ideas on what might be causing this? Thanks. Alright, I have a random thing going on. Works perfectly fine. This is the code: Code: [Select] <?php include("config.php"); //To change the odds, change the second number in the rand() function. $rand = floor(rand(0,1)); if($rand == 1) { $sql = "SELECT * FROM randomevents WHERE rarity <= '10'"; $result = mysqli_query($cxn, $sql); while ($row = mysqli_fetch_assoc($result)) { $event[] = $row['phrase']; if ($row['type'] == 'gainsp') { $rand = rand(200,500); $sql = "UPDATE members SET starpoints = starpoints+$rand WHERE userid='".$_SESSION['userid']."'"; mysqli_query($cxn, $sql) or die("Query died: updating starpoints"); } } //This will pick a random event and show it $renum = floor(rand(0,count($event))); $eventdisplay = $event[$renum]; } ?> In the database, I have the phrases set as: "You have gained {$rand} starpoints!". How do you make that variable echo out as the $rand I'm generating on this page? It just keeps posting as is. When I went the {$rand} to display as the number I'm generating to set their starpoints to. So I guess how do you hold a variable in the database? Does anyone understand what I'm asking? Here as an image to help understand: Hi, I want to pick out a random letter from a to h. How can I do this? So everytime the page re-loads, a random letter (range a-h) will show. Thanks alot for any help. Hi All I am using the below code to display users registered on my site: Code: [Select] <div class="profilbox" id="apDiv11"><div></div> <div align="center">Registered Users</div> <div class="text_area"><?php //to display image from source - registerd users $dir = "profpics"; echo '<table>'; $result = mysql_query("SELECT * FROM users order by id"); while ($row = mysql_fetch_assoc($result)) { echo "<tr><td><img src=\"$dir/{$row['prof_pic']}\" width='40' height='40'>{$row['username']}</td></tr>"; } //close out table echo '</table>'; ?></div> </div> Could anybody tell me how i can limit this to 3 random results? I then plan adding a link to 'see all' Hi Guys, I have a php script to upload a photo to a mysql table. This works great, until someone uploads a file with the same name, then it replaces the old one. Bad times! So Ive researched it and I have put a timestamp on the filename and it uploads with the correct timestamp in the images folder. However the data that it uploads to the table is just the original filename, ie it doesnt stamp the filename in the table therefore they dont match... Any ideas... <?php include('config.php'); if (isset($_GET['Ter']) ) { $ter = (int) $_GET['Ter']; if (isset($_POST['submitted'])) { //Photo Upload //This is the directory where images will be saved $name=time(); $target = "images/"; $target = $target .$name. basename( $_FILES['photo']['name']); //This gets all the other information from the form $photo = ($_FILES['photo']['name']); //Pause Photo Upload foreach($_POST AS $key => $value) { $_POST[$key] = mysql_real_escape_string($value); } $sql= "UPDATE `ter` SET `Ter` = '{$_POST['Ter']}' , `BranchName` = '{$_POST['BranchName']}' , `BranchAddress` = '{$_POST['BranchAddress']}' , `BranchTel` = '{$_POST['BranchTel']}' , `BranchEmail` = '{$_POST['BranchEmail']}' , `BranchLink` = '{$_POST['BranchLink']}' , `Theme` = '{$_POST['Theme']}' , `LocalInfo` = '{$_POST['LocalInfo']}' , `BranchInfo` = '{$_POST['BranchInfo']}' , `photo` = '{$_FILES['photo']['name']}' WHERE `Ter` = '$ter' "; mysql_query($sql) or die(mysql_error()); //Unpause Photo Upload //Writes the photo to the server if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) { //Tells you if its all ok echo "<br />The file ". basename( $_FILES['photo']['name']). " has been uploaded. <br />"; } else { //Gives and error if its not echo ""; } //End of Photo Upload echo (mysql_affected_rows()) ? "<br />Edited Branch.<br />" : "<br />Nothing changed. <br />"; } $row = mysql_fetch_array ( mysql_query("SELECT * FROM `ter` WHERE `Ter` = '$ter' ")); ?> here is the database: its a facebook app i want that my sql will choose every time random but considerate in the sex parameter. i mean that if the user is boy i will put it in parameter and boys is num-1 girls-0 and if the user is boy it will run random sql just on the boys and if its girls so random on the girls here what i did: $sql = "SELECT * FROM pcm ORDER BY RAND() LIMIT 1"; $Recordset3 = mysql_query($sql) or die(mysql_error()); $row2 = mysql_fetch_object($Recordset3); print_r($row2); but for some reason i get an error that the database is not selected maybe i didnt select my database right? please help tnx.... hello, i am trying to see how i can pick a random number between 1-15 and exclude certain numbers. so i have a staff list that once a random number is created it inserts it into the staffnumber field. so the next time i create a random number for a staff, i want to make sure that the random number doesnt select an existing staffnumber. thanks! |