I hope moderators doesn't mark this question as duplicated cause i research for this problem almost 1week and can't figure out what is wrong.
I have this code, for searching data from MySQL database tables, atm it doesn't read Unicode chars. My guess is $_GET function string to read Unicode chars, because of that, I sated MySQL table charset to utf-8 and columns collation are utf8_general_ci and also I added this two lines into php code:
header('Content-Type: text/html; charset=utf-8');
mysqli_set_charset($connect,'utf8');
but still the result of Unicode chars are 0. If I type "a" in input, it shows the all words which starts by "a" or "ä,å á..." but, if I type some Unicode char for example "ä" it says "no result founded".
Code is also online atm here is the link http://dic.munjutut.fi/php/
Also I have added utf-8 meta to HTML file. I hope someone tell me what is wrong. The code itself is:
header('Content-Type: text/html; charset=utf-8');
mysqli_set_charset($connect,'utf8');
if(isset($_GET['p'])) {
$page_number = $_GET['p'];
$arraySearch = $_GET['terms'];
$show_count = $_GET['count'];
settype($page_number, 'integer');
}
$nospaces = substr($_GET['terms'],1,4);
$offset = ($page_number - 1) * $records_number;
// check for an empty string and display a message.
if ($_GET['terms'] == "") {
echo '<div id="counter">Type "äää" or "ääää"!</div>';
// minim 3 characters condition
} else if(strlen($_GET['terms']) < $limitchar) {
echo '<div id="counter">'. $limitchar .' characters minimum</div>';
} else {
// explode search words into an array
$arraySearch = explode(" ", $_GET['terms']);
// table fields to search
$arrayFields = array(0 => $first_field, 1 => $second_field);
$countSearch = count($arraySearch);
$a = 0;
$b = 0;
$query = "SELECT * FROM $table_name WHERE (";
$countFields = count($arrayFields);
while ($a < $countFields)
{
while ($b < $countSearch)
{
$query = $query."$arrayFields[$a] LIKE '$arraySearch[$b]%'";
$b++;
if ($b < $countSearch)
{
$query = $query." AND ";
}
}
$b = 0;
$a++;
if ($a < $countFields)
{
$query = $query.") OR (";
}
}
$query = $query.") LIMIT $offset, $records_number;";
$search = mysqli_query($connect, $query);
// get number of search results
$arrayFields = array(0 => $first_field);
$countSearch = count($arraySearch);
$a = 0;
$b = 0;
$query = "SELECT * FROM $table_name WHERE (";
$countFields = count($arrayFields);
while ($a < $countFields)
{
while ($b < $countSearch)
{
$query = $query."$arrayFields[$a] LIKE '%$arraySearch[$b]%'";
$b++;
if ($b < $countSearch)
{
$query = $query." AND ";
}
}
$b = 0;
$a++;
if ($a < $countFields)
{
$query = $query.") OR (";
}
}
$query = $query.")";
$count_results = mysqli_query($connect, $query) or die(mysqli_error($connect));
$numrows = mysqli_num_rows($count_results);
// no results
if($numrows == 0) {
echo '<div id="counter">No results found</div>';
// show results
} else {
echo '<div id="results">
<div id="results_top"><p><b>'. $_GET['terms'] .'</b> - '. $numrows .' results found</p></div>
';
Ajax codes in 2 file:
search_id = '';
function handleHttpResponse() {
if (http.readyState == 4) {
if (search_id != '') {
document.getElementById(search_id).innerHTML = http.responseText;
}
}
}
function getHTTPObject() {
var xmlhttp;
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
var http = getHTTPObject();
function getScriptPage(div_id,terms_id,get_count,get_p) {
search_id = div_id;
zearch = document.getElementById(terms_id).value;
http.open("GET", "search.php?terms=" + escape(zearch)+"&count="+get_count+"&page="+get_p, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
and
function GetXmlHttpObject(handler)
{
var objXMLHttp=null
if (window.XMLHttpRequest)
{
objXMLHttp=new XMLHttpRequest()
}
else if (window.ActiveXObject)
{
objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
// show_results will be filled with new page
document.getElementById("show_results").innerHTML = xmlHttp.responseText;
document.getElementById("show_results").scrollIntoView();
}
}
function htmlData(url, terms, pag)
{
if (url.length==0)
{
document.getElementById("show_results").innerHTML = "";
return;
}
xmlHttp = GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
url=url+"?"+terms+"&"+pag;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange = stateChanged;
xmlHttp.open("GET",url,true) ;
xmlHttp.send(null);
}
#CBroe fixed this for me! Big thanks for him! Problem was with AJAX and encoding. I used escape function instead encodeURIComponent. Here the fixed code:
Old one:
http.open("GET", "search.php?terms=" + escape(zearch)+"&count="+get_count+"&page="+get_p, true);
Fixed:
http.open("GET", "search.php?terms=" + encodeURIComponent(zearch)+"&count="+get_count+"&page="+get_p, true);
I have a problem with my Flash (.fla) project. I've connected my flash with database with php script. I used ActionScript 2.0.
The problem is data can show at compile program on AdobeFlash CS6 (CTRL+Enter) but data cant show in datagrid when I open the .swf.
It's my php script
<?php
mysql_pconnect ("localhost", "root", "");
mysql_select_db ("modul");
$qr = mysql_query("SELECT * from nilaisiswa");
if (!qr || mysql_num_rows($qr)==0) {
$r_string = '&errorcode=3&msg='.mysql_error().'&';
} else {
$r_string = '&errorcode=0&n='.mysql_num_rows ($qr);
$i = 0;
while ($row = mysql_fetch_assoc ($qr)) {
while (list ($key, $val) = each ($row)) {
$r_string .= '&' . $key . $i . '=' . stripslashes($val);
}
$i++;
}
$r_string .='&';
}
echo $r_string;
?>
And here it's my ActionScript 2.0
var select_lv:LoadVars = new LoadVars();
var insert_lv:LoadVars = new LoadVars();
var delete_lv:LoadVars = new LoadVars();
var today:Date = new Date();
var deleteIndex:Number;
var errorMsgs:Array = [
"",
"Couldn't connect to server",
"Couldn't connect to database",
"Error running query",
"First four entries may not be deleted"];
var filepath:String;
var scoreInfo:Array = [];
var headerListener:Object = {};
headerListener.headerRelease = function(event:Object) {
switch (event.columnIndex) {
case 0:
if (scores_dg.getColumnAt(0).sortedUp) {
scores_dg.sortItemsBy(scores_dg.columnNames[0], Array.CASEINSENSITIVE | Array.DESCENDING);
} else {
scores_dg.sortItemsBy(scores_dg.columnNames[0], Array.CASEINSENSITIVE);
}
scores_dg.getColumnAt(0).sortedUp = !scores_dg.getColumnAt(0).sortedUp;
break;
case 1:
if (scores_dg.getColumnAt(1).sortedUp) {
scores_dg.sortItemsBy(scores_dg.columnNames[1], Array.NUMERIC | Array.DESCENDING);
} else {
scores_dg.sortItemsBy(scores_dg.columnNames[1], Array.NUMERIC);
}
scores_dg.getColumnAt(1).sortedUp = !scores_dg.getColumnAt(1).sortedUp;
break;
}
}
function zerofill(n:Number):String {
if (n<10) return '0' + n.toString();
else return n.toString();
}
filepath = "http://localhost/tesis/";
nickname_ti.maxChars = 50;
date_ti.maxChars = 10;
score_ti.text = 0;
date_ti.text = today.getDate() + '-' + zerofill(today.getMonth()+1) + '-' + zerofill(today.getFullYear());
select_lv.onLoad = function(ok:Boolean) {
if (ok) {
if (this.errorcode=="0") {
for (var i:Number=0; i < this.n; i++) {
scoreInfo.push(
{record:this["id"+i],
nickname:this["nickname"+i],
score:Number(this["score"+i]),
dateposted:this["dateposted"+i]
});
}
scores_dg.columnNames = ["nickname", "score", "dateposted"];
scores_dg.getColumnAt(0).width = 130;
scores_dg.getColumnAt(0).sortOnHeaderRelease = false;
scores_dg.getColumnAt(0).sortedUp = false;
scores_dg.getColumnAt(0).headerText = "Nickname";
scores_dg.getColumnAt(1).width = 130;
scores_dg.getColumnAt(1).sortOnHeaderRelease = false;
scores_dg.getColumnAt(1).sortedUp = false;
scores_dg.getColumnAt(1).headerText = "Score";
scores_dg.getColumnAt(2).width = 130;
scores_dg.getColumnAt(2).headerText = "Date Posted";
scores_dg.dataProvider = scoreInfo;
scores_dg.addEventListener("headerRelease", headerListener);
msg_ta.text = "Enter data and click Add to add a score.";
} else {
msg_ta.text = errorMsgs[Number(this.errorcode)];
if (this.errorcode == "3") msg_ta.text += ": " + this.msg;
}
} else {
msg_ta.text = "Flash-database select operation failed";
}
}
msg_ta.text = "Getting high scores from database...";
select_lv.sendAndLoad(filepath + "getscores.php", select_lv, "GET");
I have an sql-database, where data can be read out by an html-form. The data are shown in an html-table, this works fine! However, I would like to make the table sortable, which means, that by clicking on the respective field-name the data should be sorted according to this field (ascending/descending). I have tried different javaScript-solutions including tablesorter.com that work well in "normal" tables, however, not in this table that is built dynamically with data from a database. Here is my code that creates the table (code without specific link to JavaScript-files):
$sql = "SELECT * FROM fruitdatabase WHERE (" . implode(", ",
$spalten) . ") = (" . implode(", ", $werte) . ")";
$result = mysqli_query($db, $sql) or die("Invalid query"); //Running the
query and storing it in result
$numrows = mysqli_num_rows($result); // gets number of rows in result
table
$numcols = mysqli_num_fields($result); // gets number of columns in
result table
$field = mysqli_fetch_fields($result); // gets the column names from the
result table
$row = mysqli_fetch_array($result);
if ($numrows > 0) {
echo "<table id=myTable class=tablesorter>";
echo "<thead><tr>";
echo "<th>" . 'Nr' . "</th>";
for($x=0;$x<$numcols;$x++){
echo "<th>" . $field[$x]->name . "</th>";
}
echo "</tr></thead>";
echo "<tbody><tr>";
$nr = 1;
while ($row = mysqli_fetch_array($result)) {
echo "<td>" . $nr . "</td>";
for ($k=0; $k<$numcols; $k++) { // goes around until there are no
columns left
echo "<td>" . $row[$k] . "</td>"; //Prints the data
}
$nr = $nr + 1;
echo "</tr></tbody>";
}
echo "</table>";
}
}
mysqli_close($db);
?>
One of the javaScript-files I tried:
(function () {
"use strict";
var tableSort = function (tab) {
var titel = tab.getElementsByTagName("thead")
[0].getElementsByTagName("tr")[
0].getElementsByTagName("th");
var tbdy = tab.getElementsByTagName("tbody")[0];
var tz = tbdy.rows;
var nzeilen = tz.length;
if (nzeilen == 0) return;
var nspalten = tz[0].cells.length;
var arr = new Array(nzeilen);
var sortiert = -1;
var sorttype = new Array(nspalten);
var sortbuttonStyle = document.createElement
('style'); // Stylesheet für Button im TH
sortbuttonStyle.innerText =
'.sortbutton { width:100%; height:100%; border:
none; background-color: transparent; font: inherit; color: inherit; text-
align: inherit; padding: 0; cursor: pointer; } .sortbutton::-moz-focus-
inner { margin: -1px; border-width: 1px; padding: 0; }';
document.head.appendChild(sortbuttonStyle);
var initTableHead = function (sp) { // Kopfzeile
vorbereiten
var b = document.createElement("button");
b.type = "button";
b.className = "sortbutton";
b.innerHTML = titel[sp].innerHTML;
b.addEventListener("click", function () {
tsort(sp);
}, false);
titel[sp].innerHTML = "";
titel[sp].appendChild(b);
}
var getData = function (ele, s) {
var val = ele.innerHTML;
if (!isNaN(val) && val.search(/[0-9]/) !
= -1) return val;
var n = val.replace(",", ".");
if (!isNaN(n) && n.search(/[0-9]/) !=
-1) return n;
sorttype[s] = "s"; // String
return val;
} // getData
var vglFkt_s = function (a, b) {
var as = a[sortiert],
bs = b[sortiert];
if (as > bs) return 1;
else return -1;
} // vglFkt_s
var vglFkt_n = function (a, b) {
return parseFloat(a[sortiert]) -
parseFloat(b[sortiert]);
} // vglFkt_n
var tsort = function (sp) {
if (sp == sortiert) arr.reverse(); //
Tabelle ist schon nach dieser Spalte sortiert, also nur Reihenfolge
umdrehen
else { // Sortieren
sortiert = sp;
if (sorttype[sp] == "n")
arr.sort(vglFkt_n);
else arr.sort(vglFkt_s);
}
for (var z = 0; z < nzeilen; z++)
tbdy.appendChild(arr[z][nspalten]); // Sortierte Daten zurückschreiben
} // tsort
// Kopfzeile vorbereiten
for (var i = 0; i < titel.length; i++) initTableHead(i);
// Array mit Info, wie Spalte zu sortieren ist,
vorbelegen
for (var s = 0; s < nspalten; s++) sorttype[s] = "n";
// Tabelleninhalt in ein Array kopieren
for (var z = 0; z < nzeilen; z++) {
var zelle = tz[z].getElementsByTagName
("td"); // cells;
arr[z] = new Array(nspalten + 1);
arr[z][nspalten] = tz[z];
for (var s = 0; s < nspalten; s++) {
var zi = getData(zelle[s], s);
arr[z][s] = zi;
// zelle[s].innerHTML
+= "<br>"+zi+"<br>"+sorttype[s]; // zum Debuggen
}
}
} // tableSort
var initTableSort = function () {
var sort_Table = document.querySelectorAll
("table.sortierbar");
for (var i = 0; i < sort_Table.length; i++) new
tableSort(sort_Table[i]);
} // initTable
if (window.addEventListener) window.addEventListener("DOMContentLoaded",
initTableSort, false); // nicht im IE8
})();
Another of the javaScript-files I tried:
( function() {
"use strict";
var JB_sortbutStyle = document.createElement('style'); // Stylesheet
für Button im TH
JB_sortbutStyle.innerText = 'button.sortbut { width:100%; height:100%;
border: none; background-color: transparent; font: inherit; color:
inherit; text-align: inherit; padding: 0; cursor: pointer; }
button.sortbut::-moz-focus-inner { margin: -1px; border-width: 1px;
padding: 0; }';
document.head.appendChild(JB_sortbutStyle);
var JB_Table = function(tab) {
var up = String.fromCharCode(9650);
var down = String.fromCharCode(9660);
// var up = String.fromCharCode(8593);
// var down = String.fromCharCode(8595);
// var up = String.fromCharCode(11014);
// var down = String.fromCharCode(11015);
var no = String.fromCharCode(160,160,160,160); // Idee: 9674 ???
var dieses = this;
var defsort = 0;
var startsort_u = -1,startsort_d = -1;
var first = true;
var ssort;
var tbdy = tab.getElementsByTagName("tbody")[0];
var tz = tbdy.rows;
var nzeilen = tz.length;
if (nzeilen==0) return;
var nspalten = tz[0].cells.length;
var Titel = tab.getElementsByTagName("thead")
[0].getElementsByTagName("tr")[0].getElementsByTagName("th");
var Arr = new Array(nzeilen);
var ct = 0;
var sdir = new Array(nspalten);
var stype = new Array(nspalten);
var sortable = new Array(nspalten);
for(var i=0;i<nspalten;i++) {
stype[i] = "n";
sdir[i] = "u";
sortable[i] = false;
}
var initTableHead = function(t,nr) {
var b = document.createElement("button");
b.type = "button";
b.className = "sortbut"
b.innerHTML = t.innerHTML;
t.innerHTML = "";
if(window.addEventListener) b.addEventListener
("click",function() { dieses.sort(nr); },false);
b.title = 'Die Tabelle nach "'+b.textContent+'"
sortieren.';
t.appendChild(b);
sortsymbol.init(t,no);
if(t.className.indexOf("vorsortiert-")>-1) {
sortsymbol.set(t,down);
ssort = nr;
}
else if(t.className.indexOf("vorsortiert")>-1) {
sortsymbol.set(t,up);
ssort = nr;
}
if(t.className.indexOf("sortiere-")>-1) startsort_d=nr;
else if(t.className.indexOf("sortiere")>-1)
startsort_u=nr;
sortable[nr] = true;
} // initTableHead
var sortsymbol = {
init: function(t,s) {
var tt = t.querySelector("button");
var sp = tt.getElementsByTagName("span");
for(var i=0;i<sp.length;i++) {
if(!sp[i].hasChildNodes()) {
t.sym = sp[i].appendChild
(document.createTextNode(s));
break;
}
}
if(typeof(t.sym)=="undefined") t.sym =
tt.appendChild(document.createTextNode(s));
},
set: function(t,s) {
t.sym.data = s;
},
get: function(t) {
return t.sym.data;
}
} // sortsymbol
var VglFkt_s = function(a,b) {
var as = a[ssort], bs = b[ssort];
var ret=(as>bs)?1:(as<bs)?-1:0;
if(!ret && ssort!=defsort) {
if (stype[defsort]=="s") { as = a[defsort]; bs
= b[defsort]; ret = (as>bs)?1:(as<bs)?-1:0; }
else ret = parseFloat(a[defsort])-parseFloat(b
[defsort])
}
return ret;
} // VglFkt_s
var VglFkt_n = function(a,b) {
var ret = parseFloat(a[ssort])-parseFloat(b[ssort]);
if(!ret && ssort!=defsort) {
if (stype[defsort]=="s") { var as = a
[defsort],bs = b[defsort]; ret = (as>bs)?1:(as<bs)?-1:0; }
else ret = parseFloat(a[defsort])-parseFloat(b
[defsort]);
}
return ret;
} // VglFkt_n
var convert = function(val,s) {
var dmy;
var trmdat = function() {
if(dmy[0]<10) dmy[0] = "0" + dmy[0];
if(dmy[1]<10) dmy[1] = "0" + dmy[1];
if(dmy[2]<10) dmy[2] = "200" + dmy[2];
else if(dmy[2]<20) dmy[2] = "20" + dmy[2];
else if(dmy[2]<99) dmy[2] = "19" + dmy[2];
else if(dmy[2]>9999) dmy[2] = "9999";
}
if(val.length==0) val = "0";
if(!isNaN(val) && val.search(/[0-9]/)!=-1) return val;
var n = val.replace(",",".");
if(!isNaN(n) && n.search(/[0-9]/)!=-1) return n;
n = n.replace(/\s| | |\u00A0/g,"");
if(!isNaN(n) && n.search(/[0-9]/)!=-1) return n;
if(!val.search
(/^\s*\d+\s*\.\s*\d+\s*\.\s*\d+\s+\d+:\d\d\:\d\d\s*$/)) {
var dp = val.search(":");
dmy = val.substring(0,dp-2).split(".");
dmy[3] = val.substring(dp-2,dp);
dmy[4] = val.substring(dp+1,dp+3);
dmy[5] = val.substring(dp+4,dp+6);
for(var i=0;i<6;i++) dmy[i] = parseInt(dmy
[i],10);
trmdat();
for(var i=3;i<6;i++) if(dmy[i]<10) dmy[i] = "0"
+ dmy[i];
return (""+dmy[2]+dmy[1]+dmy[0]+"."+dmy[3]+dmy
[4]+dmy[5]).replace(/ /g,"");
}
if(!val.search
(/^\s*\d+\s*\.\s*\d+\s*\.\s*\d+\s+\d+:\d\d\s*$/)) {
var dp = val.search(":");
dmy = val.substring(0,dp-2).split(".");
dmy[3] = val.substring(dp-2,dp);
dmy[4] = val.substring(dp+1,dp+3);
for(var i=0;i<5;i++) dmy[i] = parseInt(dmy
[i],10);
trmdat();
for(var i=3;i<5;i++) if(dmy[i]<10) dmy[i]
= "0"+dmy[i];
return (""+dmy[2]+dmy[1]+dmy[0]+"."+dmy[3]+dmy
[4]).replace(/ /g,"");
}
if(!val.search(/^\s*\d+:\d\d\:\d\d\s*$/)) {
dmy = val.split(":");
for(var i=0;i<3;i++) dmy[i] = parseInt(dmy
[i],10);
for(var i=0;i<3;i++) if(dmy[i]<10) dmy[i]
= "0"+dmy[i];
return (""+dmy[0]+dmy[1]+"."+dmy[2]).replace
(/ /g,"");
}
if(!val.search(/^\s*\d+:\d\d\s*$/)) {
dmy = val.split(":");
for(var i=0;i<2;i++) dmy[i] = parseInt(dmy
[i],10);
for(var i=0;i<2;i++) if(dmy[i]<10) dmy[i]
= "0"+dmy[i];
return (""+dmy[0]+dmy[1]).replace(/ /g,"");
}
if(!val.search(/^\s*\d+\s*\.\s*\d+\s*\.\s*\d+/)) {
dmy = val.split(".");
for(var i=0;i<3;i++) dmy[i] = parseInt(dmy
[i],10);
trmdat();
return (""+dmy[2]+dmy[1]+dmy[0]).replace
(/ /g,"");
}
stype[s] = "s";
// return val.toLowerCase().replace(/
\u00e4/g,"ae").replace(/\u00f6/g,"oe").replace(/\u00fc/g,"ue").replace(/
\u00df/g,"ss");
return val.toLowerCase().replace(/\u00e4/g,"a ").replace
(/\u00f6/g,"o ").replace(/\u00fc/g,"u ").replace(/\u00df/g,"ss");
} // convert
this.sort = function(sp) {
if(sp<0 || sp>=nspalten) return;
if(!sortable[sp]) return;
if (first) {
for(var z=0;z<nzeilen;z++) {
var zelle = tz[z].getElementsByTagName
("td"); // cells;
Arr[z] = new Array(nspalten+1);
Arr[z][nspalten] = tz[z];
for(var s=0;s<nspalten;s++) {
if (zelle[s].getAttribute("data-
sort_key"))
var zi = convert(zelle
[s].getAttribute("data-sort_key"),s);
else if (zelle[s].getAttribute
("sort_key"))
var zi = convert(zelle
[s].getAttribute("sort_key"),s);
else
var zi = convert(zelle
[s].textContent,s);
Arr[z][s] = zi ;
// zelle[s].innerHTML
+= "<br>"+zi; // zum Debuggen
}
}
first = false;
}
if(sp==ssort) {
Arr.reverse() ;
if ( sortsymbol.get(Titel[ssort])==down )
sortsymbol.set(Titel[ssort],up);
else
sortsymbol.set(Titel[ssort],down);
}
else {
if ( ssort>=0 && ssort<nspalten ) sortsymbol.set
(Titel[ssort],no);
ssort = sp;
if(stype[ssort]=="s") Arr.sort(VglFkt_s);
else Arr.sort(VglFkt_n);
if(sdir[ssort]=="u") {
sortsymbol.set(Titel[ssort],up);
}
else {
Arr.reverse() ;
sortsymbol.set(Titel[ssort],down);
}
}
for(var z=0;z<nzeilen;z++)
tbdy.appendChild(Arr[z][nspalten]);
if(typeof(JB_aftersort)=="function") JB_aftersort
(tab,tbdy,tz,nzeilen,nspalten,ssort);
} // sort
if(!tab.title.length) tab.title="Ein Klick auf die
Spalten\u00fcberschrift sortiert die Tabelle.";
for(var i=Titel.length-1;i>-1;i--) {
var t=Titel[i];
if(t.className.indexOf("sortier")>-1) {
ct++;
initTableHead(t,i);
defsort = i ;
if(t.className.indexOf("sortierbar-")>-1) sdir
[i] = "d";
}
}
if(ct==0) {
for(var i=0;i<Titel.length;i++)
initTableHead(Titel[i],i);
defsort = 0;
}
if(startsort_u>=0) this.sort(startsort_u);
if(startsort_d>=0) { this.sort(startsort_d); this.sort
(startsort_d); }
if(typeof(JB_aftersortinit)=="function") JB_aftersortinit
(tab,tbdy,tz,nzeilen,nspalten,-1);
} // JB_Table
var JB_initTableSort = function() {
if (!document.querySelectorAll) return;
var JB_Tables = [];
var Sort_Table = document.querySelectorAll("table.sortierbar,
table[sortable]");
for(var i=0;i<Sort_Table.length;i++) JB_Tables.push(new JB_Table
(Sort_Table[i]));
var pars = decodeURI(window.location.search.substring(1));
if(pars.length) { // jbts=((0,1),(10,0),(3,3),(2,2)) tnr,snr
pars = pars.replace(/\s/g,"");
pars = pars.match(/jbts=\(?(\(\d+,\d+\),?){1,}\)?/gi);
if(pars) {
pars = pars[0].substr(pars[0].search("=")+1);
pars = pars.replace(/\(\(/g,"(").replace(/\)
\)/g,")").replace(/\)\(/g,")|(").replace(/\),\(/g,")|(");
pars = pars.split("|");
for(var i=0;i<pars.length;i++) {
var p = pars[i].substring(1,pars
[i].length-1).split(",");
if(p[0]>-1&&p[0]<JB_Tables.length)
JB_Tables[p[0]].sort(p[1]);
}
}
}
} // initTableSort
if(window.addEventListener) window.addEventListener
("DOMContentLoaded",JB_initTableSort,false);
})();
I would be more than happy if anybody could help me with this Problem!
I used tablesorter for same purpose. I created table dynamically from database and it worked. First add to table id="myTable". After just call the script by adding code below:
$(document).ready(function()
{
$("#myTable").tablesorter();
}
);
Note: Don't forget to include src="jquery.tablesorter.js" (download it from download link).
Now you should be able to sort your table by all columns by just clicking on table header of column.
EDIT:
Insted of:
echo "<table id=myTable class=tablesorter>";
Put:
echo "<table id='myTable' class='tablesorter'>";
How about sorting the table before displaying?
For example, if your link to the page is:
http://example.com/view/product_table
The code for querying the table is:
function getTable($order = null) {
$statement = "SELECT * FROM product_table";
if ($order) {
// switch case to prevent sql injection
switch ($order) {
case: "price":
$statement .= " ORDER BY product_price";
break;
}
}
// Continue the build sql here
}
Have the sorting button redirect to:
http://example.com/view/product_table?sort=price
Call function by:
getTable($GET[sort]);
To further my answer
I would suggest separating the code responsible for displaying and the code for building data
Name your variable to something more meaningful
Currently your code is very hard to maintain and read.
I need to search every word of an string in the database. If an word exist it needs to be highlighted. The current script works, but needs a lot of memory for my server. I don't know how i make it easier, but maybe do you?
<?php
$total_messages = $_POST['total'] - 1;
for($x = 0; $x <= $total_messages; $x++)
{
//Search highlights
$result = $mysqli->query("SELECT * FROM highlights WHERE enabled=1")
while($row = $result->fetch_assoc())
{
//Vars for highlights
$highlight_txt = $row['value'];
$highlight_type = $row['type'];
$highlight_color = "black";
$highlight_title = null;
//If the text isnt empty
if($highlight_txt != null || $highlight_txt != "")
{
//Type highlights
if($highlight_type == "tree") //Tree type
{
$highlight_type = "18"; //Category number
$highlight_background = "pink"; //Background
if($row['option1'] != null)
{
$highlight_title = htmlentities($row['option1']);
}
}
else
{
$highlight_background = "yellow"; //Background
}
//Add highlight
$message = preg_replace("/\b($highlight_txt)\b/i", "<span class='bc_highlight' highlight-type='$highlight_type' highlight-value='$highlight_txt' style='background: $highlight_background; color: $highlight_color;' title=''>$highlight_txt</span>", $message);
}
}
echo $message; //Display the message
}
Why not doing something like this?
$messages = ["This is my message1","This is my message2"];
$highlights = [];
$result = $mysqli->query("SELECT * FROM highlights WHERE enabled=1")
while($row = $result->fetch_assoc()) {
$highlights[$row["value"]] = [
"type" => $row["type"],
"color" => $row["color"]
];
}
$callback = function($matches) use ($highlights) {
$word = $matches[1];
if(isset($highlights[$word])) {
$highlight = $highlights[$word];
return sprintf('<span style="color:%s">%s</span>',$highlight["color"],$word);
} else {
return $word;
}
};
foreach($messages as &$message) {
$message = preg_replace_callback("/(\w+)/i",$message,$callback);
}
Now All of this code works fine in Firfox but in IE the divs dont change when the php infomation changes.
Can some one help me please as i am working on a project and this is holding me back
Thank you.
Here is the jQuery Code:
$.ajaxSetup({ cache: false });
$(document).ready(function(){
$("#not").css('display','none');
$("#fonline").css('display','none');
$("#not").hide();
$("#fonline").hide();
$("#shfm").click(function () {
$("#not").hide();
$("#fonline").toggle();
});
$("#notifi").click(function () {
$("#fonline").hide();
$("#not").toggle();
});
});
function closeboxes() {
$("#fonline").hide();
$("#not").hide();
}
function loadContent(id) {
$("#contentArea").load("notifications.php?o="+id+"");
};
$(document).ready(function() {
$("#settings").toggle(
function () {
$(this).html('X Close');
},
function () {
$(this).html('Settings');
}
);
});
function FriendsContent(id) {
$("#fArea").load("friends_online.php?fo="+id+"");
};
$(document).ready(function() {
$("#Options").toggle(
function () {
$(this).html('X Close');
},
function () {
$(this).html('Options');
}
);
});
var refreshId = setInterval(function()
{
$('#fArea').fadeOut("slow").load('response.php').fadeIn("slow");
}, 10000);
PHP Code:
$cOption = $_GET['fo'];
switch($cOption) {
case 1:
$recordsPerPage = 5;
$pageNum = 1;
if(isset($_GET['pg'])) {
$pageNum = $_GET['pg'];
settype($pageNum, 'integer');
}
echo "<table width='98%' border='0' cellspacing='0' cellpadding='0'>";
$offset = ($pageNum - 1) * $recordsPerPage;
$onlineresult = mysql_query("SELECT * FROM online") or die (mysql_error());
while ($ousers = mysql_fetch_array($onlineresult)) {
$onuid = $ousers['uid'];
$flist = mysql_query("SELECT * FROM friends_list WHERE fid='$onuid' AND uid='$myid' LIMIT $offset, $recordsPerPage;") or die (mysql_error());
while ($fri = mysql_fetch_array($flist)) {
$id = $fir['id'];
$uid = $fri['uid'];
$fid = $fri['fid'];
$userinfomation = mysql_query("SELECT * FROM accounts WHERE id='$fid'");
$userinfo = mysql_fetch_array($userinfomation);
$v_tgid = $userinfo['tgid'];
echo "
<tr class='menutxt2'>
<td width='11%' height='21'><center>
</center></td>
<td width='50%'>$v_tgid</td>
<td width='39%'>View Profile</td>
</tr>
";
}
}
echo "</table>";
$query = "SELECT COUNT(id) AS id FROM friends_list;";
$result = mysql_query($query) or die('Mysql Err. 2');
$row = mysql_fetch_assoc($result);
$numrows = $row['id'];
$maxPage = ceil($numrows/$recordsPerPage);
$nav = '';
for($page = 1; $page <= $maxPage; $page++)
{
if ($page == $pageNum)
{
$nav .= "<span class='menutxt'>Pages: $page </span>";
}
else
{
$nav .= "";
}
}
if ($pageNum > 1) {
$page = $pageNum - 1;
$prev = "";
$first = "";
}
else {
$prev = '';
$first = '';
}
if ($pageNum < $maxPage) {
$page = $pageNum + 1;
$next = "";
$last = "";
}
else {
$next = '';
$last = '';
}
echo "$first <b>$prev</b> $nav<b> $next</b> $last";
echo "
";
break;
case 2:
echo 'Options';
break;
default:
echo 'Whoops, didn\'t understand that option: <i>'.$cOption.'</i>';
}
IE tends to cache ajax requests when you don't want it to. The .load() towards the end of your code is issuing a GET request which IE is probably caching instead of fetching from the server.
http://www.sitecrafting.com/blog/ajax-ie-caching-issues/
google search 'ie cache ajax jquery'