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);
Related
How do I use the value of variable $dd i.e 10 or 100000 outside the if condition?
I want to show that status(available/not available) and the $dd value in separate locations.
ajax success
success: function (response) {
$("#uname_response").html(response);
}
if(isset($_POST['applied_promocode'])){
$applied_promocode = $_POST['applied_promocode'];
$dd = 0;
// Check applied_promocode
$stmt = $dbh->prepare("SELECT count(*) as cntUser FROM coupon WHERE applied_promocode=:applied_promocode");
$stmt->bindValue(':applied_promocode', $applied_promocode, PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->fetchColumn();
//Availability message
if($count > 0){
$response = "<span style='color: red;'>Not Available.</span>";
$dd = 10;
} else {
$response = "<span style='color: green;'>Available.</span>";
$dd = 100000;
}
echo $dd;
echo $response;
exit;
}
$discount_price = $dd * 100;
You can choose to send back data in JSON format if you want to be able to pass complex data (i.e. non-string value). The way to do that would be as follows:
Untested code
if($count > 0){
$response = "Not Available";
$dd = 10;
} else {
$response = "Available";
$dd = 100000;
}
$discount_price = $dd * 100;
$json_data = array('response'=>$response, 'dd' => $discount_price);
echo json_encode($json_data);
Then on the client side, you can use something like this:
success: function (response) {
var json_data = JSON.parse(response);
var color = "red";
if(json_data.response == 'Available')
{
color = "green";
}
var html = "<span style='color: "+color+";'>"+json_data.response+".</span><p>"Discounted price = "+json_data.dd+"</p>";
$("#uname_response").html(html);
}
Or if you do not like concatenation, use the traditional approach to manipulate the DOM
success: function (response) {
var json_data = JSON.parse(response);
if(json_data && json_data.response)
{
var color = "red";
if(json_data.response == 'Available')
{
color = "green";
}
var span = document.createElement('span');
span.style.color = color;
span.innerHTML = json_data.response;
var p = document.createElement('p');
p.innerHTML = "Discounted price is "+json_data.dd;
var div = document.createElement('div');
div.appendChild(span);
div.appendChild(p);
$("#uname_response").html(div);
}
else
{
alert("Invalid data returned from server");
}
}
I want to write recursive code using loops instead of recursion function. because recursion take too much time to execute and even fails.This is counting user in both side of binary tree using recursion.i want to achieve this task using loops. please help me to achieve this task.thanks in advance.I will very thank full to you.
function countActiveMembers($mid){
if ($mid == null) {
return 0;
}
$c = 0;
include("conn.php");
$query = $conn->prepare('SELECT leftm, rightm, package_choose FROM member WHERE user_id = ?');
$query->bind_param('s', $mid);
$query->execute();
$query->bind_result($leftm, $rightm, $package_choosen);
if ($query->fetch()) {
$query->close();
$conn->close();
if ($package_choosen == 1) {
$c = 0;
} else {
$c = 1;
}
if (isset($leftm) == false && isset($rightm) == false) {
return $c;
}
if (isset($leftm)) {
$c = $c + countActiveMembers($leftm);
}
if (isset($rightm)) {
$c = $c + countActiveMembers($rightm);
}
} else {
$query->close();
$conn->close();
}
return $c;
}
function countLeftActive($mid){
if ($mid == null) {
return 0;
}
$c = 0;
include("conn.php");
$query = $conn->prepare('SELECT leftm, rightm, package_choose FROM member WHERE user_id = ?');
$query->bind_param('s', $mid);
$query->execute();
$query->bind_result($leftm, $rightm, $package_choosen);
if ($query->fetch()) {
$query->close();
$conn->close();
if (isset($leftm) == false && isset($rightm) == false) {
return 0;
}
if (isset($leftm)) {
$c = $c + countActiveMembers($leftm);
}
} else {
$query->close();
$conn->close();
}
return $c;
}
function countRightActive($mid){
if ($mid == null) {
return 0;
}
$c = 0;
include("conn.php");
$query = $conn->prepare('SELECT leftm, rightm, package_choose FROM member WHERE user_id = ?');
$query->bind_param('s', $mid);
$query->execute();
$query->bind_result($leftm, $rightm, $package_choosen);
if ($query->fetch()) {
$query->close();
$conn->close();
if (isset($leftm) == false && isset($rightm) == false) {
return 0;
}
if (isset($rightm)) {
$c = $c + countActiveMembers($rightm);
}
} else {
$query->close();
$conn->close();
}
return $c;
}
I hope you can appreciate that this is difficult to test, so hopefully you can understand it enough to help.
One of the big performance issues in any system is file/database access and opening and closing connections etc. is always a slow process. This routine loads all the members in the start and passes the data around rather than continually using the database...
function countActiveMembers( $members, $mid){
if ($mid == null) {
return 0;
}
$c = 0;
// Fetch the data from the $members list, using $mid as the index
$leftm = $members[$mid]['leftm'];
$rightm = $members[$mid]['rightm'];
$package_choosen = $members[$mid]['package_choose'];
if ($package_choosen == 1) {
$c = 0;
} else {
$c = 1;
}
if (isset($leftm) == false && isset($rightm) == false) {
return $c;
}
if (isset($leftm)) {
$c = $c + countActiveMembers($members, $leftm);
}
if (isset($rightm)) {
$c = $c + countActiveMembers($members, $rightm);
}
return $c;
}
function countLeftActive($members, $mid){
if ($mid == null) {
return 0;
}
$c = 0;
$leftm = $members[$mid]['leftm'];
$rightm = $members[$mid]['rightm'];
if (isset($leftm) == false && isset($rightm) == false) {
return 0;
}
if (isset($leftm)) {
$c = $c + countActiveMembers($members, $leftm);
}
return $c;
}
function countRightActive($members, $mid){
if ($mid == null) {
return 0;
}
$c = 0;
$leftm = $members[$mid]['leftm'];
$rightm = $members[$mid]['rightm'];
if (isset($leftm) == false && isset($rightm) == false) {
return 0;
}
if (isset($rightm)) {
$c = $c + countActiveMembers($members, $rightm);
}
return $c;
}
// Use your own database credentials
$conn = mysqli_connect("172.17.0.3", "root","a177fgvTRw", "test" );
$result = $conn->query('SELECT user_id, leftm, rightm, package_choose
FROM member');
$members = [];
// Read all the members in and index them by the user_id
while ($row = $result->fetch_assoc()) {
$members[$row["user_id"]] = $row;
}
// Not entirely sure how you use it,but this shows passing the members into the start function
echo countActiveMembers($members, 1);
im quite new to PHP and im trying to make a pagination, the code works! but i need to click on the button twice to make the page refreshed/change. how do i fix this?
view/main/user/userlist.php
<?php
$_SESSION['pagelim'] = 10;
$_SESSION['page'] = $_GET['halaman'];
if ($_SESSION['page'] == '') {
$_SESSION['pos'] = 0;
$_SESSION['page'] = 1;
} else {
$_SESSION['pos'] = ($_SESSION['page']- 1) * $_SESSION['pagelim'];
}
$itemcount = listpetugas::getlisted();
$pagecount = ceil(listpetugas::getlisted()/$_SESSION['pagelim']);
for ($i=1;$i<=$pagecount;$i++)
{ ?>
<?php
if ($i!=$pagecount){
echo " <ul class='pagination'><li><a href='?controller=main&action=userlist&halaman=$i' onclick='myFunction()'>$i</a></li></ul>";?>
<?php }
else{
echo "$i";
} ?>
<?php } ?>
model/userdb.php
public static function listemup()
{
if ($_SESSION['pos'] =='' && $_SESSION['pagelim'])
{
$pos = 0;
$lim = 10;
}
else {
$pos = $_SESSION['pos'];
$lim = $_SESSION['pagelim'];
}
$list = [];
$db = FirstFire::StartConnection();
$req = $db->query("SELECT * FROM randomity LIMIT $pos,$lim");
$rowcount = $req->rowCount();
foreach ($req->fetchAll() as $post) {
$list[] = new listpetugas($post['name'],$post['email'],$post['adress'],$post['wow']);
}
return $list;
}
JS
<script>
function myFunction() {
location.reload();
}
</script>
sorry for the messy code.
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 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);
}