I'm trying to count visitor dates to see how many visits there are per month & post the result into a jquery chart.
Ok so this code below "works", but it somehow counts everything * 2. If there is 1 visitor this month it will output 2, why is that?
I would also like to know how can I make this code smaller? $jan $feb etc. seems not the way this should be done, but I'm a beginner so I don't really know how this code can be made smaller & better. Can somebody help me with this?
Database:
date
2016-11-17 16:36:12
Php:
$jan = ''; $feb = ''; $maa = ''; $apr = ''; $mei = ''; $jun = ''; $jul = ''; $aug = ''; $sep = ''; $okt = ''; $nov = ''; $dec = '';
foreach($dates as $date){
$month = date_parse_from_format("Y-m-d H:i:s", $date->date);
if($month ["month"] == '01'){$jan .= $month ["month"];}
if($month ["month"] == '02'){$feb .= $month ["month"];}
if($month ["month"] == '03'){$maa .= $month ["month"];}
if($month ["month"] == '04'){$apr .= $month ["month"];}
if($maand["month"] == '05'){$mei .= $month ["month"];}
if($maand["month"] == '06'){$jun .= $month ["month"];}
if($maand["month"] == '07'){$jul .= $month ["month"];}
if($maand["month"] == '08'){$aug .= $month ["month"];}
if($maand["month"] == '08'){$sep .= $month ["month"];}
if($maand["month "] == '10'){$okt .= $month ["month"];}
if($maand["month "] == '11'){$nov .= $month ["month"];}
if($maand["month "] == '12'){$dec .= $month ["month"];}
}
$visitsPerMonth = [];
foreach ($dates as $date) {
$month = date('m', strtotime($date->date));
$visitsPerMonth[$month]++;
}
If $dates is originating in a SQL database, instead use a GROUP BY query.
Use json_encode() on $visitsPerMonth if your jQuery chart expects JSON input.
try this:
$arr = array()
foreach($dates as $date){
$month = date('m',strtotime($date->date));
$arr[$month][] = $date;
}
Here this code creates an array an takes month as key and append data for that month as values.
As per you requirements if you are storing visits data in database then you can get the count from database query as per month like this
SELECT COUNT(*) FROM visitors YEAR(visited_date) = '2016' GROUP BY MONTH(visited_date)
If there is 1 visitor this month it will output 2, why is that?
This is because you are concatenating the string and counting the length of string. The month is of 2 characters so every time it iterates it concatenated 2 characters per iteration. See the example bellow
Case 1: $data has 1 date 2016-11-17 16:36:12
$nov = ''; // at start
$nov .= $month ["month"]; // date 2016-11-17 16:36:12
=> $nov .= '11'; //shorthand concatenation php
=> $nov = $nov . '11';
=> $nov = '' . '11'; // as $nov = '' at start
count($nov); // $nov have value '11' which has 2 character so output will be 2
Case 2: $data has 2 dates 2016-11-17 16:36:12 2016-11-18 16:36:12
$nov = ''; // at start
$nov .= $month ["month"]; // date 2016-11-17 16:36:12
=> $nov .= '11'; //shorthand concatenation php
=> $nov = $nov . '11';
=> $nov = '' . '11'; // as $nov = '' at start
now $nov have value 11 in it.
$nov .= $month ["month"]; // date 2016-11-18 16:36:12
=> $nov .= '11'; //shorthand concatenation php
=> $nov = $nov . '11';
=> $nov = '11' . '11'; // as $nov has vale 11 in it
count($nov); // $nov have value '1111' which has 4 character so output will be 4
If you want your code to work do like this
$jan = 0; $feb = 0; $maa = 0; $apr = 0; $mei = 0; $jun = 0; $jul = 0; $aug = 0; $sep = 0; $okt = 0; $nov = 0; $dec = 0;
foreach($dates as $date){
$month = date_parse_from_format("Y-m-d H:i:s", $date->date);
if($month ["month"] == '01'){$jan++}
if($month ["month"] == '02'){$feb++;}
if($month ["month"] == '03'){$maa++;}
if($month ["month"] == '04'){$apr++;}
if($maand["month"] == '05'){$mei++;}
if($maand["month"] == '06'){$jun++;}
if($maand["month"] == '07'){$jul++;}
if($maand["month"] == '08'){$aug++;}
if($maand["month"] == '08'){$sep++;}
if($maand["month "] == '10'){$okt++;}
if($maand["month "] == '11'){$nov++;}
if($maand["month "] == '12'){$dec++;}
}
But i will suggest you to do in array like this
$visitorData = ['01'=>0,'02'=>0,'03'=>0,'04'=>0,'05'=>0,'06'=>0'07'=>0,'08'=>0,'09'=>0,'10'=>0,'11'=>0,'12'=>0];
foreach ($dates as $date) {
$month = date('m', strtotime($date->date));
$visitorData[$month]++;
}
Then JSON encode the array to feed it to the jquery
Hope this will help
Related
Okay I am wondering how I get two countdown timers on the one page?
<script type = 'text/javascript'>
window.onload=function() {
setInterval("<?php
$array = count($settime);
for ($i = 0; $i < $array; $i++) {
$thitime = explode(":", $settime[$i]);
echo "timeleft(" . $thitime[1] . ", " . $thitime[0] . "); ";
}
?>", 1000);
}
function timeleft(string, id)
{
var xmlhttp=GetXmlHttpObject();
if(xmlhttp==null) { alert("Sorry, Your browser doesnt support HTTP Requests");
return;
}
var elem = "time" + id;
var load = "time_left.php?string=" + string;
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState==4) {
document.getElementById(elem).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", load, true);
xmlhttp.send(null);
}
function GetXmlHttpObject() {
var xmlhttp=null;
try {
xmlhttp=new XMLHttpRequest();
}
catch (e) {
try {
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlhttp;
}
</script>
The page I am trying to run the two timers off is only loading one of the timers, I have tried multiple things to try and fix the issue, and can't seem to figure out what it is that is wrong with it..
I even tried making two different timer scripts and that didn't work..
Here is the complete code of the page I want to run the two timers on..
<?php
/*------------includes--------------*/
include('./includes/connections.php');
include('./includes/brain_file.php');
include('./includes/style_top.php');
/*------------includes--------------*/
if ($pl['my_tuts_on'] == 'yes') {
echo "<tr bgcolor=#E6E6E6><td>
Here you can view all the inmates currently in jail. You may attempt to bust/bail them, Bailing them costs a fee, Busting them uses 10 energy and is not a garantee you will bust them, Just be carefull not to get caught and end up in jail yourself.
</td></td></tr></table></center><hr/ width=95%>";
}
echo "<center><main>Jail</main><hr width='95%'/>";
if ($pl['my_hosp'] > gmtime()) {
echo "Sorry this page is not viewable while in hospital!<hr width='85%'/>";
include('./includes/style_bottom.php');
exit();
}
$_GET['page'] = abs(intval($_GET['page']));
$min = ($_GET['page'] > '1') ? (($_GET['page'] - 1) * 25) : $min = 0;
$q_ry = array();
$q_ry = "SELECT `playerid` FROM `members`
WHERE `my_jail` > '" . mysql_real_escape_string(gmtime()) . "'";
$tot = array();
$tot = mysql_query($q_ry);
if ($joh['my_jail'] > gmtime()) {
$settime[] = $pl['playerid'] . ":" . $pl['my_jail'];
echo "<br><font size=2><b>", stripslashes($pl['jail_reason']), "</b>
<br>You will be in jail for another <span id = 'time" . $pl['playerid'] . "'><b>" . gettimeleft($pl['my_jail']) . "</b></span> yet!</font><br><br><hr width='85%'>";
}
?>
<script type = 'text/javascript'>
window.onload=function() {
setInterval("<?php
$array = count($settime);
for ($i = 0; $i < $array; $i++) {
$thitime = explode(":", $settime[$i]);
echo "timeleft(" . $thitime[1] . ", " . $thitime[0] . "); ";
}
?>", 1000);
}
function timeleft(string, id)
{
var xmlhttp=GetXmlHttpObject();
if(xmlhttp==null) { alert("Sorry, Your browser doesnt support HTTP Requests");
return;
}
var elem = "time" + id;
var load = "time_left.php?string=" + string;
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState==4) {
document.getElementById(elem).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", load, true);
xmlhttp.send(null);
}
function GetXmlHttpObject() {
var xmlhttp=null;
try {
xmlhttp=new XMLHttpRequest();
}
catch (e) {
try {
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlhttp;
}
</script>
<?php
if ($pl['my_jail'] > gmtime()) {
echo "<b>><a href='bust.php'>Try and escape for " . abs(intval($pl['my_maxnerve'] / 2)) . " nerve</a></b>
<hr width='85%'>";
}
echo "<b></b> ";
if (mysql_num_rows($tot) <= '25') {
echo "";
} else {
if ($_GET['page'] > '1') {
echo "<a href='jail.php?page=" . ($_GET['page'] - 1) . "'><<</a> ";
}
for ($i = 0; $i < (mysql_num_rows($tot) / 25); $i++) {
echo "<a href='jail.php?page=" . ($i + 1) . "'>";
if (($i + 1) == $_GET['page']) {
echo "<b>" . ($i + 1) . "</b>";
} else {
echo "<font color = '#999999'>" . ($i + 1) . "</font>";
}
echo "</a> ";
}
if ($_GET['page'] < $i) {
echo " <a href='jail.php?page=" . ($_GET['page'] + 1) . "'>>></a>";
exit();
}
}
echo "<table class='sidebarLink' border='0' width=95% class='rounded'><tr bgcolor=#151515>
<td height='20'><font color = '#FFFFFF'><b>ID#</b></font></td>
<td height='20'><font color = '#FFFFFF'><b>Player</b></font></td>
<td width=25%><font color = '#FFFFFF'><b>Time</b></font></td>
<td height='20'><font color = '#FFFFFF'><b>Level</b></font></td>
<td height='20'><font color = '#FFFFFF'><b>Reason</b></font></td>
<td height='20'><font color = '#FFFFFF'><b>Release</b></font></td></tr>";
$num = 0;
$q_ry = array();
$q_ry = "SELECT `playerid`,`playername`,`my_level`,`jail_offer`,`my_jail`,`jail_reason`
FROM `members`
WHERE `my_jail` > '" . mysql_real_escape_string(gmtime()) . "'
ORDER BY `my_jail` DESC
LIMIT $min,25";
$hopl = array();
$hopl = mysql_query($q_ry);
if (mysql_num_rows($hopl)) {
$hp = array();
while ($hp = mysql_fetch_array($hopl)) {
$num++;
if ($num % 2) {
$color = "#E6E6E6";
} else {
$color = "#E6E6E6";
}
$q_ry = array();
$q_ry = "SELECT `my_bustreward`
FROM `members_extra`
WHERE `playerid` = '" . $hp['playerid'] . "'";
$du = array();
$du = mysql_fetch_array(mysql_query($q_ry));
$settime[] = $hp['playerid'] . ":" . $hp['my_jail'];
echo "<tr bgcolor=#E6E6E6>
<td><a href = 'messages.php?action=send&XID=" . $hp['playerid'] . "'>" . $hp['playerid'] . "</a></td>
<td><a href = 'profile.php?XID=" . $hp['playerid'] . "'>" . htmlentities($hp['playername']) . "</a></td>
<td><span id = 'time" . $hp['playerid'] . "'><b>" . gettimeleft($hp['my_jail']) . "</b></span></td>
<td>" . $hp['my_level'] . "</td>
<td>" . stripslashes($hp['jail_reason']) . "</td>
<td>[<a href='release.php?action=bail&XID=" . $hp['playerid'] . "'>Bail</a>]
[<a href='release.php?action=bust&XID=" . $hp['playerid'] . "'>Bust</a>]</td></tr>";
}
} else {
echo "<tr>
<td colspan = '7' align = 'center'>
You walk into the jail to tease some inmates, but there are no inmates to tease!
</td></tr>";
}
echo "</table>
<hr width = '95%'>";
if ($pl['my_jail'] > gmtime() || $pl['am_i_staff'] > 4) {
if ($pl['am_i_staff'] > 4) {
echo '<table width="95%" align="center" border="0" bgcolor="#E6E6E6">
<b>Clear the current shoutbox.</b>
<form method="post" action="#"><tr>
<td><input type="hidden" name="clear"></td>
</tr><tr>
<td colspan="2" valign="middle" align="center"><input class="hospchat" type="submit" value="Clear ALL Shouts"></td>
<td></td>
</tr></form></table><br />';
}
if (isset($_POST['clear'])) {
if ($pl['am_i_staff'] < 5) {
print "Sorry, staff only. <a href=jail.php>> back</a>.";
exit();
} else {
mysql_query("TRUNCATE table `jailshoutsbox`");
print "All of the jail shouts have been <b>cleared</b> <a href=jail.php>> back</a>.";
}
}
if (isset($_POST['shout'])) {
if ($pl['lastShoutj'] == date("i") && $pl['am_i_staff'] < 5 && $pl['my_dondays'] < 1) {
echo "<div style='background: #DFDFDF;' width='85%'>Sorry, non donators can only post once per minute. <br /> <a href=jail.php> > back</a></div><br />";
exit();
}
if ($pl['my_jail'] <= 0 && $pl['am_i_staff'] < 5) {
echo "You are not in the jail. <a href=jail.php>> Back</a>";
exit();
}
echo "<div style='background: #E6E6E6;' width='85%'>You've shouted<br /><a href=jail.php>Refresh</a></div><br />";
$_POST['shout'] = htmlspecialchars(($_POST['shout']));
$not = array(
"'",
"/",
"<",
">",
";"
);
$_POST['shout'] = str_replace($not, "", $_POST['shout']);
mysql_query("INSERT INTO `jailshoutsbox` VALUES ('NULL', {$_SESSION['playerid']}, '{$_POST['shout']}', " . date("d") . ")");
}
echo ' <hr width=95% /> Post a message on the shoutbox.
<table width="95%" align="center" border="0" bgcolor="#E6E6E6">
<form method="post" action="#"><tr>
<td>Your Message: (max 155) </td>
<td><input class="hospchat" type="text" name="shout" maxlength="155"></td>
</tr><tr>
<td colspan="2" valign="middle" align="center"><input class="hospchat" type="submit" value="Shout"></td>
<td></td>
</tr></form></table><br /><table width="95%" style=text-align:left class="table2" border="0" cellspacing="2">
<tr bgcolor="#151515" style="font-style:bold; text-align:center;"><td style="font-style:bold;" width=55%><b><font color="#FFFFFF">Posted By:</b></td><td style="font-style:bold;" width="44%"><b><font color="#FFFFFF">Messsage:</b></td></tr>
';
$get = mysql_query("SELECT * FROM `jailshoutsbox` ORDER BY `ID` DESC LIMIT 10");
while ($r = mysql_fetch_array($get)) {
$num9 = $num9 + 1;
$odd9 = "#CCCCCC";
$even9 = "#e3e3e3";
if ($num9 % 2) {
$color9 = "$even9";
} else {
$color9 = "$odd9";
}
if ($r['User'] == 1) {
$r['Shout'] = "<font color='blue'>" . $r['Shout'] . "</font>";
}
$user = mysql_query("SELECT `playername` FROM `members` WHERE `playerid`={$r['User']}");
while ($user1 = mysql_fetch_array($user))
$player = ($r['User'] == 0) ? "SYSTEM" : "<a href='profile.php?XID={$r['User']}'>[{$r['User']}] {$user1['playername']}</a>";
echo "<tr height='50px' bgcolor=#E6E6E6><td>$player</td><td style='text-align:center;'>{$r['Shout']}</td></tr>";
}
echo "</table>";
}
include('./includes/style_bottom.php');
?>
And here is the gettimeleft function.
function gettimeleft($tl) {
if($tl <= time()) { $release = "0 Seconds"; }
else
{
$mins = floor(($tl - time()) / 60);
$hours = floor($mins / 60);
$mins -= $hours * 60;
$days = floor($hours / 24);
$hours -= $days * 24;
$months = floor($days / 31);
$days -= $months * 31;
$weeks = floor($days / 7);
$days -= $weeks * 7;
$timeleft = ($tl - time());
$secs = round($timeleft%60);
if ($months > 0)//MONTHS
{
$release .= " $months Month" . ($months > 1 ? "s" : "");
}
if ($weeks > 0)//WEEKS
{
if ($months > 0)
{
$release .= ",";
}
$release .= " $weeks Week" . ($weeks > 1 ? "s" : "");
}
if ($days > 0)//DAYS
{
if ($months > 0 ||$weeks > 0)
{
$release .= ",";
}
$release .= " $days Day" . ($days > 1 ? "s" : "");
}
if ($hours > 0)//HOURS
{
if ($months > 0 ||$weeks > 0 || $days > 0)
{
$release .= ",";
}
$release .= " $hours Hour" . ($hours > 1 ? "s" : "");
}
if ($mins > 0)//MINUTES
{
if ($months > 0 ||$weeks > 0 || $days > 0 || $hours > 0)
{
$release .= ",";
}
$release .= " $mins Minute" . ($mins > 1 ? "s" : "");
}
if($secs > 0)//SECONDS
{
if($release != "")
{
$release .= " and";
}
$release .= " $secs Second" . ($secs > 1 ? "s" : "");
}
}
return $release;
}
Is anyone please able to help me out with this?
I have this class for a megamenu used in a category menu for an ecommerce web application.
class categories {
var $categorie;
var $tabs;
var $subcategorie;
var $website;
var $coloane = 3;
var $randuri = 10;
function tabs(){
global $pdoconnect;
$stmt = $pdoconnect->query("SELECT * FROM taburi WHERE vizibil = '1' ORDER BY ordine ASC");
$tabs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$tabs_c = $stmt->rowCount();
$return = "";
if($tabs_c > 0){
$i = 1;
$return .= "\n<ul class=\"tabs\">\n";
foreach($tabs as $t){
$return .= "\t<li class=\"level0\">\n";
$return .= "\t\t<div class=\"tab-title\">\n";
$return .= "\t\t\t<span class=\"tab-image\">\n";
$return .= "\t\t\t\t".'<img src="'.$this->website.'/media/taburi/'.$t['logo'].'" />'."\n";
$return .= "\t\t\t</span>\n";
$return .= $t['nume'];
$return .= "\t\t</div>\n";
$return .= "\t".'<div class="level1 hmm-megamenu-box">'."\n";
$return .= $this->categorie($t['id']);
$return .= "\t</div>\n";
$return .= "\t</li>\n";
}
$return .= "</ul>";
}
return $return;
}
function categorie($tab){
global $pdoconnect;
$return = "";
$stmt = $pdoconnect->prepare("SELECT * FROM categorii WHERE tab =:tab AND vizibil='1'");
$stmt->bindValue(':tab', $tab, PDO::PARAM_INT);
$stmt->execute();
$categorie = $stmt->fetchAll(PDO::FETCH_ASSOC);
$categorie_c = $stmt->rowCount();
if($categorie_c > 0){
$i = 0;
$return .= "<div class=\"hmm-megamenu-block\">\n";
foreach ($categorie as $cat) {
$return .= "\t<div class=\"hmm-megamenu-column\">\n";
// if($i % 2 == 0 && !empty($i) && $this->countSubcategorii($cat['categorie']) <= $this->randuri){
// $return .= "</div><div class=\"hmm-megamenu-column\">\n";
// }
$return .= "\t\t\t<a class=\"head-list\">".$cat['categorie']."<i class=\"fa fa-chevron-right\" style=\"font-size: 8px; margin-left: 5px;\"></i></a>\n";
$return .= $this->subcategorie($cat['categorie']);
$return .= "\t\t</div>\n";
$i++;
}
$return .= "</div>";
}
return $return;
}
function subcategorie($cat){
global $pdoconnect;
$return = "";
$stmt = $pdoconnect->prepare("SELECT * FROM categorii WHERE categorie=:categorie AND subcategorie IS NOT NULL");
$stmt->bindValue(':categorie', $cat, PDO::PARAM_STR);
$stmt->execute();
$subcategorie = $stmt->fetchAll(PDO::FETCH_ASSOC);
$subcategorie_c = $stmt->rowCount();
if($subcategorie_c > 0){
foreach ($subcategorie as $scat) {
$return .= "\t".''.$scat['subcategorie'].''."\n";
}
}
return $return;
}
}
For the moment the menu items looks like this
but the desired result should be
How can i get this result just with php?
I suspect the problem is two fold, in both style and HTML markup.
From a style perspective, your current layout is more or less a grid. You need something a lot more fluid within your CSS.
To allow this, you might need to pre-calculate columns so that you know you're evenly distributing X groups with a total of Y items into 3 columns. This lets you deal with cases where one group may have more items than can fit in the height of the menu (and need to overflow).
Solved
function categorie($tab){
global $pdoconnect;
$return = "";
$stmt = $pdoconnect->prepare("SELECT * FROM categorii WHERE tab =:tab AND vizibil='1'");
$stmt->bindValue(':tab', $tab, PDO::PARAM_INT);
$stmt->execute();
$categorie = $stmt->fetchAll(PDO::FETCH_ASSOC);
$categorie_c = $stmt->rowCount();
$return .= "<div class=\"hmm-megamenu-block\">\n";
if($categorie_c > 0){
$i = 1;
$return .= "\t<div class=\"hmm-megamenu-column\">\n";
foreach ($categorie as $cat) {
if($i % 3 == 0 && !empty($i) && $this->countSubcategorii($cat['categorie']) <= $this->randuri){
$return .= "</div><div class=\"hmm-megamenu-column\">\n";
}else if($i % 3 == 0 && !empty($i) && $this->countCategorii($tab) >= $this->coloane){
$return .= "</div><div class=\"hmm-megamenu-column\">\n";
}else if($i % 2== 0 && $this->countCategorii($tab) == 2){
$return .= "</div><div class=\"hmm-megamenu-column\">\n";
}
$return .= "\t\t\t<a class=\"head-list\">".$cat['categorie']."<i class=\"fa fa-chevron-right\" style=\"font-size: 8px; margin-left: 5px;\"></i></a>\n";
$return .= $this->subcategorie($cat['categorie']);
$i++;
}
$return .= "</div>";
}
$return .= "</div>";
return $return;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am using the free code of tablefilter.free.fr and have adding this to my code but it does not get executed.
I have added the html and javascript into https://jsfiddle.net/koalyptus/eCqG3/ and it works fine but when i use my page -> http://mr-tipster.com/pages/newcard.php?venue=Southwell it does not render for some reason although the same html is output.
below is the full code i use on the page to create the tables and add the javascript.
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="../table/tablefilter.js"></script>
<?php
//show today's meeting name
if ($numrows > 0) {
echo '' . $entry . '';
} else {
echo '' . $entry . '';
}
$met1 = array_values($meeting);
if (array_shift($met1) == $entry && $venue =="" || $venue == $entry)
{
echo ''.$entry.'';
if ($venue =="")
{
$venue = array_shift($met1);
}
}
else
{
}
// pull the times for that meeting
$grabtracktimes = mysqli_query($db, 'SELECT Racetime,Going,distance, COUNT(*) c FROM tom_cards Where Track = "' . $venue . '" GROUP BY Racetime HAVING c > 1;');
$meetingtime = array();
echo "<br />";
while ($grabtodaystracktimes = mysqli_fetch_array($grabtracktimes)) {
$meetingtime[] = $grabtodaystracktimes['Racetime'];
}
$meetingtime1 = array_unique($meetingtime);
foreach ($meetingtime1 as $entrytime) {
if ($time == "") {
$time = array_shift(array_values($meetingtime1));
}
if (array_shift($meetingtime1) == $entrytime and $time == "" or $time == $entrytime) {
echo '' . $entrytime . '';
if ($time == "") {
$time = array_shift($meetingtime1);
}
} else {
echo '' . $entrytime . '';
}
}
echo "<br /><b>" . $venue . "(" . $time . ")</b>";
$sqltodaystrack = "";
$sqltodaystrack2 = mysqli_query($db, $sqltodaystrack );
$todaystrackleftorright = "";
$todaystrackspeed = "";
$todaystracksurface = "";
while ( $sqltodaystrack3 = mysqli_fetch_array($sqltodaystrack2)) {
$todaystrackleftorright = $sqltodaystrack3['Left_or_Right'];
$todaystrackspeed = $sqltodaystrack3['speed'];
$todaystracksurface = $sqltodaystrack3['surface'];
}
$sql = 'SELECT Race_Name,distance,going,surface FROM tom_cards Where Track ="' . $venue . '" and Racetime = "' . $time . '" group by Racetime ';
$horses2 = mysqli_query($db, $sql);
$first = true;
while ($todayhorse = mysqli_fetch_array($horses2)) {
if ($first == true) {
// do something
$first = false;
$todaysgoing = $todayhorse['going'];
$todaysdistance = miletofurlong($todayhorse['distance']);
echo "<br /><br /><b>" . $todayhorse['Race_Name'] . "</b>";
//add notes about the race course here
$sqlfortrack = 'SELECT notes,Handicaps, Non_Handicaps FROM RaceCourse Where Course ="' . $venue . '"';
$fortrack = mysqli_query($db, $sqlfortrack );
while ($fortrack2 = mysqli_fetch_array($fortrack)) {
echo "<br /><span style='font-size:11px'><b>Course Notes:</b> ".$fortrack2['notes']."</span><BR />";
//check if handicap or not and check for any course details
if (strpos($todayhorse['Race_Name'], 'Handicap') !== FALSE)
{
echo "<span style='font-size:11px'>".$fortrack2['Handicaps']."<span/>";
}
else
{
echo "<span style='font-size:11px'>".$fortrack2['Non_Handicaps']."</span>";
}
}
echo " <br /><br />Distance: <b>" . miletofurlong($todayhorse['distance']) . "f </b>(" . $todayhorse['distance'] . ") Going: <b>" . $todayhorse['going'] . "</b>";
$surface = trim($db->real_escape_string($todayhorse['surface']));
}
}
echo "</div>";
echo "<table id='table1' style='border:0px;margin-top:50px;text-align: center ;'>";
echo "<tr style='font-weight: bold;'><td>Horse</td><td>Form</td><td>History</td><td>OR/Class</td><td>MT Rating</td><td>Naps</td></tr>";
$sql = 'SELECT horse,rp,ts,Naps,`OR`,Class,Jockeys_Claim,Trainer,Track FROM tom_cards Where Track ="' . $venue . '" and Racetime = "' . $time . '"';
$horses2 = mysqli_query($db, $sql);
$loop = 0;
while ($todayhorse = mysqli_fetch_array($horses2)) {
$placed = "";
$data = "";
$horse = trim($todayhorse['horse']);
$jockeys = $todayhorse['Jockeys_Claim'];
$trainer = $todayhorse['Trainer'];
$class = $todayhorse['Class'];
$or = $todayhorse['OR'];
$rp = $todayhorse['rp'];
$ts = $todayhorse['ts'];
$naps = $todayhorse['Naps'];
if ($surface == "Turf") {
$win = 0;
$runs = 0;
$place = 0;
$horsesplaced = ;
$check = "no";
while ($pasthorse = mysqli_fetch_array($horsesplaced)) {
$dbDate = $pasthorse['Date'];
$placeddata = intval($pasthorse['Place']);
//add 1 to runs everyloop to show how many runs they have had
$runs = $runs + 1;
//if the horse has won a race then mark it red and add 1 point to the win tally
if ($placeddata == 1) {
$placed .= "<b><span style='color:#8DB600'>" . $pasthorse['Place'] . "</span></b>";
$win = $win + 1;
} else {
//if the horse was placed higher then 9th just add 0
if (intval($pasthorse['Place']) > 9) {
$pasthorse['Place'] = 0;
}
//echo all the places
if ($pasthorse['Place'] == "PU") {
$pasthorse['Place'] = str_replace($pasthorse['Place'], 'PU', '<b>P</b>');
}
if ($pasthorse['Place'] == "F") {
$pasthorse['Place'] = str_replace($pasthorse['Place'], 'F', '<b>F</b>');
}
if ($pasthorse['Place'] == "2" or $pasthorse['Place'] == "3") {
$pasthorse['Place'] = str_replace($pasthorse['Place'], $pasthorse['Place'], "<span style='color:#8DB600'>" . $pasthorse['Place'] . "</span>");
}
$placed .= $pasthorse['Place'];
// if runners are greater then 4 and less the 8 only 2 to place
if ($pasthorse['Runners'] < 4 and $pasthorse['Runners'] > 8) {
if ($pasthorse['Place'] == 2) {
$place = $place + 1;
}
}
if ($pasthorse['Runners'] < 7 and $pasthorse['Runners'] > 16) {
if ($pasthorse['Place'] == 2 or $pasthorse['Place'] == 3) {
$place = $place + 1;
}
}
if ($pasthorse['Runners'] < 15) {
if ($pasthorse['Place'] == 2 or $pasthorse['Place'] == 3 or $pasthorse['Place'] == 4) {
$place = $place + 1;
}
}
}
}
} elseif ($surface == "AW") {
$win = 0;
$runs = 0;
$place = 0;
$horsesplaced = ;
while ($pasthorse = mysqli_fetch_array($horsesplaced)) {
$placeddata = intval($pasthorse['Place']);
//add 1 to runs everyloop to show how many runs they have had
$runs = $runs + 1;
//if the horse has won a race then mark it red and add 1 point to the win tally
if ($placeddata == 1) {
$placed .= "<b><span style='color:red'>" . $pasthorse['Place'] . "</span></b>";
$win = $win + 1;
} else {
//if the horse was placed higher then 9th just add 0
if (intval($pasthorse['Place']) > 9) {
$pasthorse['Place'] = 0;
}
//echo all the places
$placed .= $pasthorse['Place'];
// if runners are greater then 4 and less the 8 only 2 to place
if ($pasthorse['Runners'] < 4 and $pasthorse['Runners'] > 8) {
if ($pasthorse['Place'] == 2) {
$place = $place + 1;
}
}
if ($pasthorse['Runners'] < 7 and $pasthorse['Runners'] > 16) {
if ($pasthorse['Place'] == 2 or $pasthorse['Place'] == 3) {
$place = $place + 1;
}
}
if ($pasthorse['Runners'] < 15) {
if ($pasthorse['Place'] == 2 or $pasthorse['Place'] == 3 or $pasthorse['Place'] == 4) {
$place = $place + 1;
}
}
}
}
}
$winner = "";
$placed1 = "";
if ($runs != 0) {
$winner = "(" . round(($win / $runs) * 100) . "%) ";
$placed1 = "(" . round((($place + $win) / $runs) * 100) . "%) ";
}
$thetrack = horseontrack($horse, $venue, $db);
list($corseruns, $corsewins, $corseplace) = explode("/", $thetrack);
$sqlhorses = "SELECT distance,Place,Runners FROM `horsesrp` WHERE `Horse` = '" . $horse . "' order by distance + 0,
substring_index(distance, 'm', -1) + 0";
$horseplaced = mysqli_query($db, $sqlhorses);
$data = "";
$dataleftorright = "";
$dataspeed = "";
$datasurface = "";
$storage = array();
$storetrackdirection = array();
$storetrackdirectionsurface= array();
$storetrackspeed= array();
while ($pasthorse = mysqli_fetch_array($horseplaced)) {
// check to see if its distance is that of today
$placetotals = 0;
$wintotals = 0;
$test = "";
$placeddata = intval($pasthorse['Place']);
if ($placeddata == 1) {
} else {
if ($pasthorse['Runners'] > 4 and $pasthorse['Runners'] < 8) {
$test = "--between 5 and 7--" . $pasthorse['Place'];
if ($pasthorse['Place'] == 2) {
$placetotals = 1;
}
}
if ($pasthorse['Runners'] > 7 and $pasthorse['Runners'] < 16) {
$test = "--Between 8 and 15--" . $pasthorse['Place'];
if ($pasthorse['Place'] == 2 or $pasthorse['Place'] == 3) {
$placetotals = 1;
}
}
if ($pasthorse['Runners'] > 15) {
$test = "over 15" . $pasthorse['Place'];
if ($pasthorse['Place'] == 2 or $pasthorse['Place'] == 3 or $pasthorse['Place'] == 4) {
$placetotals = 1;
}
}
}
// if the distance is the same
// Take this outside of the if statements
$mtfl = miletofurlong($pasthorse['distance']);
if ($mtfl == $todaysdistance) {
$Horsedist = "<b><span style='color:#ff4500 '>" . $mtfl . "f</span></b>";
} elseif (($mtfl >= $todaysdistance - 1) && ($mtfl <= $todaysdistance + 1)) {
// You don't need to check for equality here - if you get here it is because
// the values are not equal
$Horsedist = "<b><span style='color:#8DB600'>" . $mtfl . "f</span></b>";
} else {
$Horsedist = $mtfl . "f";
}
if (!isset($storage[$Horsedist])) {
$storage[$Horsedist] = array(
"win" => 0,
"placed" => 0,
"raced" => 0
);
}
// Then increment if required
// $data .= "<span style='font-size:10.5px'>".$Horsedist. " -Won:".$wintotals. " Placed:".$placetotals." </span><br />";
}
$sqlhorsesgoing = "SELECT going,Place,Runners FROM `horsesrp` WHERE `Horse` = '" . $horse . "' order by going";
$horseplacedgoing = mysqli_query($db, $sqlhorsesgoing);
$datagoing = "";
$storagegoing = array();
while ($pasthorsegoing = mysqli_fetch_array($horseplacedgoing)) {
// check to see if its going is that of today
$placeddatagoing = intval($pasthorsegoing['Place']);
if ($placeddatagoing == 1) {
} else {
if ($pasthorsegoing['Runners'] > 4 and $pasthorsegoing['Runners'] < 8) {
if ($pasthorsegoing['Place'] == 2) {
$placetotalsgoing = 1;
}
}
if ($pasthorsegoing['Runners'] > 7 and $pasthorsegoing['Runners'] < 16) {
if ($pasthorsegoing['Place'] == 2 or $pasthorsegoing['Place'] == 3) {
$placetotalsgoing = 1;
}
}
if ($pasthorsegoing['Runners'] > 15) {
if ($pasthorsegoing['Place'] == 2 or $pasthorsegoing['Place'] == 3 or $pasthorsegoing['Place'] == 4) {
$placetotalsgoing = 1;
}
}
}
// if the going is the same
// Take this outside of the if statements
$mtfl1 = $pasthorsegoing['going'];
if ($mtfl1 == $todaysgoing) {
$Horsegoing = "<b><span style='color:#ff4500 '>" . $mtfl1 . "</span></b>";
} else {
$Horsegoing = $mtfl1;
}
if (!isset($storagegoing[$Horsegoing])) {
$storagegoing[$Horsegoing] = array(
"win" => 0,
"placed" => 0,
"raced" => 0
);
}
// Then increment if required
}
$data = "<table class='tg' align='center' style='font-size:10.5px;'><tr><th style='padding-right:5px;'></th><th style='padding-right:5px;'> Runs </th><th style='padding-right:5px;'> Wins </th><th style='padding-right:5px;'> Placed </th></tr>";
foreach ($storage as $pony => $tab) {
// $data .= "<span style='font-size:10.5px'>".$Horsedist. " -Won:".$wintotals. " Placed:".$placetotals." </span><br />";
if ($tab["win"] !== 0) {
$distancewinners = "<b><span style='color:#ff4500 '>" . $tab["win"] . "</span></b>";
} else {
$distancewinners = $tab["win"];
}
if ($tab["placed"] !== 0) {
$distanceplace = "<b><span style='color:#ff4500 '>" . $tab["placed"] . "</span></b>";
} else {
$distanceplace = $tab["placed"];
}
}
$data .= "</table>";
foreach ($storagegoing as $ponygoing => $tabgoing) {
if ($tabgoing["win"] !== 0) {
$distancewinners = "<b><span style='color:#ff4500 '>" . $tabgoing["win"] . "</span></b>";
} else {
$distancewinners = $tabgoing["win"];
}
if ($tabgoing["placed"] !== 0) {
$distanceplace = "<b><span style='color:#ff4500 '>" . $tabgoing["placed"] . "</span></b>";
} else {
$distanceplace = $tabgoing["placed"];
}
//work out which courses the horse has ran at
$horseplacedtracks = "SELECT track,Place,Runners FROM `horsesrp` WHERE `Horse` = '" . $horse . "'";
$horseplacedtracks2 = mysqli_query($db, $horseplacedtracks );
$track ="";
$leftorright = "";
$surface = "";
$speed = "";
while ($pasthorsetracks = mysqli_fetch_array($horseplacedtracks2 ))
{
//remove (aw) and get the track name
$track = trim(str_replace("(AW)", "", $pasthorsetracks['track']));
//is the track left or right??
// check to see if its going is that of today
$placetotalstrack = 0;
$wintotalstrack = 0;
$placeddatatrack = intval($pasthorsetracks['Place']);
if ($placeddatatrack == 1) {
$placetotalstrack = 1;
$wintotalstrack = 1;
} else {
if ($pasthorsetracks['Runners'] > 4 and $pasthorsetracks['Runners'] < 8) {
if ($pasthorsetracks['Place'] == 2) {
$placetotalstrack = 1;
}
}
if ($pasthorsetracks['Runners'] > 7 and $pasthorsetracks['Runners'] < 16) {
if ($pasthorsetracks['Place'] == 2 or $pasthorsetracks['Place'] == 3) {
$placetotalstrack = 1;
}
}
if ($pasthorsetracks['Runners'] > 15) {
if ($pasthorsetracks['Place'] == 2 or $pasthorsetracks['Place'] == 3 or $pasthorsetracks['Place'] == 4) {
$placetotalstrack = 1;
}
}
}
// check the track against the database and asign left or right
$grabtrackdetails = "SELECT Left_or_Right FROM `RaceCourse` WHERE `Course` = '" . $track . "'";
$grabtrackdetails2 = mysqli_query($db, $grabtrackdetails );
while ($pastgrabtrackdetails = mysqli_fetch_array($grabtrackdetails2 ))
{
$leftorright = $pastgrabtrackdetails['Left_or_Right'];
/////////////////////////////////////////////////////////////////////////////////////
if (!isset($storetrackdirection[$leftorright])) {
$storetrackdirection[$leftorright] = array(
"win" => 0,
"placed" => 0,
"raced" => 0
);
}
// Then increment if required
$storetrackdirection[$leftorright]["win"] += $wintotalstrack;
$storetrackdirection[$leftorright]["placed"] += $placetotalstrack;
$storetrackdirection[$leftorright]["raced"] += 1;
}
// check the track against the database and asign left or right
$grabtrackdetailssurface = "SELECT surface FROM `RaceCourse` WHERE `Course` = '" . $track . "'";
$grabtrackdetailssurface2 = mysqli_query($db, $grabtrackdetailssurface );
while ($pastgrabtrackdetailssurface = mysqli_fetch_array($grabtrackdetailssurface2 ))
{
$surface = $pastgrabtrackdetailssurface['surface'];
if ($surface == "")
{
$surface = "Mix";
}
/////////////////////////////////////////////////////////////////////////////////////
if (!isset($storetrackdirectionsurface[$surface])) {
$storetrackdirectionsurface[$surface] = array(
"win" => 0,
"placed" => 0,
"raced" => 0
);
}
// Then increment if required
$storetrackdirectionsurface[$surface]["win"] += $wintotalstrack;
$storetrackdirectionsurface[$surface]["placed"] += $placetotalstrack;
$storetrackdirectionsurface[$surface]["raced"] += 1;
}
$horsehistory = "SELECT Date,track,Class,Distance,going,Place,Jockeys_claim,`OR`,Runners FROM `horsesrp` WHERE `Horse` = '" . $horse . "' order by Date DESC";
$horsehistory2 = mysqli_query($db, $horsehistory );
$horseshistoryget = "<br />";
?>
<script type="text/javascript">
var tf<?php echo $loop; ?> = setFilterGrid("loop<?php echo $loop; ?>");
</script>
<?
$horseshistoryget .= "<table id='loop".$loop."' class='mytable' align='center' style='font-size:10.5px;'><tr><th style='padding-right:5px;'></th><th style='padding-right:5px;'> Course </th><th style='padding-right:5px;'> Class</th><th style='padding-right:5px;'> Distance </th><th style='padding-right:5px;'> Going</th><th style='padding-right:5px;'> Outcome </th><th style='padding-right:5px;'> Jockey </th><th style='padding-right:5px;'> OR </th></tr>";
while ($gethorsehistory = mysqli_fetch_array($horsehistory2 ))
{
//$horseshistoryget .= "<tr style='height:18px; border-top:1pt solid black; border-bottom:0pt solid black;'><td style='border-top:1pt solid black; border-bottom:0pt solid black;'>" .$gethorsehistory["Date"] . "</td><td style='border-top:1pt solid black; border-bottom:0pt solid black;'>" . $gethorsehistory["Track"] . "</td><td style='border-top:1pt solid black; border-bottom:0pt solid black;'>" . $gethorsehistory["Class"] . "</td><td style='border-top:1pt solid black; border-bottom:0pt solid black;'>" . $gethorsehistory["Distance"] . "</td><td style='border-top:1pt solid black; border-bottom:0pt solid black;'>" . $gethorsehistory["Place"] . "</td><td style='border-top:1pt solid black; border-bottom:0pt solid black;'>" . $gethorsehistory["Jockeys_claim"] . "</td><td style='border-top:1pt solid black; border-bottom:0pt solid black;'>" . $gethorsehistory["`OR`"] . "</td></tr>";
$timestamp = strtotime($gethorsehistory["Date"]);
$newDate = date('d.m.y', $timestamp);
// check if the value is the same as today and bold it
$horseshistoryget .= "<tr><td>". $newDate. "</td>";
//check what todays course speed and surface is like
$todayscourseprofile = "SELECT speed,surface from RaceCourse where course = '".$venue."' ";
$todayscourseprofile2 = mysqli_query($db, $todayscourseprofile );
$todayscoursespeed = "" ;
$todayscoursesurface = "";
while ($gettodayscourseprofile = mysqli_fetch_array($todayscourseprofile2 ))
{
$todayscoursespeed = $gettodayscourseprofile["speed"] ;
$todayscoursesurface = $gettodayscourseprofile ["surface"];
}
//check if venue has the same profile as this one
$trackprofie = trim(str_replace("(AW)", "", $gethorsehistory["track"]));
$allcourseprofile = "SELECT speed, surface from RaceCourse where course = '".$trackprofie."' ";
$allcourseprofile2 = mysqli_query($db, $allcourseprofile );
while ($getallcourseprofile = mysqli_fetch_array($allcourseprofile2 ))
{
$allcoursespeed = "" ;
$allcoursesurface = "";
$allcoursespeed = $getallcourseprofile["speed"] ;
$allcoursesurface = $getallcourseprofile ["surface"];
}
//if they match colour them
if($todayscoursespeed == $allcoursespeed and $allcoursesurface == $todayscoursesurface )
{
if ($todayscoursespeed <> "" and $todayscoursesurface <> "")
{
$showtrack = "<span style='color:#336600 '>".$gethorsehistory["track"]."</span>";
}
else
{
$showtrack = $gethorsehistory["track"];
}
}
elseif ($todayscoursespeed == $allcoursespeed)
{
if ($todayscoursespeed <> "")
{
$showtrack = "<span style='color:#996600 '>".$gethorsehistory["track"]."</span>";
}
else
{
$showtrack = $gethorsehistory["track"];
}
}
elseif($todayscoursesurface == $allcoursesurface)
{
if ($todayscoursesurface <> "")
{
$showtrack = "<span style='color:#CC3300 '>".$gethorsehistory["track"]."</span>";
}
else
{
$showtrack = $gethorsehistory["track"];
}
}
else
{
$showtrack = $gethorsehistory["track"];
}
if ($gethorsehistory["track"] == $venue)
{
$horseshistoryget .= "<td><b>" . $showtrack. "</b></td>";
}
else{
$horseshistoryget .= "<td>" . $showtrack."</td>";
}
if ($gethorsehistory["Class"] == "Class".$class)
{
$horseshistoryget .= "<td><b>" . $gethorsehistory["Class"] . "</b></td>";
}
else
{
$horseshistoryget .= "<td>" . $gethorsehistory["Class"] . "</td>";
}
if (miletofurlong($gethorsehistory["Distance"]) == $todaysdistance)
{
$horseshistoryget .= "<td><b>" . miletofurlong($gethorsehistory["Distance"]). "f" . "</b></td>";
}
else
{
$horseshistoryget .= "<td>" . miletofurlong($gethorsehistory["Distance"]). "f" . "</td>";
}
if ($gethorsehistory["going"] == $todaysgoing)
{
$horseshistoryget .= "<td><b>" . $gethorsehistory["going"] . "</b></td>";
}
else{
$horseshistoryget .= "<td>" .$gethorsehistory["going"] . "</td>";
}
if ($gethorsehistory["Place"] == 1){
$pastplace = "<b><span style='color:#ff4500 '>".$gethorsehistory["Place"]."</span></b>";
}
else{
$pastplace = $gethorsehistory["Place"];
}
$horseshistoryget .= "<td>" . $pastplace ."/". $gethorsehistory["Runners"]. "</td>";
if ($gethorsehistory["Jockeys_claim"] == $jockeys)
{
$horseshistoryget .= "<td><b>" .$gethorsehistory["Jockeys_claim"]. "</b></td>";
}
else{
$horseshistoryget .= "<td>" . $gethorsehistory["Jockeys_claim"] . "</td>";
}
$horseshistoryget .= "<td>" .$t1. $gethorsehistory["OR"] .$t2. "</td></tr>";
}
$horseshistoryget .= "</table><br />";
//does the jockey only have one ride today???
echo "<tr valign='top'><td >";
echo "<b><span style='font-size:12px'> " . $horse . "</span></b> <sup><span style='font-size:10px;color:gray'><abbr title='Days Since Last Race'>" . horselastrace($horse, $db) . "</abbr> </span><b><span style='font-size:10px;color:red'><abbr title='Beaten Favourite'>" . horsebeatenfav($horse, $db) . "</abbr></span></sup></b>
<br /><span style='font-size:10.5px'><abbr title='Jockey'>J: " . $jockeys . "</abbr><abbr title='Jockey Win rate last 4 months'> (" . round(howhotisjockey($jockeys, $db)) . "%)</abbr> " . " <abbr title='Jockey Win rate on horse'>(" . round(howhotisjockeyonhorse($jockeys, $db, $horse)) . "%)</abbr><abbr title='Jockey rides today'> " . jockeyridestoday($jockeys, $db) . "</abbr>
<br /><abbr title='Trainer'> T: " . $trainer . "</abbr> <abbr title='Trainer Win rate last 4 months'>(" . round(howhotistrainer($trainer, $db)) . "%)</abbr> <abbr title='Trainers horses out today'> " . trainersridestoday($trainer, $db) . "</abbr> </span></td>";
echo "<td ><span style='font-size:11px'><abbr title='P = Pulled Up , F = Fell'> " . $placed . "</abbr></span> <span style='font-size:10.5px'> <abbr title='Win Percent'> " . $winner . "</abbr> <abbr title='Place Percent'>" . $placed1 . "</abbr></span> </td>";
// echo "<td ><span style='font-size:11px'>".$dataleftorright.$dataspeed.$datasurface."</span></td>";
// echo "<td >" . $data . "<br /></td>";
// echo "<td >" . $datagoing . "<br /></td>";
echo "<td >".$horseshistoryget."</td>";
echo "<td ><span style='font-size:11px'><abbr title='class and highest winning OR'> " . classtop2($horse, $db, $or, $class) . "</abbr></span> </td>";
echo "<td ><span style='font-size:11px'><abbr title='Mr-Tipster speed rating'> " . round((($rp + $ts) / 2)) . "</abbr> </span></td>";
echo "<td ><span style='font-size:11px'>" . $naps . "</span></td>";
echo "</tr>";
$loop = $loop + 1;
}
?>
</table>
</div>
</body>
</html>
I've writen this code but it doesn't work. I'm pretty sure it's mostly correct, but I don't know what's wrong with it. The script returns as output "undefined"
------PHP ON SERVER----------------- (http://www.autofficinacicco.it/json.php)
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli($nomehost, $nomeuser, $password, "");
$result = $conn->query("SELECT codice, immagine, testo FROM Promozioni");
$outp = array();
while($rs = $result->fetch_array(MYSQLI_ASSOC))
{
$outp[]=$rs;
}
$conn->close();
echo json_encode($outp);
?>
-----JAVA SCRIPT----------------------------------------
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://www.autofficinacicco.it/json.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out+=arr["immagine"];
out+="</br>";
out+=arr["codice"];
out+="</br>";
out+=arr["testo"];
out+="</br>";
}
out += "</table>"
document.getElementById("id").innerHTML =out;
}
</script>
Your JSON is not proper document. Change json formating and use json_encode(); function
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC))
{
if ($outp != "[") {$outp .= ",";}
$outp .= '{"Codice":"' . $rs["codice"] . '",';
$outp .= '"Testo":"' . $rs["testo"] . '",';
$outp .= '"Immagine":"'. $rs["immagine"] . '"}';
}
$outp .="]";
$conn->close();
to
$outp = array();
while($rs = $result->fetch_array(MYSQLI_ASSOC))
{
$outp[] = $rs;
}
$conn->close();
echo json_encode($outp);
I have a website where users contribute with content. The content takes form of tables, where every td element is of equal height and width. The different pieces of content have different number of rows and columns. I want to stack these elements in an infinite-scroll webpage. ATM I'm doing this: I construct a table, in it a tr. I load element by element inside tds and count their number of columns. When a certain threshold has been reached, i break the tr and start a new tr. This makes the content elements border eachother sideways, leaving no room between each. However I also want to load the elements in such a way that there is minimal room between elements vertically. How can I do this?
Here is my code. I DO NOT expect to have it rewritten or have new code written for me. This is only to make it clearer to you what I am currently doing.
<?php
$row = 0;
$column = 0;
$maxColumns = 124;
echo "<table><tr>";
$listHandle = fopen('pieces/piecesList', 'r');
while (!feof($listHandle)) {
echo "<td>";
$filename = trim(fgets($listHandle));
$templateHandle = fopen("pieces/" . $filename, 'r');
$thisLine = fgets($templateHandle);
list($lowestX, $highestX, $lowestY, $highestY) = sscanf($thisLine, '%d %d %d %d');
//echo $lowestX . $highestX . $lowestY . $highestY;
$templateTable = "<table id=\"" . $filename . "\" title =\"" . $filename . "\">" . PHP_EOL;
$greenCells = array();
$fileLength = 0;
while (!feof($templateHandle)) {
$thisLine = fgets($templateHandle);
list($thisX, $thisY) = sscanf($thisLine, '%d %d');
$carrier = $thisX . " " . $thisY;
array_push($greenCells, $carrier);
$fileLength++;
}
for ($y = $lowestY; $y <= $highestY; $y++) {
// echo "inside for loop Y \n";
$templateTable = $templateTable . "<tr>" . PHP_EOL;
for ($x = $lowestX; $x <= $highestX; $x++) {
// echo $y . $x;
$templateTable = $templateTable . "<td";
$coordinateExists = FALSE;
for ($i = 0; $i < $fileLength; $i++) {
if ($greenCells[$i] == $x . " " . $y) {
$coordinateExists = TRUE;
break;
}
}
if ($coordinateExists) {
$templateTable = $templateTable . " class=\"green";
if ($x == 0 && $y == 0) {
$templateTable = $templateTable . " markerdot";
}
$templateTable = $templateTable . "\"";
} else if ($x == 0 && $y == 0) {
$templateTable = $templateTable . " class=\"markerdot\"";
}
$templateTable = $templateTable . " x='" . $x . "' y='" . $y . "'>";
$templateTable = $templateTable . "</td>" . PHP_EOL;
}
$templateTable = $templateTable . "</tr>" . PHP_EOL;
}
$templateTable = $templateTable . "</table> </td>";
if ($column == 0) {
$tallestTemplateHeight = $highestY - $lowestY;
} else if (($highestY - $lowestY) > $tallestTemplateHeight) {
$tallestTemplateHeight = $highestY - $lowestY;
}
echo $templateTable;
$column += $highestX - $lowestX;
if ($column >= $maxColumns) {
$row += $tallestTemplateHeight;
echo "</tr></table><table><tr>";
}
}
fclose($listHandle);
?>
</div>
PS: I am open to discarding my current setup entirely.
I'll throw this out as an idea - FIDDLE
It uses divs instead of a table, and by playing with the loops, width, etc, you can adjust it as you see fit.
Everything fits together edge to edge.
JS
var counter = 0;
var numdivs = 8;
$('#clickme').click(function(){
for(var i=1; i < 50; ++i)
{
$("<div class='standarddiv'>X</div>").appendTo('.holder');
counter = counter + 1;
if(counter==numdivs)
{
$("<div class='clearboth'></div>").appendTo('.holder');
counter = 0;
}
}
});