refresh multiple classes every n secs from php backend - javascript

I have some code in jquery that connects to php and refreshes the class with latest data. This is working ok. However, I need to update 3 classes and when it refreshses the values are empty.
Is there a way I can query db and update 3 classes with fresh data every n sec. Many thanks
js
// Update server with latest actions,destructions and return requests
setInterval(function() {
$.get('/domain/admin/refreshBox.php', function(data) {
$(".actions").text(data);
$(".retrievals").text(data);
$(".returns").text(data);
});
}, 10000);
php
$sql= mysqli_query($conn,"SELECT count(*) as total FROM act WHERE new = '1'");
$rows = mysqli_fetch_assoc($sql);
$num = $rows['total'];
//echo $num;
$ni = $num;
if($ni < 1) {
$ni = '0';
}
echo $ni;
$nisql= mysqli_query($conn,"SELECT count(*) as ni FROM act WHERE activity='New Intake' AND new = '1'");
$niintknum_row = mysqli_fetch_assoc($nisql);
$niintknum = $niintknum_row['ni'];
//echo $num;
$niintk_num = $niintknum;
if($niintk_num < 1) {
$niintk_num = '0';
echo $niintk_num;
$brtvsql= mysqli_query($conn,"SELECT count(*) as rtrv FROM act WHERE activity='Box Retrieval' AND new = '1'");
$brtv_row = mysqli_fetch_assoc($brtvsql);
$brtvnum = $brtv_row['rtrv'];
//echo $num;
$brtv_num = $brtvnum;
if($brtv_num < 1) {
$brtv_num = '0';
echo $brtv_num;
$brtnsql= mysqli_query($conn,"SELECT count(*) as brtn FROM act WHERE activity='Box Return' AND new = '1'");
$brtn_row = mysqli_fetch_assoc($brtnsql);
$brtnnum = $brtn_row['brtn'];
//echo $num;
$brtn_num = $brtnnum;
if($brtn_num < 1) {
$brtn_num = '0';
}
echo $brtn_num;

Related

How do I create directory using array_column

The following code creates two folders, one with the $folderName and one with the $date with the files uploaded. If I change the $folderName to something static like "uploadingFolder" it creates the folder with the files uploaded.
How can I get the naming convention for the folder I want uploaded with its contents: firstname lastname date.
$formdata = json_decode(file_get_contents("php://input"),true);
$fname = array_column($formdata, 'firstname');
$lname = array_column($formdata, 'lastname');
$date = date('d-m-Y');
$folderName = $fname[0].$lname[0].$date;
//$folderName = "uploadingFolder";
mkdir('uploads/'.$folderName, 0777, true);
$total = count($_FILES['files']['name']);
for( $i=0 ; $i < $total ; $i++ ) {
$tmpFilePath = $_FILES['files']['tmp_name'][$i];
$newFilePath = "uploads/".$folderName."/".$_FILES['files']['name'][$i];
if(move_uploaded_file($tmpFilePath, $newFilePath)){
echo "upload successful ";
} else {
echo "error uploading files ";
}
}
Sample of json
$sampledata = '{"step":3,"form":{"firstname":"Jackie","lastname":"Hamer","address":"#45 test street","phone":"8681234567","email":"jackie#gmail.com","id":"a0e4c2c2g6c2b1g6","passport":"4545454787T","country":"Grenada","date":"2020-06-13","rdate":"2020-06-11","hotel":"True Blue Bay","package":"10","payment":"10","pfirstname":"Jamie","plastname":"Grant","atravellerfirstname":"Jackie","atravellerlastname":"Browne","refereefname":"Jamie","refereelname":"Lester","refereeaddress":"#45 Test","refereephone":"8684567894","refereefname2":"Jamie","refereelname2":"Louis","refereeaddress2":"#45 Test","refereephone2":"8687878787","formfiles":[]},"countries":[{"Country":"Grenada","_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591657087,"_created":1591657074,"_id":"5edec27264396144390000cd"},{"Country":"Barbados","_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591657105,"_created":1591657105,"_id":"5edec2913763637d1700010f"},{"Country":"St. Lucia","_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591657142,"_created":1591657142,"_id":"5edec2b6303466c0d0000254"},{"Country":"Curacao","_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591720520,"_created":1591720483,"_id":"5edfba233336352eef0002f9"},{"Country":"Panama","_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591720527,"_created":1591720527,"_id":"5edfba4f363331fc08000133"},{"Country":"Cancun","_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591720558,"_created":1591720558,"_id":"5edfba6e38353443d10002c6"}],"hotels":[{"HotelName":"True Blue Bay","URL":"https://www.truebluebay.com/","Country":["Grenada"],"Image":{"path":"storage/uploads\\truebluebay.jpg"},"_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591720577,"_created":1589575617,"_id":"5ebeffc134306446460002b9","TestCountry":null}],"selectValue":"Grenada","files":[{},{},{},{},{},{}],"disabled":false,"sumbitted":false,"submitted":true}';
Like this;
<?php
$formdata = json_decode(file_get_contents("php://input"), true);
$fname = $formdata['form']['firstname'];
$lname = $formdata['form']['lastname'];
$date = date('d-m-Y');
$folderName = $fname.' '.$lname.' '.$date;
// Added spaces between for ya. Would recommend to do it like [YYYY-MM-DD Lastname Firstname] though
mkdir('uploads/'.$folderName, 0777, true);
$total = count($_FILES['files']['name']);
for( $i=0 ; $i < $total ; $i++ ) {
$tmpFilePath = $_FILES['files']['tmp_name'][$i];
$newFilePath = "uploads/".$folderName."/".$_FILES['files']['name'][$i];
if(move_uploaded_file($tmpFilePath, $newFilePath)){
echo "upload successful ";
} else {
echo "error uploading files ";
}
}
I did an test on this;
<?php
$sampledata = '{"step":3,"form":{"firstname":"Jackie","lastname":"Hamer","address":"#45 test street","phone":"8681234567","email":"jackie#gmail.com","id":"a0e4c2c2g6c2b1g6","passport":"4545454787T","country":"Grenada","date":"2020-06-13","rdate":"2020-06-11","hotel":"True Blue Bay","package":"10","payment":"10","pfirstname":"Jamie","plastname":"Grant","atravellerfirstname":"Jackie","atravellerlastname":"Browne","refereefname":"Jamie","refereelname":"Lester","refereeaddress":"#45 Test","refereephone":"8684567894","refereefname2":"Jamie","refereelname2":"Louis","refereeaddress2":"#45 Test","refereephone2":"8687878787","formfiles":[]},"countries":[{"Country":"Grenada","_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591657087,"_created":1591657074,"_id":"5edec27264396144390000cd"},{"Country":"Barbados","_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591657105,"_created":1591657105,"_id":"5edec2913763637d1700010f"},{"Country":"St. Lucia","_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591657142,"_created":1591657142,"_id":"5edec2b6303466c0d0000254"},{"Country":"Curacao","_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591720520,"_created":1591720483,"_id":"5edfba233336352eef0002f9"},{"Country":"Panama","_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591720527,"_created":1591720527,"_id":"5edfba4f363331fc08000133"},{"Country":"Cancun","_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591720558,"_created":1591720558,"_id":"5edfba6e38353443d10002c6"}],"hotels":[{"HotelName":"True Blue Bay","URL":"https://www.truebluebay.com/","Country":["Grenada"],"Image":{"path":"storage/uploads\\truebluebay.jpg"},"_mby":"5ebef4733964375a880000ca","_by":"5ebef4733964375a880000ca","_modified":1591720577,"_created":1589575617,"_id":"5ebeffc134306446460002b9","TestCountry":null}],"selectValue":"Grenada","files":[{},{},{},{},{},{}],"disabled":false,"sumbitted":false,"submitted":true}';
$formdata = json_decode($sampledata, true);
$fname = $formdata['form']['firstname'];
$lname = $formdata['form']['lastname'];
$date = date('d-m-Y');
$folderName = $fname.' '.$lname.' '.$date;
var_dump($folderName); // string(23) "Jackie Hamer 16-06-2020"
Extra important note: Be sure no illegal chars for folders exists in the first or lastname ! You should strip or replace illegal special chars!

Multiple fields with the same name in AJAX and PHP

Everyone.
I got some good help a couple of days ago, so I'm hoping that someone can show me where I'm going wrong here. Basically, what I'm trying to do is update a MySQL database in the background when a user clicks a button. The form is a series of records, and the records have common field names (ID, DSA_Number, Manager_Review, etc.) Right now, the code doesn't even seem to return success or failure messages.
Here's the script on the main page:
<script>
$(document).ready(function(){
$("#button").click(function(){
var DDD_Number=$("#DDD_Number").val();
var Manager_Review=$("#Manager_Review").val();
var RID=$("#RID").val();
var Services=$("Services").val();
var Dues_List=$("Dues_List").val();
var ID=$("ID").val();
var myrid=$("myrid").val();
var Manager_Comments=$("Manager_Comments").val();
var President_Comments=$("President_Comments").val();
var dataTosend='?DDD_Number='+DDD_Number+'&Manager_Review='+Manager_Review+'&RID='+RID+'&Services='+Services+'&Dues_List='+Dues_List+'&Manager_Comments='+Manager_Comments+'&President_Comments='+President_Comments;
$.ajax({
type: "GET",
url:'baseupdater-test.php' + dataTosend,
data:dataTosend,
async: true,
success:function(data){
document.getElementById('stuffhere').innerHTML.text = "Success.";
document.getElementById('stuffhere').innerHTML.text = data;
},
error: function(data){
document.getElementById('stuffhere').innerHTML.text = "Failure.";
}
});
});
</script>
Here's the code that draws the rows on the table:
<?php
/* This code writes the rows in the table for baserecord.php */
$n = 0;
$o = $n + 1;
$firstday = date('m/1/Y');
if(isset($_GET['MR'])) // If $_GET['MR'] is set ...
{
$MR = $_GET['MR']; // Set the variables.
$PR = $Pres_Rev;
}
else // If not, select the maximum (latest) Manager Review Date.
{
$getmr = "select max(STR_TO_DATE(Manager_Review_Date, '%m/%d/%Y')) as Manager_Review_Date,
President_Review_Date from clientdb.MRS2_test
inner join clients_MRS
on clientdb.clients_MRS.DDD_Case = clientdb.MRS2_test.DDD_Number
where SCID = '$ID';";
$rs2 = mysqli_query($con,$getmr);
$rvd = mysqli_fetch_assoc($rs2);
$MR = date('m/d/Y', strtotime($rvd['Manager_Review_Date']));
echo "MR: $MR<br>";
$PR = date('m/d/Y', strtotime($rvd['President_Review_Date']));
}
// The following query select the data for the row and orders it by the latest Manager Review Date.
$cliselect = "select distinct clientdb.Plans.Client_ID, clientdb.clients_MRS.DSA_Status, clientdb.clients_MRS.DSA_Status_Date, clientdb.clients_MRS.First_Name, clients_MRS.Last_Name, clientdb.clients_MRS.County, clientdb.Plans.DDD_Case, RID, Plans.Program, max(Plans.Plan) as MPlan, Tier, Plan_End_Date, clientdb.MRS2_test.RID, clientdb.MRS2_test.President_Comments, clientdb.MRS2_test.Manager_Comments, clientdb.MRS2_test.Services_Issues, clientdb.MRS2_test.Dues_List
from clientdb.Plans
inner join clientdb.clients_MRS on clientdb.clients_MRS.DDD_Case = clientdb.Plans.DDD_Case
inner join clientdb.MRS2_test on clientdb.MRS2_test.DDD_Number = clientdb.Plans.DDD_Case
where SCID = '$ID' and (DSA_Status = 'Active' OR (DSA_Status <> 'Active' AND STR_TO_DATE(DSA_Status_Date, '%d/%m/%Y') > STR_TO_DATE($firstday, '%m/%d/%Y'))) AND (Manager_Review_Date = '$MR')
group by clientdb.Plans.DDD_Case order by STR_TO_DATE(clientdb.MRS2_test.Manager_Review_Date, '%m/%d/%Y') DESC, clientdb.Plans.Last_Name;";
//echo "cliselect $cliselect<br>";
$cres = mysqli_query($con, $cliselect);
while ($dddr = mysqli_fetch_assoc($cres)) {
$DDD_Case = $dddr['DDD_Case'];
$First_Name = $dddr['First_Name'];
$Last_Name = $dddr['Last_Name'];
$County = $dddr['County'];
$Tier = $dddr['Tier'];
if($ddr['Plan_End_Date'] <> '')
{
$Plan_End_Date = $dddr['Plan_End_Date'];
}
$Pres_Comments = $dddr['President_Comments'];
$Mgr_Comments = $dddr['Manager_Comments'];
$Dues = $dddr['Dues_List'];
$Services = $dddr['Services_Issues'];
$RID = $dddr['RID'];
$mxselect = "select max(Plan) as MPlan from clientdb.Plans where clientdb.Plans.DDD_Case = '$DDD_Case';";
$rens = mysqli_query($con, $mxselect);
$rmm = mysqli_fetch_assoc($rens);
$MPlan = $rmm['MPlan'];
$endsel = "select Plan_End_Date, Program from clientdb.Plans where clientdb.Plans.DDD_Case = $DDD_Case and clientdb.Plans.Plan = $MPlan;";
$rsel = mysqli_query($con, $endsel);
$end = mysqli_fetch_assoc($rsel);
$Plan_End_Date = $end['Plan_End_Date'];
$Program = $end['Program'];
//The purpose of ths quer s to get the RID for each row.
$mrselect = "select * from MRS2_test where DDD_Number = '$DDD_Case' and Manager_Review_Date = '$MR'
group by DDD_Number, RID
order by RID DESC
Limit 1 ;";
$run = mysqli_query($con,$mrselect);
$mrss = mysqli_fetch_assoc($run);
$Manager_Review_Date = $mrss['Manager_Review_Date'];
$President_Review_Date = $mrss['President_Review_Date'];
$myRID = $mrss['RID'][$n];
echo "<tr><td>$o</td><td sorttable_customkey='$DDD_Case'><input class='ddd' type = 'text' value = '$DDD_Case' name = 'DDD_Number[]' size='6'></td><td sorttable_customkey='$Last_Name'>$First_Name $Last_Name</td><td>$County</td><td>$Program</td><td>$Tier</td><td sorttable_customkey='";
?>
<?php echo strtotime($Plan_End_Date);
echo "'>$Plan_End_Date</td><td><textarea class='expnd' name='Services[]'>$Services</textarea></td><td><input name='Dues_List[]'' type = 'text' value = '$Dues'></td><td><textarea class='expnd' name='Manager_Comments[]'>$Mgr_Comments</textarea></td><td><textarea class='expnd' name='President_Comments[]'>$Pres_Comments</textarea></td><td><input type='text' size='4' name = 'myrid[]' value='$RID' readonly></td><input type='hidden' name = 'manreview-orig' value='$Manager_Review_Date'></tr>";
$n = $n++;
$o++;
}
?>
And finally, this is the code that does the update:
<?php
include 'config.php';
$con = mysqli_connect($DB_server, $DB_user, $DB_password, $DB_database);
$Manager_Review = $_GET['Manager_Review'];
$Old_MR = $_GET['manreview-orig'];
//echo "OLD MR: $Old_MR<br>";
if($_GET['President_Review'] == '12/31/1969')
{
$President_Review = '';
}
if($_GET['President_Review'] <> '')
{
$President_Review = $_GET['President_Review'];
}
else
{
$President_Review = '';
}
$ID = $_GET['ID'];
$Services = $_GET['Services'];
echo "New Content!<br>";
$n = 0;
while ($n <= sizeof($_GET)) {
$ridselect = "select clientdb.MRS2_test.RID, clientdb.clients_MRS.DDD_Case, clientdb.clients_MRS.SCID from clientdb.MRS2_test
inner join clientdb.clients_MRS
on clientdb.clients_MRS.DDD_Case = clientdb.MRS2_test.DDD_Number
where Manager_Review_Date = '$Old_MR' and clientdb.clients_MRS.DDD_Case = clientdb.MRS2_test.DDD_Number
order by RID;";
$rsc = mysqli_query($con, $ridselect);
$rowrid = mysqli_fetch_assoc($rsc);
$RID = $_GET['myrid'][$n];
// echo "RID: $RID<br>";
$MDD = $_GET['RID'];
$myrid = $_GET['myrid'][$n];
$DDD_Case = $_GET['DDD_Number'][$n];
$Period = ltrim(substr($Manager_Review,0,2), "0");
$Services = mysqli_real_escape_string($con, $_GET['Services'][$n]);
$Manager_Comments = mysqli_real_escape_string($con, $_GET['Manager_Comments'][$n]);
$President_Comments = mysqli_real_escape_string($con, $_GET['President_Comments'][$n]);
$Dues_List = mysqli_real_escape_string($con, $_GET['Dues_List'][$n]);
$DDD_Case = $_GET['DDD_Number'][$n];
$updater = "update clientdb.MRS2_test set clientdb.MRS2_test.Services_Issues = '$Services',
clientdb.MRS2_test.Manager_Comments = '$Manager_Comments', clientdb.MRS2_test.President_Comments = '$President_Comments',
clientdb.MRS2_test.Dues_List = '$Dues_List', Period = '$Period' where DDD_Number = '$DDD_Case' and RID = '$RID';";
echo $updater . "<br>";
$date_updater = "update clientdb.MRS2_test set clientdb.MRS2_test.Manager_Review_Date = '$Manager_Review',
clientdb.MRS2_test.President_Review_Date = '$President_Review' where RID = '$RID';";
echo "dateupdater: $date_updater<br>";
if(!mysqli_query($con, $date_updater))
{
echo "That failed miserably.<br>";
}
else
{
$rws = mysqli_affected_rows($con);
echo "affected rows: $rws<br>";
echo "Success.<br>";
}
mysqli_query($con, $updater);
$datestamp = date('Y-m-d h:i:s');
$upstamp = "update clientdb.MRS2_test set Update_Time = '$datestamp' where DDD_Case = '$DDD_Case' and RID = '$RID';";
mysqli_query($con,$upstamp);
$n++;
}
echo "<script language='Javascript'>document.getElementById('stuffhere').InnerHTML = '<?php echo $updater; ?>';</script>";
?>
I've tried serializing the form, and I haven't had any success there. Any suggestions would be greatly welcome. Sorry for the long post, but I'm just not sure where the error is at this point.
Your code
var data= [DDD_Number,Manager_Review,RID,Services,Dues_List,ID,myrid,Manager_Comments,President_Comments];
var datatosend = JSON.stringify(data);
$.ajax({
type: "GET",
url:'baseupdater-test.php',
data:dataTosend,
async: true,
success:function(data){
document.getElementById('stuffhere').innerHTML.text = "Success.";
document.getElementById('stuffhere').innerHTML.text = data;
},
error: function(data){
document.getElementById('stuffhere').innerHTML.text = "Failure.";
}
});
As i can see you are trying to send the data twice, first through url and second with the ajax data method please fix that i think its a wrong approach to do that you should send it only once.
And moreover you must convert the data into json format to make the ajax request work
and now what's happening is as your data is not in the correct format your code must be stuck at the data in ajax you can see it in console the ajax request would not show you any value passing to another and that is the main reason the Success or Failure are not being show.

Php variable if else statement

I am trying to define my php variable for my php poll vote. I want to echo "Have a good day!" if the vote in for "Hello" is more that "Others" else echo "Have a good night!". :
if ($votePercent < $votePercent) {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
How to I define the variable $votePercent?
<div class="container">
<h3><?php echo $pollResult['poll']; ?></h3>
<p><b>Total Votes:</b> <?php echo $pollResult['total_votes']; ?></p>
<?php
if(!empty($pollResult['options'])){ $i=0;
//options bar color class array
$barColorArr = array('azure','emerald','violet','yellow','red');
//generate option bars with votes count
foreach($pollResult['options'] as $opt=>$vote){
//calculate vote percent
$votePercent = round(($vote/$pollResult['total_votes'])*100);
$votePercent = !empty($votePercent)?$votePercent.'%':'0%';
//define bar color class
if(!array_key_exists($i, $barColorArr)){
$i = 0;
}
$barColor = $barColorArr[$i];
?>
<div class="bar-main-container <?php echo $barColor; ?>">
<div class="txt"><?php echo $opt; ?></div>
<div class="wrap">
<div class="bar-percentage"><?php echo $votePercent; ?></div>
<div class="bar-container">
<div class="bar" style="width: <?php echo $votePercent; ?>;"></div>
</div>
</div>
</div>
<?php $i++; } } ?>
Back To Poll
</div>
This is the how I am connected to mysql.
<?php
class Poll{
private $dbHost = 'localhost';
private $dbUser = '';
private $dbPwd = '';
private $dbName = '';
private $db = false;
private $pollTbl = 'polls';
private $optTbl = 'poll_options';
private $voteTbl = 'poll_votes';
public function __construct(){
if(!$this->db){
// Connect to the database
$conn = new mysqli($this->dbHost, $this->dbUser, $this->dbPwd, $this->dbName);
if($conn->connect_error){
die("Failed to connect with MySQL: " . $conn->connect_error);
}else{
$this->db = $conn;
}
}
}
/*
* Runs query to the database
* #param string SQL
* #param string count, single, all
*/
private function getQuery($sql,$returnType = ''){
$result = $this->db->query($sql);
if($result){
switch($returnType){
case 'count':
$data = $result->num_rows;
break;
case 'single':
$data = $result->fetch_assoc();
break;
default:
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$data[] = $row;
}
}
}
}
return !empty($data)?$data:false;
}
/*
* Get polls data
* Returns single or multiple poll data with respective options
* #param string single, all
*/
public function getPolls($pollType = 'single'){
$pollData = array();
$sql = "SELECT * FROM ".$this->pollTbl." WHERE status = '1' ORDER BY created DESC";
$pollResult = $this->getQuery($sql, $pollType);
if(!empty($pollResult)){
if($pollType == 'single'){
$pollData['poll'] = $pollResult;
$sql2 = "SELECT * FROM ".$this->optTbl." WHERE poll_id = ".$pollResult['id']." AND status = '1'";
$optionResult = $this->getQuery($sql2);
$pollData['options'] = $optionResult;
}else{
$i = 0;
foreach($pollResult as $prow){
$pollData[$i]['poll'] = $prow;
$sql2 = "SELECT * FROM ".$this->optTbl." WHERE poll_id = ".$prow['id']." AND status = '1'";
$optionResult = $this->getQuery($sql2);
$pollData[$i]['options'] = $optionResult;
}
}
}
return !empty($pollData)?$pollData:false;
}
/*
* Submit vote
* #param array of poll option data
*/
public function vote($data = array()){
if(!isset($data['poll_id']) || !isset($data['poll_option_id']) || isset($_COOKIE[$data['poll_id']])){
return false;
}else{
$sql = "SELECT * FROM ".$this->voteTbl." WHERE poll_id = ".$data['poll_id']." AND poll_option_id = ".$data['poll_option_id'];
$preVote = $this->getQuery($sql, 'count');
if($preVote > 0){
$query = "UPDATE ".$this->voteTbl." SET vote_count = vote_count+1 WHERE poll_id = ".$data['poll_id']." AND poll_option_id = ".$data['poll_option_id'];
$update = $this->db->query($query);
}else{
$query = "INSERT INTO ".$this->voteTbl." (poll_id,poll_option_id,vote_count) VALUES (".$data['poll_id'].",".$data['poll_option_id'].",1)";
$insert = $this->db->query($query);
}
return true;
}
}
/*
* Get poll result
* #param poll ID
*/
public function getResult($pollID){
$resultData = array();
if(!empty($pollID)){
$sql = "SELECT p.subject, SUM(v.vote_count) as total_votes FROM ".$this->voteTbl." as v LEFT JOIN ".$this->pollTbl." as p ON p.id = v.poll_id WHERE poll_id = ".$pollID;
$pollResult = $this->getQuery($sql,'single');
if(!empty($pollResult)){
$resultData['poll'] = $pollResult['subject'];
$resultData['total_votes'] = $pollResult['total_votes'];
$sql2 = "SELECT o.id, o.name, v.vote_count FROM ".$this->optTbl." as o LEFT JOIN ".$this->voteTbl." as v ON v.poll_option_id = o.id WHERE o.poll_id = ".$pollID;
$optResult = $this->getQuery($sql2);
if(!empty($optResult)){
foreach($optResult as $orow){
$resultData['options'][$orow['name']] = $orow['vote_count'];
}
}
}
}
return !empty($resultData)?$resultData:false;
}
}
This is the index.php code.
<form method="post" action="">
<h3><?php echo $pollData['poll']['subject']; ?></h3>
<ul>
<?php foreach($pollData['options'] as $opt){
echo '<li><input type="radio" name="voteOpt" value="'.$opt['id'].'" >'.$opt['name'].'</li>';
} ?>
</ul>
<input type="hidden" name="pollID" value="<?php echo $pollData['poll']['id']; ?>">
<input type="submit" name="voteSubmit" value="Vote">
Results
</form>
This is my test url: php poll. Please let me know if you need more details. I am not sure which code is needed to be shown here. Thankyou so much for helping.
Try this --
results.php
if ($_GET['PollID'] == 2) {
$votePercent = "Have a good day!";
} else {
$votePercent = "Have a good night!";
}
index.php
In this page, radio button value are 1 and 2

Submenu keep active when user click on it and open in a new page

I have problem when a visitor clicks on a submenu and the link opens in a new page, so I want to keep that submenu active on that page.
I have css class active and javascript for opening it, what I need is to make it with php to be active.
This is UL with class:
This is my code. Can it be done with php or with javascript.
<ul>
<?php
$qKategori = ("SELECT * FROM kategori WHERE kprind = 0");
$rKategori = mysqli_query($dbc, $qKategori);
if ($rKategori) {
while ($exKat = mysqli_fetch_array($rKategori, MYSQLI_ASSOC)){
$emrikategorise = $exKat['kemri'];
$idkategori = $exKat['kid'];
$idprind = $exKat['kprind'];
?>
<li><?=$emrikategorise;?>
<ul>
<?php
$qPrind = ("SELECT * FROM kategori WHERE kprind = '".$idkategori."'");
$rPrind = mysqli_query($dbc,$qPrind);
while($prind = mysqli_fetch_array($rPrind)) {
?>
<li><?=$prind['kemri']?> </li>
<?php
}
mysqli_free_result($rPrind);
?>
</ul>
</li>
<?php }
mysqli_free_result($rKategori);
}
?>
</ul>
You can see menu on the left in The website is www.sitimobil.mk
You probably will need to build the array before outputting to be able to determine which menus should be active. You can also combine it with an optimization of the query to not have to do 1 query per category.
Something like:
$active = isset($_GET['kid'] ? $_GET['kid'] : -1;
$tree = array();
$list = array();
$qKategori = ("SELECT * FROM kategori ORDER BY kprind");
$rKategori = mysqli_query($dbc, $qKategori);
if ($rKategori) {
while ($exKat = mysqli_fetch_array($rKategori, MYSQLI_ASSOC)){
$id = $exKat['kid'];
//To prevent numerical array with unused space
$name = 'kategori'.$exKat['kid'];
$list[$name] = $exKat;
//Calculate depth to see if the menu is a sub..sub..sub menu etc.
$parent = $list[$name]['kprind'];
if($parent == 0) {
$list[$name]['depth'] = 0;
$list[$name]['childCount'] = 0;
}
else {
$list['kategori'.$parent]['childCount']++;
$list[$name]['depth'] = $list['kategori'.$parent]['depth']+1; //Increment
}
if($id == $active) {
$list[$name]['active'] = true;
while($parent != 0) {
$parentName = 'kategori'.$parent;
$list[$parentName]['active'] = true;
$parent = $list[$parentName]['kprind'];
}
}
else
$list[$name]['active'] = false;
}
mysqli_free_result($rPrind);
//Once we have that we can output the results...
function output_menu($list, $parent = 0, $active = false)
$activeClass = $active ? ' class="active"' : '';
echo '<ul'.$activeClass.'>';
foreach($list as $row){
if($row['kprind'] != $parent) continue;
$link = $row['kprind'] == 0 ? '#' : 'kategori.php?kid='.$row['kid'];
echo '<li>'.$row['kemri'].'';
if($row['childCount'] > 0)
output_menu($list, $row['kprind'], $row['active']);
echo '</li>';
}
echo '</ul>';
}
output_menu($list);
}
This is still a bit rough but should do the trick. It can probably be optimized so that we don't have to go through the list too many times but has the benefit of not having to request too many calls to the database. That should result in a lighter workload for the DB and faster output.

A simple approach to Infinite Scroll MySql Pulls

I'm having difficulty iterating through records while scrolling window. My initial thought was to load enough records to fit on screen then load an additional set when window scrolled to bottom. I've tried using session / variables to pass some counter to a function, no luck. The code below returns enough records to fit window height but with 0,10 limit. What would be a simple method to resolve this?
Another question is should I use LIMIT or ID > + LIMIT on the Mysql query?
$(function(){
setInterval(function(){
var totalHeight, currentScroll, visibleHeight;
if (document.documentElement.scrollTop)
{ currentScroll = document.documentElement.scrollTop; }
else
{ currentScroll = document.body.scrollTop; }
totalHeight = document.body.offsetHeight;
visibleHeight = document.documentElement.clientHeight;
if (totalHeight <= currentScroll + visibleHeight )
{
$.get('infinite_pull.php', function(data) {
$('body').append(data);
//alert('Load was performed.');
});
}
else
{
$('.dd').css('background-color','white');
}
}
, 100);
});
PHP
<?php
session_start();
mysql_connect('localhost','root','');
mysql_select_db('project5');
$query = "select user_email from users limit 0,10;";
$results= mysql_query($query);
while($row = mysql_fetch_array($results)){
echo $row['0'] . '<br/>';
}
?>
to call the php file multiple times sound bad,
all that overhead proberly worse then getting all at once.
can't you just calculate how many you need, and ask for that number?
<?php
$from = (int) $_GET['from'];
$count = (int) $_GET['count'];
mysql_connect('localhost','root','');
mysql_select_db('project5');
$query = "select user_email from users limit {$from},{$count};";
$results= mysql_query($query);
while($row = mysql_fetch_array($results)){
echo $row['0'] . '<br/>';
}
?>
i also think you should add an order by, to be sure the result always gets in the same order.
Use LIMIT, which combines a offset (1st param) and number of rows to get (2nd param). Here's a short example of pagination that get's the 7th page of a 100 numbers 7 at a time.
<?php
$arr = array();
for ( $x = 0; $x < 100; $x += 1 ) {
$arr[] = $x;
};
$page = 7;
$per_page = 7;
$current_page = 1;
for ( $z = 0; $z < count( $arr ); $z += 1 ) {
if ( 0 === ( $z % $per_page ) ) {
$current_page += 1;
}
if ( $current_page === $page ) {
$num_results = $current_page * $per_page;
$query = "select user_email from users limit {$num_results},{$per_page};";
echo "value $z on page $page via $query \n";
}
}
?>
Output:
$ php pagination.php
value 35 on page 7 via select user_email from users limit 49,7;
value 36 on page 7 via select user_email from users limit 49,7;
value 37 on page 7 via select user_email from users limit 49,7;
value 38 on page 7 via select user_email from users limit 49,7;
value 39 on page 7 via select user_email from users limit 49,7;
value 40 on page 7 via select user_email from users limit 49,7;
value 41 on page 7 via select user_email from users limit 49,7;

Categories

Resources