PHP concatenation not working properly - php

So i'm trying to build a pagination for my website without refreshing the page.
I'm using ajax, php and mysql for that purpose.
At the moment i'm stuck with php, specifically with foreach and concatenation.
Here's my foreach loop:
if (isset($_POST['page'])) {
$algus = $_POST['page'];
$loos = '';
$mitu = 5;
$msg = [];
foreach (uritused($conn, $id, $algus, $mitu) as $key => $vals) {
$loos .= "<tr class='tr-data'>";
$loos .= '<td>'.$vals['eventi_nimi'].'<br><span class="owner" data-id="'.$vals['owner-id'].'">'.$vals['owner'].'</span></td>';
$loos .= '<td data-loosiaeg="'.$vals['loosiAeg'].'">'.$vals['loosiAeg'].'</td>';
$loos .= '<td>'.$vals['attendiloos'].'</td>';
$loos .= '<td>';
if (is_array($vals['auhinnad'])) {
foreach($vals['auhinnad'] as $keys => $val){
$loos .= $val['auhind'].'<br>';
}
} else {
$loos .= $vals['auhinnad'];
}
$loos .= '</td>';
$loos .= '<td>Postitus: '.$vals['tingimused']['postitus'].'<br>Osalus: '.$vals['tingimused']['osalus'].'</td>';
$loos .= '<td>';
if (is_array($vals['valista'])) {
foreach($vals['valista'] as $keys => $val){
$loos .= $val['nimi'].'<br>';
}
} else {
$loos .= $vals['valista'];
}
$loos .= '</td>';
$loos .= '<td data-sec='.$vals['sec'].' class="tr-icons">
<i class="material-icons staatus ' . $vals['staatus'] . '" data-staatus="'.$vals['staatus'].'" data-toggle="tooltip" data-placement="bottom" data-class="stopped" data-eltext="radio_button_checked" data-text="radio_button_unchecked" title="Peata loosimine">radio_button_checked</i></td>';
$loos .= "</tr>";
}
$msg['data'] = $loos;
$msg['success'] = true;
echo json_encode($msg);
}
Here's my ajax call
var page = 1;
$.ajax({
type: "POST",
url: "pages/php/loosid_data.php",
cache: false,
dataType: 'json',
data: {'page': page},
success: function(msg){
console.log(msg);
if(msg['success']){
$('.tr-data').remove();
$('.m-loosid table').append(msg['data']);
}
},
error: function(msg){
console.log(msg);
}
});
EDIT: Heres the function
function uritused($conn, $id, $algus, $mitu){
try{
$uritused = $conn->prepare("SELECT COUNT(*) FROM loosid WHERE usr_id='$id'");
$uritused->execute();
}catch(PDOException $e){
echo $e->getMessage();
}
$uritus_arr = [];
$count = $uritused->fetchColumn();
if($count > 0){
try{
$urituseds = $conn->prepare("SELECT * FROM loosid WHERE usr_id='176237127636' ORDER BY loosiAeg DESC LIMIT 1, 5");
$urituseds->execute();
}catch(PDOException $e){
echo $e->getMessage();
}
$uritus = $urituseds->fetchAll();
for ($z=0;$z<$count;$z++) {
$uritus_arr[$z] = array(
'eventi_nimi' => $uritus[$z]['eventi_nimi'],
'loosiAeg' => $uritus[$z]['loosiAeg'],
'tingimused' => array(
'postitus' => $uritus[$z]['post'],
'osalus' => $uritus[$z]['osalus']
),
'sec' => $uritus[$z]['sec'],
'staatus' => $uritus[$z]['staatus'],
'attendiloos' => $uritus[$z]['attendiloos']
);
$auhinnad = explode(',', $uritus[$z]['auhinnad']);
if($uritus[$z]['auhinnad'] != '-'){
foreach ($auhinnad as $key) {
$auhind = explode('-', $key);
$auhinna_arr[] = array(
'auhind' => $auhind[0],
'voitjad' => $auhind[1]
);
}
$uritus_arr[$z]['auhinnad'] = $auhinna_arr;
}else{
$uritus_arr[$z]['auhinnad'] = $uritus[$z]['auhinnad'];
}
$valista = explode(',', $uritus[$z]['valista']);
if($uritus[$z]['valista'] != '-'){
foreach ($valista as $keys) {
$valistad = explode('-', $keys);
$valista_arr[] = array(
'nimi' => $valistad[0],
'id' => $valistad[1]
);
}
$uritus_arr[$z]['valista'] = $valista_arr;
}else{
$uritus_arr[$z]['valista'] = $uritus[$z]['valista'];
}
$valista_arr = [];
$auhinna_arr = [];
}
}
return $uritus_arr;
}
THIS NOW GIVES ME UNDEFINED OFFSET, ALTHOUGH I KNOW THAT THERE'S DATA WITH THAT INFO IN THE DB.
For some reason the data is always empty.
Whenever i try to run this same code inside my page directly without ajax, everything works as it should.
Maybe you guys have any suggestions on how to fix this? I know that there's already same kind of posts out here but i haven't found my answer yet.

#Gino Pane
I'm sorry but thats not the case actually. It seems that i made a rookie mistake with my query. I have only one instance of data in the database but my limit is set to 1, 5 but it should be 0, 5.
Basically my query was looking data from the database starting at 1 when it should've started at 0. Thats why it seemed to me that there is no data in the database.
I also said that when i echo foreach directly on the page it works because i had more than 1 instance of data in the database at that time.
Sorry for wasting your time guys.

Related

PHP echo last Array values

Im trying few hours repair my code but its always fail.
I have array in file:
$liquidyLista7 = array(
'Arbuz' => array(
'Wyraźny arbuz, soczysty arbuz, naprawde chyba najlepszy z oferty',
'Delikatny arbuz.',
'odświeżajacy arbuz',
'Bardzo delikatny, mniej wyrażny arbuz'
),
// and much more...
... i want to echo all values from each arrays but my "bad epic" code not work :/
function pokazOpisyVolish($liquidyLista7)
{
$i = 0;
$select = '<div id="volishPage'.$i.'" class="tab-pane fade"><ul class="comment-list">';
foreach($liquidyLista7 as $key => $record) {
$i++;
if (is_array($record)) {
$select .= '<li><p class="desc">'.$key.'</p>';
$select .= pokazOpisyVolish($record);
$select .= '</li>';
} else {
$select .= '<li><p class="desc">'.$record.'</p></li>';
}
}
$select .= '</ul></div>';
return $select;
echo pokazOpisyVolish($liquidyLista7);
Pls visit my test website and check how it works in "Mr Jack" (simple HTML - not PHP) but in "Volish" is my PHP code... :(
may be you are looking for some thing like this. the link you gave
uses plugin and css to display the result onto the webpage,
i can show you how to do it, but after that you have use your own css to display the result, i am thinking you might have add some div
name
just run this code in separate file, and you are good, understand what's happening and than add the div
<?php
$liquidyLista7 = array(
'Arbuz' => array(
'Wyraźny arbuz, soczysty arbuz, naprawde chyba najlepszy z oferty',
'Delikatny arbuz.',
'odświeżajacy arbuz',
'Bardzo delikatny, mniej wyrażny arbuz'
),
'newArtist' => array(
'Wyraźny arbuz, soczysty arbuz, naprawde chyba najlepszy z oferty',
'Delikatny arbuz.',
'odświeżajacy arbuz',
'Bardzo delikatny, mniej wyrażny arbuz'
)
);
//get the link from url
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
foreach ($liquidyLista7 as $key => $record) {
//ad artist name to the current url
echo "<a href=$actual_link?artistName=$key>$key</a><br>";
if(isset($_GET['artistName'])){
if(is_array($record)){
echo "<ul>";
foreach($liquidyLista7[$key] as $value)
if($_GET['artistName']==$key)
echo "<li>$value</li>";
}
echo "</ul>";
}
}
?>

I want to display subject for specific class i.e A or B but current I display only A?

I try to display every each data on the specific td, but I dont know where to fix my code. Please check the screenshop below to understand the clearly problems. Please any help to solve this problems.
<table class="table table-hover table-bordered ">
<tr><th>Day</th><th colspan="2">08:00-08:40</th><th colspan="2">8:40-09:20</th><th colspan="2">09:20-10:00</th><th>10:00-10:15</th><th colspan="2">10:15-10:55</th><th colspan="2">10:55-11:35</th><th colspan="2">11:35-12:15</th><th>12:15-01:15</th><th colspan="2">01:15-01:55</th><th colspan="2">01:55-02:35</th></tr>
<?php
$timesVariants = array("08:00-08:40", "08:40-09:20", "09:20-10:00", "10:00-10:15", "10:15-10:55", "10:55-11:35", "11:35-12:15", "12:15-01:15", "01:15-01:55","01:55-02:35");
$sqlquery = "SELECT * FROM timetable,classroom,subprogramme WHERE classroom.classid = timetable.classid AND subprogramme.subid = timetable.subid";
$res = $connect->query($sqlquery);
$classes = array();
while($row = $res->fetch_assoc()) {
$classes[$row['day']][$row['tid']][$row['time']] = array('courseid'=> $row['cid'], 'classname' => $row['classname'], 'subname' => $row['subname']);
}
//This is a loop
foreach($classes as $day => $daySchedule) {
foreach($daySchedule as $teacher) {
print '<tr>';
print "<td>$day</td>";
foreach($timesVariants as $time) {
if (empty($teacher[$time])){
print "<td>*</td><td>*</td>";
}
else{
print '<td>' . $teacher[$time]['courseid'] . '</td><td>' . $teacher[$time]['subname'] . ''. $teacher[$time]['classname'] . '</td>';
}
}
print '</tr>';
}
}
?>
</table>
Output
Results display on the webpage
You trouble is in the GROUP BY. MySql have no strict restrictions (by default) that each column should use aggregation function, so the result is the first row, instead of complicating SQL use PHP, your result seems not to be huge, so another loop will not affect performance:
$timesVariants = array("08:00-08:40", "08:40-09:20", "09:20-10:00", "10:00-10:15", "10:15-10:55", "10:55-11:35", "11:35-12:15", "12:15-1:15", "01:15-01:55","01:55-02:35");
$sqlquery = "SELECT * FROM timetable";
$classes = array();
while($row = $res->fetch_assoc()) {
$classes[$row['day']][$row['tid']][$row['time']] = array('subject'=> $row['subject'], 'class' => $row['class'], 'progid' => $row['progid']);
}
//This is a loop
foreach($classes as $day => $daySchedule) {
foreach($daySchedule as $teacher) {
print '<tr>';
print "<td>$day</td>";
foreach($timesVariants as $time) {
if (empty($teacher[$time]))
print "<td>None</td><td>None</td>";
else
print '<td>' . $teacher[$time]['subject'] . '</td><td>' . $teacher[$time]['class'] . '</td>';
}
print '</tr>';
}
}
<?php
if(isset($_POST["tid"])){
$tid = $connect->real_escape_string($_POST["tid"]);
$sqlquery = "SELECT * FROM timetable,classroom,subprogramme WHERE classroom.classid = timetable.classid AND subprogramme.subid = timetable.subid AND timetable.tid = ".$tid." ORDER BY timetable.timid ASC";
$res = $connect->query($sqlquery);
if($res->num_rows > 0){
?>
<table class="table table-bordered table-striped">
<tr><th>Day</th><th colspan="2">8:00-8:40</th><th colspan="2">8:40-9:20</th><th colspan="2">9:20-10:00</th><th colspan="2">10:00-10:15</th><th colspan="2">10:15-10:55</th><th colspan="2">10:55-11:35</th><th colspan="2">11:35-12:15</th><th colspan="2">12:15-1:15</th><th colspan="2">1:15-1:55</th><th colspan="2">1:55-2:35</th></tr>
<?php
$timesVariants = array("8:00-8:40", "8:40-9:20", "9:20-10:00", "10:00-10:15", "10:15-10:55", "10:55-11:35", "11:35-12:15", "12:15-01:15", "1:15-1:55","1:55-2:35");
$classes = array();
while($row = $res->fetch_assoc()) {
$classes[$row['day']][$row['tid']][$row['time']] = array('courseid'=> $row['cid'], 'classname' => $row['classname'], 'subname' => $row['subname']);
}
//This is a loop
foreach($classes as $day => $daySchedule) {
foreach($daySchedule as $teacher) {
print '<tr>';
print "<td>$day</td>";
foreach($timesVariants as $time) {
if (empty($teacher[$time])){
print "<td>*</td><td>*</td>";
}
else{
print '<td>' . $teacher[$time]['courseid'] . '</td><td>' . $teacher[$time]['subname'] . ''. $teacher[$time]['classname'] . '</td>';
}
}
print '</tr>';
}
}
?>
</table>
<?php
}
else{ print "<div class='alert alert-danger col-md-4'><span class='glyphicon glyphicon-remove'></span> Not yet set timetable</div>"; }
} ?>
</div>
The problems was on td I forgot to put colspan = 2, and other problem on sql query I forgot to inner join the tables in order to get all right that i want to display on the page.

nestedSortable on codeigniter

I do sorting function with codeigniter for pages with "nestedSortable".. When i click submit button it doesnt find " {sortable: cSortable}"
my code example:
in views
$(document).ready(function() {
$.post('<?php echo site_url('admin/pages/order_ajax'); ?>', {}, function(data) {
$('#orderResult').html(data);
});
$('#save').click(function() {
oSortable = $('.sortable').nestedSortable('toArray');
$.post('<?php echo site_url('admin/pages/order_ajax'); ?>', {sortable: cSortable}, function(data) {
$('#orderResult').html(data);
});
});
});
in model file
public function save_order($pages) {
if (count($pages)) {
foreach ($pages as $order => $page) {
dump($page);
if ($page['item_id'] != '') {
$data = array('parent_id' => (int) $page['parent_id'], 'order' => $order);
$this->db->set($data)->where($this->_primary_key, $page['item_id'])->update($this->_table_name);
echo '<pre>' . $this->db->last_query() . '</pre>';
}
}
}
}
in the controller file
public function order_ajax() {
// save order from ajax call
if (isset($_POST['sortable'])) {
$this->page_m->save_order($_POST['sortable']);
}
//fetch all pages
$this->data['pages'] = $this->page_m->get_nested();
//fetch view
$this->load->view('admin/pages/order_ajax', $this->data);
}
I see this error http://i57.tinypic.com/2uj6wpd.jpg
another error:
<?php
echo get_ol($pages);
function get_ol($array, $child = FALSE) {
$str = '';
if (count($array)) {
$str .= $child == FALSE ? '<ol class="sortable">' : '<ol>';
foreach ($array as $item) {
$str .= '<li id="list_' . $item['id'] . '">';
$str .= '<div>' . $item['title'] . '</div>';
//do we have childrens ?
if (isset($item['children']) && count($item['children'])) {
$str .= get_ol($item['children'], TRUE);
}
$str .= '</li>' . PHP_EOL;
}
$str .= '</ol>' . PHP_EOL;
}
return $str;
}
?>
so i dont get it shows me on line 10 and 11 that could't find name and title
"TypeError: parentItem is null
pid = parentItem[2];"
Looks like a type, wrong variable name. Should cSortable actually be oSortable?

Make more than one database call in wordpress plugin (PHP CRUD)

I have 2 pieces of code from a simple plugin that work independently from each other but don't work together.
if(isset($_POST['submit'])){
if(has_presence($_POST['product_name'])){
insert_row_into_table('CAL_products');
show_errors();
if(has_presence($wpdb->last_query)) {
echo "Update Successful";
} else {
echo "Update Failed";
}
} else {
echo "The field 'Product Name' cannot be blank.";
}
}
And this one
$results_array = $wpdb->get_results("SELECT * FROM wpCMS_CAL_products ORDER BY id ASC");
echo build_table_from_results_array($results_array);
The functions are included at the bottom.
The problem I have is that when the page loads there is no $_POST so it skips over the if statement and builds the table. This table builds fine.
When the form is submitted the if statements come back true and the new value is added to the database successfully, but then the table doesn't build until the page is refreshed. If the code to build the table is put at the top above the if statement it builds fine but doesn't include the new value until the page is refreshed.
Is it possible to add a new item to the database table before the results are populated to the HTML table?
function insert_row_into_table($table_name){
global $wpdb;
$prefix = $wpdb->prefix; //Define the wordpress table prefix
$table = $prefix . $table_name; //Build the table name
unset($_POST['submit']);
echo print_r($_POST);
$data = $_POST; //collect the data from post
$wpdb->insert( $table, $data ); //insert data into the table
}
function show_errors(){
echo $wpdb->show_errors();
echo $wpdb->print_error();
}
function has_presence($value) {
return isset($value) && $value !== "";
}
function build_table_from_results_array($results_array) {
$out = "";
$out .= "<table class=\"widefat\">";
$out .= "<thead>";
foreach($results_array[0] as $key => $element) {
if($key == "id") {
$out .= "<th class=\"id-column\">";
$out .= strtoupper($key);
$out .= "</th>";
} else {
$out .= "<th>";
$out .= ucwords(str_replace("_", " ", $key));
$out .= "</th>";
}
}
$out .= "</thead>";
$out .= "<tbody>";
$i = 0;
foreach($results_array as $key => $element){
if($i % 2 === 0) $extraclass= "alternate";
$out .= "<tr class=\"$extraclass\">";
$i++;
$extraclass="";
foreach($element as $subkey => $subelement){
$out .= "<td>$subelement</td>";
}
$out .= "<td>EDIT</td>";
$out .= "</tr>";
}
$out .= "</tbody>";
$out .= "</table>";
return $out;
}
A general pattern for this type of page is Post-Redirect-Get. You could, for instance, pull the if(isset($_POST['submit'])) block out into a separate file called processForm.php. The form's action parameter is changed to processForm.php. The form sends $_POST data to processForm which inserts the new database records, and processForm in turn redirects the user back to the original page which gets the results.
If you want a one-page solution using the above code, add this code at the very top of the file, before you output anything at all. This starts the output buffer, which is usually necessary if you want to use the header() command to redirect.
ob_start();
Then edit the if(isset) block:
if(isset($_POST['submit'])){
if(has_presence($_POST['product_name'])){
insert_row_into_table('CAL_products');
show_errors();
if(has_presence($wpdb->last_query)) {
echo "Update Successful";
header("Location: index.php"); //change index.php to the current page
//header("Location: ".$from); //or use a variable
} else {
echo "Update Failed";
}
} else {
echo "The field 'Product Name' cannot be blank.";
}
}
Finally, add this at the very end of the script to close the output buffer:
ob_end_flush();
Essentially, this code refreshes the page on success after the new entries are inserted into the database. This should allow your table to include the new records.

Geolocation script issues

I've some issues with a geolocation script I'm working on and maybe someone could help me here :).
For this script I have 4 files :
functions.js:
function geolocation(){
GMaps.geolocate({
success: function(position) {
var userLat = position.coords.latitude;
var userLng = position.coords.longitude;
var dataString = 'userLat='+userLat+'&userLng='+userLng;
$.ajax({
type : 'POST',
url : 'getEvents.php',
data : dataString,
dataType : 'text',
success : function(msg){
console.log(msg);
}
});
},
error: function(error) {
alert('Echec de la localisation...');
},
not_supported: function() {
alert('Votre navigateur ne supporte pas la géolocalisation...');
}
});
}
index.php:
<?php require 'php/getEvents.php'; ?>
<!DOCTYPE html>
<html lang="fr">
<?php include('inc/head.html'); ?>
<body>
<div class="mosaic">
<?php echo visitorMosaicBox($data); ?>
</div>
<script type="text/javascript">
$(document).ready(function(){
geolocation();
});
</script>
</body>
</html>
getEvents.php:
<?php
session_start();
require 'db-connect.php';
require 'lib.php';
$userLat = $_POST['userLat'];
$userLng = $_POST['userLng'];
$area = 10;
$i = 0;
$data = array();
if($userLat != '' && $userLng != ''){
if(isset($_SESSION['id'])){
echo 'Logged';
}else{
try{
$sql = "SELECT restaurants.cover, restaurants.name, restaurants.address, restaurants.location, restaurants.zip, events.title, events.trailer, events.id
FROM events
LEFT JOIN restaurants ON restaurants.id = events.fk_restaurants";
$req = $db->query($sql);
}catch(PDOException $e){
echo 'Erreur: '.$e->getMessage();
}
while($res = $req->fetch()){
$fetchAddress = $res['address'].', '.$res['zip'].' '.$res['location'];
$fixedAddress = str_replace(' ','+',$fetchAddress);
$geocode = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$fixedAddress.'&sensor=false');
$output = json_decode($geocode);
$lat = $output->results[0]->geometry->location->lat;
$lng = $output->results[0]->geometry->location->lng;
$distance = distance($userLat, $userLng, $lat, $lng, false);
if($distance <= $area){
$data[$i] = array(
"id" => $res['id'],
"name" => $res['name'],
"cover" => $res['cover'],
"address" => $fetchAddress,
"title" => $res['title'] ,
"trailer" => $res['trailer'],
);
$i++;
}
}
}
}else{
$data = 'ERROR';
}
?>
lib.php :
<?php
function visitorMosaicBox($array){
for($i=0; $i<sizeOf($array);$i++){
$html = '<div class="box" id="box-'.$i.'">';
$html .= '<img src="'.$array[$i]['cover'].'" alt="'.$array[$i]['name'].'" />';
$html .= '<span class="ribbon"></span>';
$html .= '<div class="back"></div>';
$html .= '<div class="infos" id="event-'.$array[$i]['id'].'">';
$html .= '<p class="msg"></p>';
$html .= '<div class="txt-1">';
$html .= '<span class="sits"><span class="dinners">5</span></span>';
$html .= '<h3>'.$array[$i]['title'].'<span class="block">'.$array[$i]['name'].'</span></h3>';
$html .= '<ul class="actions">';
$html .= '<li>Partager</li>';
$html .= '<li>Participer</li>';
$html .= '<li class="last">Info</li>';
$html .= '</ul>';
$html .= '</div>'; // Fin de .txt-1
$html .= '<div class="txt-2">';
$html .= '<h3>'.$array[$i]['title'].'</h3>';
$html .= '<p>'.$array[$i]['trailer'].'</p>';
$html .= 'Fermer';
$html .= '</div>'; // Fin de .txt-2
$html .= '</div>'; // Fin de .infos
$html .= '</div>'; // Fin de .box
return $html;
}
}
?>
So now what's that's supposed to do...
1/ functions.js geolocates the visitor, gets his coordonates (lat,lng) and send them to my getEvents.php
2/ getEvents.php receives the coordonates from functions.js, and compare them with the results from the database.
3/ If the distance between the result and the user is lower than the area (10) then I store all the datas from the result in my array $data.
4/ The function visitorMosaicBox() creates as many divs as there are results in my array.
5/ In index.php, I simply call visitorMosaicBox() by passing my array $data.
My problem is that no divs are created even if there are results. I receive the visitor's coordonates in my getEvents.php file but in my index.php file the coordonates doesn't exists.
Does anyone know why my coordonates can't pass from my getEvents.php file to my index.php file please ? Any solution ?
If I split my script in these 4 files it's because I'll need to do other stuffs on my getEvents.php file depending on the visitor is connected or not, etc...
Thanks and sorry for this long question.
Antho

Categories