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;
}
Related
My jQuery Datatable is not sorting properly in some columns. When I sort the GGC_ID column, it's sorting properly, but when I sort the CustomerID column, its not sorting. And when I sort the Customer Name column, the CustomerID column is the one that is sorting.
Here's my code:
record.js:
var tbl = $('#tbl').DataTable({
"processing": true,
"serverSide": true,
"order": [],
"searchable": true,
"columnDefs": [
{
"orderable": false,
"targets": [0,4]
}
],
"ajax": {
url: "fetch.php",
method: "POST"
}
});
fetch.php
$query = '';
$query .= "SELECT records.GGC_ID, company.Comp_Name, customer.CUST_ID, customer.CUST_NAME FROM records INNER JOIN company on company.Comp_ID = records.COMP_ID INNER JOIN customer ON customer.CUST_ID = records.CUST_ID ";
if(isset($_POST["search"]["value"]))
{
$query .= 'WHERE Comp_Name LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR CUST_NAME LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR GGC_ID LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"])) {
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].
' ';
} else {
$query .= "ORDER BY GGC_ID DESC ";
}
if($_POST["length"] != -1) {
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$stmt = $db->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
$data = array();
$filtered_rows = $stmt->rowCount();
foreach ($result as $row) {
$sub_array = array();
$sub_array[] = $row["Comp_Name"];
$sub_array[] = $row["GGC_ID"];
$sub_array[] = $row["CUST_ID"];
$sub_array[] = $row["CUST_NAME"];
$sub_array[] = '<button type="button" name="update" id="'.$row["CUST_ID"].'"
class = "btn btn-default details" data-toggle="modal" data-target="#customer_modal">Details</button> ';
$data[] = $sub_array;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rows,
"recordsFiltered" => get_total_all_records(),
"data" => $data
);
echo json_encode($output);
$_REQUEST["order"][0][column] - does not have field name, it has index of field in columns
$index = $_REQUEST["order"][0][column];
ORDER BY $_REQUEST["columns"][ $index ]["name"]
You can open google console, network tab, find server request - header tab to see variables it sends.
Also
echo "<pre>";
print_r($_REQUEST);
echo "</pre>";
exit();
Your fixed code:
$index = $_POST['order']['0']['column'];
$field = $_POST["columns"][ $index ]["name"];
$query .= 'ORDER BY '.$field.' '.$_POST['order']['0']['dir'].
' ';
When you sort the Customer Name column, echo $query, check sql is right.
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
I have a page with buttons that a user clicks on.
When the button gets clicked I need it to change the image and call a php script to save the change.
I somehow can't get the button to do both, it changes the pic but won't call the php.
CODE:
<?php
$db = new PDO('mysql:host=localhost;dbname=MySettings;charset=utf8mb4', 'TestUser', '1234567890');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
try {
$mytable = $_SESSION["SESS_myuserid"];
if($mytable == null)
{$url='login.php';
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';}
$stmt = $db->prepare("SELECT * FROM ".$mytable);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$conn = null;
echo'<script>';
$count = count($result);
for ($i = 0; $i < $count; $i++) {
$TheId = $result[$i]['Id'];
$TheFunction = $result[$i]['TheFunction'];
$TheSetting = $result[$i]['TheSetting'];
if ($TheSetting == "0"){
echo 'var newsrc'.$TheId.' = "on.jpg";';
}
else{
echo 'var newsrc'.$TheId.' = "off.jpg";';
}
echo 'function changeImage'.$TheId.'() {';
echo 'if ( newsrc'.$TheId.' == "off.jpg" ) {';
echo "document.getElementById('pic".$TheId."').src = '/images/Boff.png';";
echo "$('#newCode').load('Monitor.php?id=".$TheId."&Table=".$mytable."');";
echo 'newsrc'.$TheId.' = "on.jpg";';
echo '}';
echo 'else {';
echo "document.getElementById('pic".$TheId."').src = '/images/Bon.png';";
echo "$('#newCode').load('Monitor.php?id=".$TheId."&Table=".$mytable."');";
echo 'newsrc'.$TheId.' = "off.jpg";';
echo '}';
echo '}';
}
echo'</script>';
$myLeft=0;
$myTop=0;
$myRow=0;
for ($i = 0; $i < $count; $i++) {
$TheId = $result[$i]['Id'];
$TheFunction = $result[$i]['TheFunction'];
$TheSetting = $result[$i]['TheSetting'];
if ($TheSetting == "0"){
$ThePic = "images/Boff.png";
}
else{
$ThePic = "images/Bon.png";
}
echo '<div>';
echo ' ';
echo '</div>';
$myTop=$myTop + 30;
$myRow=$myRow + 1;
if ($myRow == 12){
$myRow=0;
$myTop=0;
if ($myLeft == 0){
$myLeft = 292;
}
else {
$myLeft = 615;
}
}
}
}
catch(PDOException $e) {
$url='login.php';
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';
}
?>
Fixed :
Changed the script function. Added a hidden div to be called to load the php which outputs nothing so stays invisible.
echo'<script>';
$count = count($result);
for ($i = 0; $i < $count; $i++) {
$TheId = $result[$i]['Id'];
$TheFunction = $result[$i]['TheFunction'];
$TheSetting = $result[$i]['TheSetting'];
if ($TheSetting == "0"){
echo 'var newsrc'.$TheId.' = "on.jpg";';
}
else{
echo 'var newsrc'.$TheId.' = "off.jpg";';
}
echo 'function changeImage'.$TheId.'() {';
echo 'if ( newsrc'.$TheId.' == "off.jpg" ) {';
echo "document.getElementById('pic".$TheId."').src = '/images/Boff.png';";
echo 'newsrc'.$TheId.' = "on.jpg";';
echo '}';
echo 'else {';
echo "document.getElementById('pic".$TheId."').src = '/images/Bon.png';";
echo 'newsrc'.$TheId.' = "off.jpg";';
echo '}';
echo' $("#HtmlConvo").load("Monitor.php?id='.$TheId.'&Table='.$mytable.'");';
echo '}';
}
echo'</script>';
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;
}
}
});