Despite what our teachers may have said, there is such a thing as a stupid question. And generally, newbies are the ones asking ‘em. I know I sure did (thankfully, under a pseudonym). But unlike the mean-old folks who would often answer my questions (“RTFM, idiot!”), I don’t believe in picking on those trying to learn. In fact, today, it’s time to pick on someone trying to teach…
Gonzalo Larralde pointed me to discussion on a coding messageboard where a poster asked a fairly simple, naïve question: “How do I create a multithreaded application using PHP. i want to write scripts that run parallelly.” As I’ve discussed before (see Pounding A Nail: Old Shoe or Glass Bottle?), my response would have been an explanation of what’s fundamentally wrong with such a question. Another poster, however, had a different answer…
Let us suppose you want to send 1000 emails, using 10 threads and each thread will send 100 emails, so here is how you do it.
You will need two pages. One page to call the task and the other page will be the task itself.
Make two pages. One as main.php and the other as thread.php.
thread.php page will contain your code to send emails from people in the database and main.php will build html image <img> tag in loop. This image tag will not have an image in it, but instead will call thread.php file in a remote instance.
The code for main.php page is something like this.
<? //START A LOOP //thread.php is being sent with 3 parameters in query string. //'from' parameter will tell the thread.php page that where the records should start. //'to' parameter will tell the thread.php page that where the records should end. //change the above 2 parameters to whatever you want //'refresh' parameter is being passed with the $i variable to make sure the page is not cached. for($i=1;$i<=10;$i++){ echo "<img border=0 src='thread.php?from=1&to=1000&refresh=$i' width=0 weight=0>"; } ?>The code for thread.php page is something like this.
<? //connect to database here.... $from = $_GET['from']; $to = $_GET['to']; $sql="SELECT * FROM mailing_list_table WHERE list_id between $from and $to";
$rs = mysql_query($sql) or die(mysql_error()); while($row=mysql_fetch_array($rs)){ //send mail here to each record } mysql_free_result($rs); ?>