Hi David,
The first half of the code below works fine with data being entered into the database correctly.
The second half is supposed to randomly select a single row from the same database however if I use it within the myRecordHandler function as in the code below, instead of returning a single random url I get every url in the database all joined up or concatenated. If the code from the second half is taken out of the function altogether and run from a separate file the correct data is returned.
What am I doing wrong?
Thanks.
<?php
mysql_connect("", "", "") or die(mysql_error());
mysql_select_db ("");
function myRecordHandler($item)
{
mysql_query("INSERT INTO merchanturls (link, date) VALUES ('".trim($item["MERCHANTURL"])."', CURDATE());");
//First Half
////////////////////////
//Second Half
$result = mysql_query("SELECT * FROM `merchanturls` ORDER BY RAND() LIMIT 0,1;");
while ($r = mysql_fetch_array($result)) {
$row1 = $r["id"];
$row2 = $r["link"];
$row3 = $r["date"];
}
echo "$row1";
print "$row2";
//echo "$row3";
}
// fetch the response and parse the results
MagicParser_parse($url,"myRecordHandler","xml|PRODUCTSEARCH/RESULTLIST/RESULT/");
?>
Hi David,
Your re-code worked perfectly first time I understand what you have said about truncating, many thanks!
I recently purchased my first PHP book but still need to pop along for lessons.
Hello Dave,
I'm not sure from the code what you're trying to do with the second part; as it stands it will print out more or less every record (some may be repeated, it depends how random rand() is being) since myRecordHandler is being called for every record in your XML.
Does the following code do what you're expecting:
<?php
mysql_connect("", "", "") or die(mysql_error());
mysql_select_db ("");
function myRecordHandler($item)
{
mysql_query("INSERT INTO merchanturls (link, date) VALUES ('".trim($item["MERCHANTURL"])."', CURDATE());");
}
// fetch the response and parse the results
MagicParser_parse($url,"myRecordHandler","xml|PRODUCTSEARCH/RESULTLIST/RESULT/");
$result = mysql_query("SELECT * FROM `merchanturls` ORDER BY RAND() LIMIT 0,1;");
while ($r = mysql_fetch_array($result)) {
$row1 = $r["id"];
$row2 = $r["link"];
$row3 = $r["date"];
}
echo "$row1";
print "$row2";
//echo "$row3";
?>
The only thing to bear in mind of course is that unless you are TRUNCATing the table each time you run the script you are probably building up the database of lots of identical rows - unless "link" is a unique or primary key. In a script such as this, you would often expect to see something like:
mysql_query("TRUNCATE merchanturls");
...just before your call to MagicParser_parse()...
Hope this helps!
Cheers,
David.