Using while() and continue in PHP - php

I am learning PHP and trying to use the while and continue expressions correctly.
I have a script that creates a 6 digit PIN, and I want to ensure that it is unique, otherwise I want to generate another PIN.
while(1) {
$pin = rand(111111,999999);
$sel = mysql_query("SELECT * FROM formusers WHERE pin = '$pin'");
if(mysql_num_rows($sel) != 0) { continue; }
mysql_query("INSERT INTO formusers(email,password,pin) VALUES('".$_POST['srEmail']."','".$_POST['srPass']."','".$pin."')");
if(mysql_affected_rows()!=-1) {
echo "Pin:" . $pin;
exit;
} else {
echo "Existing email, try again<br />";
}
break;
}
Do I have the syntax for the loop correct? It seems to work, but there's no way for me to debug it in the instance the rand() function creates the same PIN twice.
Also, in the event I did run out of unique PINs, what would happen here? Presumably it would loop indefinitely? Is there any way to prevent this?

Yeah, the code works, but as stated the infinite loop is concerning. You could possibly solve that like this:
var $i = 0;
while($i < 10) {
$i++;
$pin = rand(111111,999999);
$sel = mysql_query("SELECT * FROM formusers WHERE pin = '$pin'");
if(mysql_num_rows($sel) != 0) { continue; }
mysql_query("INSERT INTO formusers(email,password,pin) VALUES('".$_POST['srEmail']."','".$_POST['srPass']."','".$pin."')");
if(mysql_affected_rows()!=-1) {
echo "Pin:" . $pin;
exit;
} else {
echo "Existing email, try again<br />";
}
break;
}
This would ensure you would never make more than 10 iterations. However, the larger problem is probably that even that sampling size won't work in the future. This presents a bit of a conundrum. One possible approach is to determine how many unique numbers exist before starting the loop by counting them and then iterate that many times, but that approach is something like n2 (maybe, I'm not real good on big-O, I just know it would be bad).

You can leverage the unique nature of php array keys for this.
function getPins($qty){
$pins = array();
while (count($pins) < $qty){
$pins[rand(111111,999999)] = "";
}
return array_keys($pins);
}
This will make sure that for a given run you will get $qty number of unique pins. You might want to look at appending a unique prefix to each run of the function to avoid multiple runs creating collisions between the two.

You can seed random, so it gives you the same values every time, you run it:
srand (55 ); //Or some other value.
The while loop syntax looks okay to me.

Related

I don't know what to do with the probability draw

I am currently giving a score of one or more people and choosing to draw more than one person based on the score. However, there is still a runtime error and is not being resolved. Please let me know how to this problem solve.
this is my code:
$selectChildrens = array();
for($i=0;$i<$recuTotal;$i++){
$random = rand(0,sizeof($childSelectArray)-1);
$selectChild = $childSelectArray[$random];
$sameCheck = 0;
if(sizeof($selectChildrens) == 0){
array_push($selectChildrens,$selectChild);
while(($key = array_search($selectChild,$childSelectArray)) != NULL){
unset($childSelectArray[$key]);
}
$recuTotal—;
$i=0;
}else{
array_push($selectChildrens,$selectChild);
while(($key2 = array_search($selectChild,$childSelectArray)) != NULL){
unset($childSelectArray[$key2]);
}
$recuTotal—;
$i=0;
}
}
I see that your attempt to decrement $recuTotal is not using correct syntax.
Use this line instead: $recuTotal--
You are using a long dash, but need two hyphens.
As for your array_search() lines, I always use: !==false though I'm not sure it matters.
Lastly, you can use !sizeof($selectChildrens) as a shorter if statement.
Though I'll admit I didn't fully comb your code to see what it is doing, this is a DRYer code block that will perform the same way:
$selectChildrens = array();
for($i=0;$i<$recuTotal;$i++){
$random = rand(0,sizeof($childSelectArray)-1);
$selectChild = $childSelectArray[$random];
$sameCheck = 0;
array_push($selectChildrens,$selectChild);
while(($key=array_search($selectChild,$childSelectArray))!==false){
unset($childSelectArray[$key]);
}
$recuTotal--;
$i=0;
}

How to Exclude selection and all related (MySQL + PHP)

I am trying to solve a mysteries code that writing a number in a choice I will get all opposite of that number
I did almost done with that the only problem with it I might have the opposite recalled as he does have another recorded in another course
In more word my PHP about courses when I do ask MY PHP course it well give me all people how did not take course 1 but some people were recalled as they have other courses
The Problem when I choose For Example Course X I do get All Who Did not Take Course X But Some where Called From The same Table cause They Do Have Taken Other Courses In the same table
I did resolve The first Problem Using the following code
if(isset($_GET['course_guid']) && $_GET['course_guid']!="" )
$f.=" AND s.course_guid != '".$_GET['course_guid']."'";
And I Did Create Another page Select.php To Omit All Identified People from Orig.php using The Following Code
<?php
if(isset($_GET['id']))
foreach($_GET as $key => $post)
$_GET[$key]=m($post);
$ff="";
if(isset($_GET['id']) && $_GET['id']!="")
$ff.=" AND cs.id = '".$_GET['id']."' ";
$prns =(isset($_GET['prn'])? $_GET['prn']:'');
if(isset($prns) && $prns!="")
$ff.=" AND cs.prn = '".$prns."' ";
$course_guids =(isset($_GET['course_guid'])? $_GET['course_guid']:'');
if(isset($course_guids) && $course_guids!="")
$ff.=" AND cs.course_guid = '".$course_guids."' ";
$from_time=system_time();
$date_from= date("d",$from_time)."-".date("m",$from_time)."-".date("Y",$from_time);
$date_to=date("d",system_time())."-".date("m",system_time())."-".date("Y",system_time());
if(isset($_GET['alldates']) && $_GET['alldates']=="on") {
$t_f=mktime(0,0,0,6,1,2011);
$t_t=system_time();
} else {
$t_f=mktime(0,0,0,substr($date_from,3,2),substr($date_from,0,2),substr($date_from,6,4));
$t_t=mktime(23,59,59,substr($date_to,3,2),substr($date_to,0,2),substr($date_to,6,4));
}
$query="SELECT cs.id,cs.prn,cs.course_guid FROM courses_attend cs
WHERE cs.time BETWEEN $t_f AND $t_t
$ff
";
//echo "$prns";
$rs22 = mysql_query($query) or die(mysql_error());
// $total22 = mysql_num_rows($rs22);
/*
while($row22=mysql_fetch_assoc($rs22))
{
$prnss =(isset($row22['prn'])? $row22['prn']:'');
print($prnss);
}
*/
?>
print($prnss); // this should be the code needed to be recalled In Orig.php
and It should Be Called Inside a loop mysql_fetch_array which is cannot be Used In orig.php Cause I do already Have a structure and Another Loop In that page Cause real Output Interface is there
as far as I do know I do think function callback() would be a solve on the other hand I do not know how to create one
// Answer
for ($i= 0; $i < mysql_num_rows($rs22);$i++) {
$row22 = mysql_fetch_assoc($rs22);
$prnss = $row22['prn'];
// echo "$prnss"; // return print all Omitted data
// echo "<br />\n";
$f.=" AND s.prn != '".$prnss."' ";
}
Solved By Adding This In Orig.php
On the other hand and after testing Select.php DATA can be added TO the Orig.php
Best regards

goto equivalent for php version < 5.3.0?

I need to use the goto operator in my code as I can't seem to think of a way around it. However the problem is my host only has PHP version 5.2.17 installed.
Any ideas?
Below is my code:
if ($ready !=="y")
{
$check=mysql_query("SELECT `inserted` FROM `team`");
$numrows = mysql_num_rows($check);
$i="0";
while ($i<$numrows && $row = mysql_fetch_assoc($check))
{
$array[$i] = $row['inserted'];
$i++;
}
if (in_array("n", $array))
{
goto skip;
}
else
{
mysql_query("
UPDATE game SET ready='y'
");
}
}
skip:
There are a few anti-patterns in your code. Let's clean it up. I'll explain what's been changed in a jiffy.
if($ready !== "y") {
$sth = mysql_query("SELECT inserted FROM team WHERE inserted = 'n'");
if(mysql_num_rows($sth) > 0) {
mysql_query("UPDATE game SET ready = 'y'");
}
}
First things first: There is no need to perform a query, fetch all of the results, then loop through those results (in_array) looking for a specific value. Let the database do that for you by expressly looking only for rows where inserted is the string literal "n".
Because we know that we're only getting "n" records back, we just need to check if there are any results. If so, run the query. If there are no "n" records, the UPDATE isn't run.
If you need to know that the UPDATE ran, add a check for it:
$ran_update = false;
if($ready !== "y") {
$sth = mysql_query("SELECT inserted FROM team WHERE inserted = 'n'");
if(mysql_num_rows($sth) > 0) {
mysql_query("UPDATE game SET ready = 'y'");
$ran_update = true;
}
}
if($ran_update) {
// ...
}
You want to use the correct control word to break from the loop:
if ($ready !=="y")
{
$check=mysql_query("SELECT `inserted` FROM `team`");
$numrows = mysql_num_rows($check);
$i="0";
while ($i<$numrows && $row = mysql_fetch_assoc($check))
{
$array[$i] = $row['inserted'];
$i++;
}
if (in_array("n", $array))
{
break;
}
else
{
mysql_query("
UPDATE game SET ready='y'
");
}
}
The break keyword will do exactly what you want: End the execution of the while loop. Never ever ever use a goto!
As a direct response to the title of this post:
do{
if (!$condition){
break;
}
// Code called if conditions above are met
}while(0);
//Code always called
In some circumstances, this, or a goto, can make for very tidy and readable code.
First, you could use a break to exit your initial loop. Second, if you need to test for anything, set a variable (must be global not local) as a flag or indicator before calling break, then do a conditional test statement where your skip line is to perform any additional steps you need.

SQL Result Random loop through

I have a SQL database that contains a field. I can get all of the elements in that field by:
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){
$ftype =$row['ftype']; //name of field is 'ftype'
print $ftype} //do something
I want a random element to be printed out each time the page is opened/refreshed.
Knowing that the result is an array containing the information i want, I want to randomly choose an element of the array. Also, if there are N elements in the array, I want to choose all N elements exactly once before I show any element again for second time. The process repeats itself. I know how to code something like this in java or python, but I don't think that's the way I should go.
I think I need to use javascript, but I'm just not sure what technology to use.
UPDATE:
Patrick's idea seems to be exactly what i was looking for. I thought I would share what I have now and maybe you can suggest optimization. I hope the intent in the code is obvious.
<?
session_start();
if (!isset($_SESSION['count']) || !isset($_SESSION['randomArray'])) {
$count = 0;
$randomArray = array();
$sql="SELECT youtubeurl FROM Foodlist";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){
array_push($randomArray,$row['youtubeurl']);
}
shuffle($randomArray);
$_SESSION['randomArray'] = $randomArray;
$_SESSION['count'] = $count;
} elseif ($_SESSION['count'] >= sizeof($_SESSION['randomArray'])){
$_SESSION['count'] = 0;
$randomArray = $_SESSION['randomArray'];
shuffle($randomArray);
$_SESSION['randomArray'] = $randomArray;
} else{
$randomArray = $_SESSION['randomArray'];
$count = $_SESSION['count'];
echo $randomArray[$count];
$_SESSION['count']++;
}
?>
You can do this without Javascript, however you'll need to open/maintain a session.
Pseudocode:
data = data_from_mysql()
choice = random.choice(data, exclude = SESSION['choices'])
SESSION['choices'].append(choice)
print choice
if len(SESSION['choices']) == len(data):
SESSION['choices'] = []
If you want a random result let the dbms take care of it. Add this to the bottom of your sql query.
ORDER BY RAND()
LIMIT 1

When listing information from a database using php and mysql how would you make the first row look different to the rest?

Basically I have articles in my database and I want to alter the way the first record displays. I want the lastest (Posted) article to be the focus and the older article just to list, (see F1.com). I need to know how to get the first of my values in the array and get it to display differently but I am not sure how to do this, I can do it so all rows display the same just not how to alter the first row. I also need to know how to tell the rest of the rows to display the same afterwards im guessing you use an if statement there and before that some kind of count for the rows.
Current code:
$result = mysql_query("SELECT * FROM dbArticle WHERE userID='".$_SESSION["**"]."' ORDER BY timestamp DESC");
while($row = mysql_fetch_array($result))
{
echo "<h2 class=\"heading1\">". $row['title'] ."</h2>";
echo "By: ".$row['username']." Type: ".$row['type']." Posted: ".$row['timestamp']."
$body = $row['body'];
echo "<br/><p>";
echo substr("$body",0,260);
echo "...<span class=\"tool\"><a class=\"blue\" href=\"index.php?pageContent=readArticle&id=".$row['id']."\">Read More</a></span></p><hr/>";
}
mysql_close($con);
Ok I have taken Luke Dennis's code and tried to test it, but I am getting this error: Warning: Invalid argument supplied for foreach() this is the line of the foreach statment. Something that has just come to mind is that I will only want 5 or so of the older articles to display. This is what I have thats creating the error:
<? $con = mysql_connect("localhost","****","***");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("******", $con);
$result = mysql_query("SELECT * FROM dbArticle ORDER BY timestamp DESC");
$first = true;
foreach($result as $row){
if($first)
{
echo"".$row['title']."";
echo"this is the headline";
$first = false;
}
else
{
echo"".$row['title']."";
}
}
?>
Do I need to add mysql_fetch_array somewhere to set the array up?
I would just iterate through the results and apply a css class to the first entry:
$first = true;
while ($row = mysql_fetch_assoc($result)) {
$cssClass = '';
if ($first) {
$cssClass = 'highlight';
}
echo '<p class="' . $cssClass . '">' . $row['text'] . '</p>';
$first = false;
}
It's a bit crude, but I often hard-code a variable to designate the first run through a loop. So something like:
$first = true;
foreach($list_of_items as $item)
{
if($first)
{
// Do some stuff
$first = false;
}
else
{
// Do some other stuff
}
}
A simple if statement when looping through your results will usually do the trick. You can use a boolean to indicate if you've output the first row of results or now. If you haven't then give it a particular style and then set the boolean to true. Then all subsequent rows get a different style.
All of the above are correct. Luke Dennis' post is of course fleshed-out a bit more.
As Brian Fisher said, add some CSS styling to the first link when you encounter it per Luke's post.
I took a look at the article list on the F1 website. Pretty well constructed site - "One would expect that." :-)
Anyway, the article listings are contained within a two row table (summary="Latest Headlines") in descending order (newest first).
Just place a class in the second column (<td class="first-news-article">). Then add the class name and appropriate styling values in the css file - probably your' modules.css. There's already quite a few class values associated with articles in that file, so you may be able to just use an existing value.
That should be about it - other than actually doing it!
By the way, judging by the quality of the underlying html, I'm assuming there's already an "article list emitter." Just find that emitter and place the appropriate conditional to test for the first record.
Darrell
I just noted your code addition. I assume that you were showing the F1 site as an example. Anyway, I think you're on your way.
I presume you have some code that loops through your resultset and prints them into the page? Could you paste this code in, and that might give us a starting point to help you.
I don't know PHP, so I'll pseudocode it in Perl. I wouldn't do it like this:
my $row_num = 0;
for my $row ($query->next) {
$row_num++;
if( $row_num == 1 ) {
...format the first row...
}
else {
...format everything else...
}
}
The if statement inside the loop unnecessarily clutters the loop logic. It's not a performance issue, it's a code readability and maintainability issue. That sort of thing just BEGS for a bug. Take advantage of the fact that it's the first thing in the array. It's two different things, do them in two different pieces of code.
my $first = $query->next;
...format $first...
for my $row ($query->next) {
...format the row...
}
Of course, you must make the first row stand out by using tags.
I'd use array_shift():
$result = mysql_fetch_assoc($resultFromSql); // <- edit
$first = array_shift($result);
echo '<h1>'.$first['title'].'</h1>';
foreach ($result as $row) {
echo '<h2>'.$row['title'].'</h2>';
}
The best way to do this is to put a fetch statement prior to the while loop.
Putting a test inside the while loop that is only true for one iteration can be a waste of time for a result of millions of rows.

Categories