Syntax error in other file when adding a foreach - php

Here's the error i'm getting :
syntax error, unexpected end of file, expecting function (T_FUNCTION)' in D:\User\Documents...\Controllers\DeviceController.php:68
It happens in this code :
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Data\Campaign;
use App\Data\Device;
use App\Helpers\Database;
use App\Helpers\DateHelpers;
use App\Helpers\ProfileHelpers;
use App\Helpers\Utils;
use Illuminate\Http\Request;
class DeviceController extends ApiController
{
public function show($deviceId)
{
return Device::find($deviceId);
}
public function update(Request $request, $deviceId)
{
$isAlertActive = filter_var($request->input('isAlertActive'), FILTER_VALIDATE_BOOLEAN);
$isAlertAfter5Pushes = filter_var($request->input('isAlertAfter5Pushes'), FILTER_VALIDATE_BOOLEAN);
$isAlertAfter10Pushes = filter_var($request->input('isAlertAfter10Pushes'), FILTER_VALIDATE_BOOLEAN);
$hasAtLeastOneSettingActive = $isAlertActive || $isAlertAfter5Pushes || $isAlertAfter10Pushes;
$settings = [
'is_alert' => $isAlertActive,
'is_alert_after_5_pushes' => $isAlertAfter5Pushes,
'is_alert_after_10_pushes' => $isAlertAfter10Pushes
];
if ($isAlertActive) {
$settings['alert_seuil'] = intval($request->input('alertThreshold'));
$settings['alert_votemini'] = intval($request->input('minVoteCountBeforeAlert'));
}
if ($hasAtLeastOneSettingActive)
$settings['next_alert_in_hours'] = intval($request->input('nextAlertInHours'));
Device::where('id_device', $deviceId)
->update($settings);
}
/////////////////////////////////////////////////////////////////////////////
public function putInLocation($sectionId, $locationName)
{
$section = Section::find($sectionId);
if ($section && $section->area->id_client == $this->clientId) {
Location::createLocation($sectionId, $locationName);
return self::jsonSuccess();
}
else
return self::jsonBadRequest();
}
public function delete($locationId)
{
$location = Location::find($locationId);
if ($location && $location->section->area->id_client == $this->clientId) {
$location->delete();
return self::jsonSuccess();
}
else
return self::jsonBadRequest();
}
}
?>
I don't see any syntax error there, i checked the brackets multiple times but maybe i missed something ?
What's weird for me is that there is no syntax error until i add a foreach in another file (D:\User\Documents...\Views\Partials\areasettings.php). Here's the foreach :
<div class="col-lg-3 col-lg-offset-0 v">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-barcode"></span></span>
<select class="form-control" id="deviceSelect">
<option selected disabled> <?php echo trans('areasettings.add_id_placeholder') ?> </option>
<option> TEST </option>
<?php
$devices = $db->fetchAll("select `id_device_mac` from `dashboard_demo.nao_device`");
foreach ($devices as $device) {
$idDevice = $device->id_device;
$idDeviceMac = $device->id_device_mac;
//echo "<option value=\"$idDevice\">$idDeviceMac</option>\n";
<option value="<?= $device['id_device_mac'] ?>"><?= $device['id_device_mac'] ?></option>
}
?>
</select>
<!--<input type="text" class="form-control" placeholder="<?php echo trans('areasettings.add_id_placeholder') ?>" autocomplete="off"
ng-model="newSectionName">-->
</div>
</div>
Thanks in advance for helping me !
EDIT : Changed the fetchAll with this line (laravel way) :
$devices = DB::table('dashboard_demo.nao_device')->select('id_device_mac')->get()
But i still get the same error.
I searched deeper in my logs and also found that devices is undefined apparently.

This line looks wrong, if you are using vanilla PDO.
$devices = $db->fetchAll("select `id_device_mac` from `dashboard_demo.nao_device`");
PDO::fetchAll does not execute a query, it just processes the resultset of an already executed query.
So something like this perhaps
$sql = 'select `id_device_mac` from `dashboard_demo.nao_device`';
$result = $db->query($sql);
if ( ! $result ) {
print_r($db->errorInfo())
exit;
}
while ($device = $result->fetch(PDO::FETCH_OBJ)) {
$idDevice = $device->id_device;
$idDeviceMac = $device->id_device_mac;
echo "<option value='$idDevice'>$idDeviceMac</option>\n";
}
This way should show you if any errors happened in the query.
Also changed the content of the while loop. You were using an array notation in there but an objct notation when getting data from the $device variable above?

Related

Illegal string offset 'name' CodeIgniter 4

I'm a new user of CodeIgniter 4. I got this error when I want to show 'prodi_name' of table 'prodi' on a form.
This is my ProdiModel
protected $table = 'prodi';
protected $primaryKey = 'id_prodi';
public function getProdi($id = false)
{
if ($id == false) {
return $this->findAll();
}
return $this->where('prodi_code', $id)->first();
}
I have setting my BaseController with
$this->prodiModel = new \App\Models\ProdiModel();
so my Controller is
public function add()
{
$data = [
'title' => 'Admin',
'prodi' => $this->prodiModel->getProdi(),
'validation' => \Config\Services::validation()
];
return view('admin/add', $data);
}
And this is my form, I want to show the prodi_name on a multiple select field
<div class="form-group">
<label>Prodi</label>
<select class="form-control select2 multiple" id="prodi" name="prodi[]" multiple="multiple" data-placeholder="Select prodi">
<?php
foreach ($prodi as $prodi) :
echo "<option value='" . $prodi["prodi_name"] . "'";
if (old('prodi')) {
if (in_array($prodi['prodi_name'], old('prodi'))) echo "selected";
}
echo ">" . $prodi['prodi_name'] . "</option>";
endforeach; ?>
</select>
</div>
Please help me to solve this problem. Thanks
first of all in CI 4 there is no first() method,
use
public function getProdi($id = false)
{
if ($id == false) {
return $this->findAll();
}
return $this->where('prodi_code', $id)->getFirstRow(‘array’);
}
On the second thought you are returning two types of data here, if id is false you return multidimensional array and if id is there code returns single row.
Again in the same method, you have called findAll(), if it returns and associative array, your code should run, but if that returns a object then you should change to,
<?php
foreach ($prodi as $prodi) :
echo "<option value='" . $prodi->prodi_name . "'";
if (old('prodi')) {
if (in_array($prodi->prodi_name, old('prodi'))) echo "selected";
}
echo ">" . $prodi->prodi_name . "</option>";
endforeach; ?>

How to calculate with html form select and option in php

A form that takes a lot of information from the user and processes it, and finally a number is displayed.
A number of objects are obtained according to other objects.
index.php
<form action="calc.php" method="POST">
<select name="NumberOfPeople2">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select name="NumberOfBathTimes">
<option value="1">one</option>
<option value="2">two</option>
</select>
<select name="DurationOfBathing">
<option value="10">10 min</option>
<option value="20">20 min</option>
</select>
<input type="submit" value="submit">
</form>
calc.php
<?php
include 'include/calc.inc.php';
$NumberOfPeople = $_POST['NumberOfPeople'];
$NumberOfBathTimes = $_POST['NumberOfBathTimes'];
if($_POST['DurationOfBathing']=='10')
{
$DurationOfBathing='60';
}
if($_POST['DurationOfBathing']=='20')
{
$DurationOfBathing='100';
}
if($_POST['NumberOfBathTimes']=='1')
{
$FactorUseBath='0.14285714';
$FactorNumberBath='1.2';
}
if($_POST['NumberOfBathTimes']=='2')
{
$FactorUseBath='0.28571429';
$FactorNumberBath='1.2';
}
$ConsumptionBath = new Calc($NumberOfPeople,$DurationOfBathing,$FactorUseBath,$FactorNumberBath);
echo $ConsumptionBath->calcMethod();
calc.inc.php
<?php
class Calc{
public $NumberOfPeople;
public $DurationOfBathing;
public $FactorUseBath;
public $FactorNumberBath;
public function __construct($NumberOfPeople,$DurationOfBathing,$FactorUseBath,$FactorNumberBath){
$this->NumberOfPeople = $NumberOfPeople;
$this->DurationOfBathing; = $DurationOfBathing;
$this->FactorUseBath; = $FactorUseBath;
$this->FactorNumberBath; = $FactorNumberBath;
}
public function calcMethod(){
$result = $this->DurationOfBathing*$this->FactorUseBath;*$this->FactorNumberBath*$this->NumberOfPeople;
return $result;
}
}
All objects obtained must be multiplied.
The answer is $ConsumptionBath
Is this the right way?
This is right way, but you should declare each and every variable somewhere which is used in script. For example, in your given script, variable $DurationOfBathing is initialised only in if conditions and will give undefined variable error in case if conditions fails. So I've updated code below:
include 'include/calc.inc.php';
$NumberOfPeople = $_POST['NumberOfPeople'];
$NumberOfBathTimes = $_POST['NumberOfBathTimes'];
$DurationOfBathing = $FactorUseBath = $FactorNumberBath = '';
if ($_POST['DurationOfBathing'] == '10') {
$DurationOfBathing = '60';
} else if ($_POST['DurationOfBathing'] == '20') {
$DurationOfBathing = '100';
}
if ($_POST['NumberOfBathTimes'] == '1') {
$FactorUseBath = '0.14285714';
$FactorNumberBath = '1.2';
} else if ($_POST['NumberOfBathTimes'] == '2') {
$FactorUseBath = '0.28571429';
$FactorNumberBath = '1.2';
}
$ConsumptionBath = new Calc($NumberOfPeople, $DurationOfBathing, $FactorUseBath, $FactorNumberBath);
echo $ConsumptionBath->calcMethod();
Update
There is some problem in class as well. Some extra semi colons ; are added there. Use this updated code:
<?php
class Calc {
public $NumberOfPeople;
public $DurationOfBathing;
public $FactorUseBath;
public $FactorNumberBath;
public function __construct($NumberOfPeople, $DurationOfBathing, $FactorUseBath, $FactorNumberBath) {
$this->NumberOfPeople = $NumberOfPeople;
$this->DurationOfBathing = $DurationOfBathing;
$this->FactorUseBath = $FactorUseBath;
$this->FactorNumberBath = $FactorNumberBath;
}
public function calcMethod() {
$result = $this->DurationOfBathing * $this->FactorUseBath * $this->FactorNumberBath * $this->NumberOfPeople;
return $result;
}
}

How to load data to an already loaded view?

I have a little project, where i use codeigniter, jquery and bootstrap.
I have "Startsite" where the user have to say:
Option 1: Edit project
Option 2: Create project
I think it is useful to show my Controller as first:
In the construct method i load all models, in the index i load data to all dropdowns in my "startsite", in saveProject i save my created project and the method i have a issue is editProject. Look here:
class projekt extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper('html');
$this->load->helper('url');
$this->load->helper('form');
$this->load->model('projektklassen_model');
$this->load->model('kundengruppen_model');
$this->load->model('produktgruppen_model');
$this->load->model('ablehnungsgrund_model');
$this->load->model('absatzregion_model');
$this->load->model('anfragetyp_model');
$this->load->model('businessunit_model');
$this->load->model('endkundeOEM_model');
$this->load->model('lieferanten_model');
$this->load->model('prozentverteilungEOP_model');
$this->load->model('prozentverteilungSOP_model');
$this->load->model('realisierungsstatus_model');
$this->load->model('gsmbereich_model');
$this->load->model('firma_model');
$this->load->model('projekt_model');
}
public function index()
{
$data['projektklassen'] = $this->projektklassen_model->getProjektklassen();
$data['kundengruppen'] = $this->kundengruppen_model->getKundengruppen();
$data['produktgruppen'] = $this->produktgruppen_model->getProduktgruppen();
$data['ablehnungsgruende'] = $this->ablehnungsgrund_model->getAblehnungsgruende();
$data['absatzregionen'] = $this->absatzregion_model->getAbsatzregionen();
$data['anfragetypen'] = $this->anfragetyp_model->getAnfragetypen();
$data['businessunits'] = $this->businessunit_model->getBusinessunits();
$data['endkundenOEM'] = $this->endkundeOEM_model->getEndkundenOEM();
$data['lieferanten'] = $this->lieferanten_model->getLieferanten();
$data['prozentverteilungenEOP'] = $this->prozentverteilungEOP_model->getProzentverteilungenEOP();
$data['prozentverteilungenSOP'] = $this->prozentverteilungSOP_model->getProzentverteilungenSOP();
$data['realisierungsstati'] = $this->realisierungsstatus_model->getRealisierungsstatus();
$data['gsmbereiche'] = $this->gsmbereich_model->getGSMBereiche();
$data['firmen'] = $this->firma_model->getFirmen();
$data['projekte'] = $this->projekt_model->getProjekte();
$data['preFormVisible'] = true;
$this->load->view('project2', $data);
}
function saveProjekt(){
if($this->input->post('btGenerate')){
$pdm = $this->projekt_model->getPDM();
$this->projekt_model->addprojekt($pdm);
}
redirect('projekt');
}
function editProjekt(){
if($this->input->post('btladeProjekt')){
$data['proDetails'] = $this->projekt_model->editprojekt();
$data['preFormVisible'] = false;
$this->load->view('project2', $data);
}
redirect('projekt');
} }
What should happend?
The user choose on the "startsite" to edit an project. He select a project in a dropdown and click an button.
Here the form from the startsite:
<?php echo form_open('projekt/editProjekt', array('name' => 'preform')); ?>
<div class="col-sm-6 col-md-6 col-lg-6">
<label for='projekt'>Projekt</label>
<?php echo form_dropdown('projekt', $projekte, '', 'class="form-control" id="projekt"'); ?>
</div>
<div class="col-sm-6 col-md-4 col-lg-3">
<button type="submit" id="btladeProjekt" name="btladeProjekt" value="btladeProjekt" class="btn btn-primary headbutton"><i class="glyphicon glyphicon-pencil"></i> Projekt bearbeiten </button>
</div>
<?php echo form_close(); ?>
Now the controller method editProject calls a method in the model. I show you:
function editprojekt() {
$serverName = "de-sal-v-sql011";
$connectionInfo = array( "Database"=>"NB_Roll_Plan", "UID"=>"s-global_it-bit002", "PWD"=>"\$Ev1danzA\$");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$projektID = $this->input->post('projekt');
$data = array();
$tsql = "SELECT ProjektID, Projektname, KDGR, Kundenname, ProduktgruppeID, Projektklasse, MABVertrieb, GSMBereich, Ansprechpartner_kunde,ProjektanfrageNR_kunde,
Anfragedatum, Abgabedatum_angebot, PDM, übergeordnetePDM, Kommentar, Projektrisiken from Projekt WHERE ProjektID = ? ORDER BY Projektname ASC";
$var = array($projektID);
$query = sqlsrv_query($conn, $tsql, $var);
if($query != false){
while( $row = sqlsrv_fetch_array( $query, SQLSRV_FETCH_ASSOC) ) {
$data['ProjektID'] = $row['ProjektID'];
$data['Projektname'] = $row['Projektname'];
$data['KDGR'] = $row['KDGR'];
$data['Kundenname'] = $row['Kundenname'];
$data['ProduktgruppeID'] = $row['ProduktgruppeID'];
$data['Projektklasse'] = $row['Projektklasse'];
$data['MABVertrieb'] = $row['MABVertrieb'];
$data['GSMBereich'] = $row['GSMBereich'];
$data['Ansprechpartner_kunde'] = $row['Ansprechpartner_kunde'];
$data['ProjektanfrageNR_kunde'] = $row['ProjektanfrageNR_kunde'];
$data['Anfragedatum'] = $row['Anfragedatum'];
$data['Abgabedatum_angebot'] = $row['Abgabedatum_angebot'];
$data['PDM'] = $row['PDM'];
$data['übergeordnetePDM'] = $row['übergeordnetePDM'];
$data['Kommentar'] = $row['Kommentar'];
$data['Projektrisiken'] = $row['Projektrisiken'];
}
sqlsrv_free_stmt($query);
}else{
die( print_r( sqlsrv_errors(), true));
}
return $data;
}
Now i want to display the returned data in the view, but when i try this nothing happens.
<?php
if(isset($proDetails)){
echo "test";
echo "<input type='text' class='form-control' id='proname' name='proname' value='".$proDetails->ProjektID."'/>";
}else{
echo "<input type='text' class='form-control' id='proname' name='proname'>";
}
?>
What did i miss? Thx in advance
Alright I think I have understand what is you required #JamesnxD. You can load the all the drop down in a view and the edit form in another view do like this
$this->load->view('front/dropdown');
$this->load->view('front/editform',$data);
$this->load->view('front/front_footer');
some change your model function and add a param.
function editprojekt($proID) {
$projektID = $proID
}
and change your index method
public function index($proID = '') {
if($proID) {
$data['proDetails'] = $this->projekt_model->editprojekt($proID);
} else {
$data['proDetails'] = false;
}
}
Finally when you edit content you call projekt/index/12 (12 = projektID) in browser url
you know that you can use array to load helper, model and library
$this->load->helper(array('html', 'url', 'form'));
$this->load->model(array('projektklassen_model', 'kundengruppen_model', 'produktgruppen_model', 'ablehnungsgrund_model','absatzregion_model','anfragetyp_model','businessunit_model','endkundeOEM_model','lieferanten_model','prozentverteilungEOP_model','prozentverteilungSOP_model','realisierungsstatus_model','gsmbereich_model','firma_model','projekt_model'));

Twitter Typeahead in CodeIgniter. Not passing array datum to hidden form field

I'm trying to use the typeahead.js Twitter Typeahead (not Bootstrap typeahead) to display names pulled from a mysql table using the CodeIgniter framework. The model also collects id values along with the name.
The controller and model seem to be presenting the correct array format.
Model
class People_model extends CI_Model{
function __construct() {
parent::__construct();
}
function get_person($name) {
$mode = $this->uri->segment(3);
$this->db->select("id, CONCAT(firstName,' ', lastName) AS name, type",FALSE);
$this->db->from('people');
if($mode == 'signin')
$this->db->where("status !=", "enter");
else
$this->db->where("status", "enter");
$this->db->like("concat(firstName,' ', lastName)", $name);
$this->db->order_by('name');
$query = $this->db->get();
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$new_row['value']=htmlentities(stripslashes($row['name']));
$new_row['id']=htmlentities(stripslashes($row['id']));
$row_set[] = $new_row; //build an array
}
}
echo json_encode($row_set); //format the array into json data
}
}
Controller (relevant functions)
function get_person() {
$this->config->set_item('disable_template', TRUE);
$this->load->model('People_model');
$name = $this->input->get_post();
$this->People_model->get_person($name);
}
function dosigninout() {
$mode = $this->uri->segment(3);
switch($mode) {
case 'signin':
$mode = 'enter';
break;
case 'signout':
$mode = 'exit';
break;
default:
$this->load->view("home/error", array('error' => "Invalid mode specified."));
}
$meeting = $this->_currentMeeting();
$person = $this->input->post('person_id');
if(!$this->_validPerson($person, $this->input->post('name'))) $this->load->view("home/error", array('error' => "You requested an operation with ".$this->input->post('name')." who has an ID of $person. The name and ID don't match."));
$this->db->insert("attendance", array('person_id' => $person, 'meeting_id' => $meeting['meetingID'], 'type' => $mode));
$this->db->where("id", $person);
$this->db->update("people", array('status' => $mode));
$redirectTo = (isset($_POST['redirect'])) ? $this->input->post('redirect') : false;
if($redirectTo) redirect($redirectTo);
else redirect('attendance');
}
Sample JSON data returned
[{"value":"Anna Woodhouse","id":"2"},{"value":"Elaine Woodhouse","id":"4"}]
View
$baseURL = base_url();
$extraHeadData = "";
?>
<h2><?=$title?></h2>
<p>Current meeting: <?=$meetingTitle?> on <?=$meetingDate?>.</p>
<?=form_open("attendance/dosigninout/$mode", array('id' => "signInOutForm"))?>
<fieldset>
<legend>Whom do you want to sign <?=($mode == "signin") ? 'in' : 'out'?>?</legend>
<div class="control-group">
<div class="controls">
<input type="hidden" name="person_id" id="person_id" value="" />
<input class="people-typeahead" type="text" id="typeahead" name="name" placeholder="person's full name"/>
</div>
</div>
</fieldset>
<div class="form-actions">
<?=form_submit('','Save changes','class="btn btn-primary"'); ?>
</div>
</form>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
<script src="<?php echo $baseURL?>assets/js/typeahead.min.js"></script>
<script>
$(function($) {
$('input.people-typeahead').typeahead({
name: 'people',
remote: 'http://localhost/badgeentry/index.php/attendance/get_person',
dataType: 'json'
});
$("#people-typeahead").on("typeahead:selected typeahead:autocompleted", function(e,datum) {
$(person_id).val() = datum.id
});
});
</script>
In the form field I get the correct drop down list, but when an item is selected any new database entry has an id of "0" instead of the selected name id. I'm almost certain that this is an issue with the javascript code in the view not being correct, but quite frankly, I have no js skills to sort it out!
I see an issue here :
$(person_id).val() = datum.id
You are using jQuery's .val() incorrectly and the use of the selector is wrong too. It should look like :
$("#person_id").val(datum.id);
jQuery .val() documentation
I finally figured out how to get this working. Part of the problem was that I could find no examples of using typeahead.js in CodeIgniter that showed how the various script, view, controller and model components interact. I tried switching to Twitter bootstrap typeahead. However, despite finding references to using it with an arrays rather than a string, I still could not get a working solution.
In the end I went back to Twitter typeahead and started from scratch. I found this tutorial helped enormously:
Twitter Bootstrap typeahead.js with underscore.js Templating – A Tutorial - Alan Greenblatt
I'm posting what worked for me in case it can help anyone else with similar issues. This version also includes setting the remote source as a variable which allowed me to define it through PHP so that I could select data in the model based on the URL.
Model
class People_model extends CI_Model{
function __construct() {
parent::__construct();
}
function get_person($name) {
$modeinout = $this->uri->segment(3);
$this->db->select("id, CONCAT(firstName,' ', lastName) AS name, type",FALSE);
$this->db->from('people');
if($modeinout == 'signin'){
$this->db->where('status !=', 'enter');
}
else {
$this->db->where('status', 'enter');
}
$this->db->like("concat(firstName,' ', lastName)", $name);
$this->db->order_by('name');
$query = $this->db->get();
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$new_row['name']=htmlentities(stripslashes($row['name']));
$new_row['id']=htmlentities(stripslashes($row['id']));
$row_set[] = $new_row; //build an array
}
}
echo json_encode($row_set); //format the array into json data
}
Controller (relevant functions)
function signin() {
$this->load->helper("form");
$this->template->javascript('assets/js/underscore-min.js');
$this->template->javascript('assets/js/typeahead.min.js');
$data = $this->_currentMeeting();
$data['title'] = "Sign Someone In";
$data['attributes_form'] = array('id' => 'signInOutForm','class' => 'form-horizontal validate', 'enctype' => 'multipart/form-data');
$data['mode'] = 'signin';
$this->load->view("home/attendance/signinout", $data);
}
function signout() {
$this->load->helper("form");
$this->template->javascript('assets/js/underscore-min.js');
$this->template->javascript('assets/js/typeahead.min.js');
$data = $this->_currentMeeting();
$data['attributes_form'] = array('id' => 'signInOutForm','class' => 'form-horizontal validate', 'enctype' => 'multipart/form-data');
$data['id'] = '';
$data['title'] = "Sign Someone Out";
$data['mode'] = 'signout';
$this->load->view("home/attendance/signinout", $data);
}
function get_people() {
$this->config->set_item('disable_template', TRUE);
$this->load->model('People_model');
$name = $this->input->post('query');
$this->People_model->get_person($name);
}
function dosigninout() {
$mode = $this->uri->segment(3);
switch($mode) {
case 'signin':
$mode = 'enter';
break;
case 'signout':
$mode = 'exit';
break;
default:
$this->load->view("home/error", array('error' => "Invalid mode specified."));
}
$meeting = $this->_currentMeeting();
$person = $this->input->post('person_id');
if(!$this->_validPerson($person, $this->input->post('person_name'))) $this->load->view("home/error", array('error' => "You requested an operation with ".$this->input->post('person_name')." who has an ID of $person. The name and ID don't match."));
$this->db->insert("attendance", array('person_id' => $person, 'meeting_id' => $meeting['meetingID'], 'type' => $mode));
$this->db->where("id", $person);
$this->db->update("people", array('status' => $mode));
$redirectTo = (isset($_POST['redirect'])) ? $this->input->post('redirect') : false;
if($redirectTo) redirect($redirectTo);
else redirect('attendance');
}
View
<?php
$baseURL = base_url();
$extraHeadData = "";
?>
<h2><?=$title?></h2>
<p>Current meeting: <?=$meetingTitle?> on <?=$meetingDate?>.</p>
<?=form_open("attendance/dosigninout/$mode", array('id' => "signInOutForm",'class' => "form-horizontal validate"))?>
<input type="hidden" name="person_id" id="person_id">
<?php echo validation_errors(); ?>
<fieldset>
<legend>Whom do you want to sign <?=($mode == "signin") ? 'in' : 'out'?>?</legend>
<div class="control-group">
<div class="controls">
<input type="text" placeholder="person's full name" name="person_name" id="person_name" class="person-typeahead">
</div>
</div>
</fieldset>
<div class="form-actions">
<?=form_submit('','Save changes','class="btn btn-primary"'); ?>
</div>
</form>
<script>
var person_url="<?php echo site_url('attendance/get_people')."/".$mode;?>";
$(function($) {
_.compile = function(templ) {
var compiled = this.template(templ);
compiled.render = function(ctx) {
return this(ctx);
}
return compiled;
}
$('.person-typeahead').typeahead({
template: '<p><strong><%= name %></strong>: <%= id %></p>',
name: 'people',
valueKey: 'name',
engine: _,
remote: (person_url),
dataType: 'json'
}).on('typeahead:selected typeahead:autocompleted', function(event, datum) {
$('#person_id').val(datum.id);
$('#person_name').val(datum.name);
});
});
</script>
<?=jquery_validate('attendance/signout');?>

last.fm api - random / shuffle foreach loop

I am currently working with the lat.fm api to develop an app.
I have a function which runs to pull in the weekly track listing from a last.fm group.
The aim is to pull in the album artwork and to make a "gridview" template.
The below code does this:
public function getWeeklyTrackChartGrid($methodVars) {
// Check for required variables
if ( !empty($methodVars['group']) ) {
$vars = array(
'method' => 'group.getweeklytrackchart',
'api_key' => $this->auth->apiKey
);
$vars = array_merge($vars, $methodVars);
if ( $call = $this->apiGetCall($vars) ) {
$i = 0;
//shuffle($call->weeklytrackchart->track);
$loopN = $call->weeklytrackchart->track;
foreach ($loopN as $track ) {
require 'config.php';
//if(++$i > $userLimit*2) break;
$albumArtS = $tracks['album']['image']['small'] = (string) $track->image[0];
$albumArtM = $tracks['album']['image']['small'] = (string) $track->image[1];
$albumArtL = $tracks['album']['image']['small'] = (string) $track->image[2];
$playCounts = $tracks[$i]['playcount'] = (string) $track->playcount;
?>
<?php if ($playCounts > 1) { ?>
<?php if ($albumArtL) { ?>
<img src="<?php echo $albumArtL; ?>" />
<?php } ?>
<?php } else { ?>
<?php if ($albumArtM) { ?>
<img src="<?php echo $albumArtM; ?>" />
<?php } ?>
<?php } ?>
<?php if ($albumArtwork == "yes") { ?>
<?php if ($albumArt) { ?>
<?php } }?>
<?php $i++;
}
return $tracks;
}
else {
return FALSE;
}
}
else {
// Give a 91 error if incorrect variables are used
$this->handleError(91, 'You must include a group variable in the call for this method');
return FALSE;
}
}
I would like to use the php function shuffle on the foreach loop to randomise the tracks, rather than pull them in, in the order last.fm gives them you.
As you can see i havent commented the shuffle function out above, as when i add this i get the following warning:
Warning: shuffle() expects parameter 1 to be array, object given in
Any ideas on what could be the problem?
Cheers,
Dan
$loopN = (array) $call->weeklytrackchart->track;
shuffle($loopN);

Categories