I'm trying to work with the form dropdown function for the codeigniter form helper.
echo form_dropdown('userCharacters', $userRoster, '', '', 'id="userCharacter"');
If you notice the $userRoster is the array I pass from the controller to the view.
Here's how it shows up when I do a print_r on the array.
Array
(
[0] => stdClass Object
(
[id] => 1
[rosterName] => Kid Wonder
)
[1] => stdClass Object
(
[id] => 3
[rosterName] => Oriel
)
)
However I am getting these errors and not sure why
A PHP Error was encountered
Severity: 4096
Message: Object of class stdClass could not be converted to string
Filename: helpers/form_helper.php
Line Number: 352
A PHP Error was encountered
Severity: 4096
Message: Object of class stdClass could not be converted to string
Filename: helpers/form_helper.php
Line Number: 352
EDIT :
Array
(
[0] => Array
(
[id] => 1
[rosterName] => Kid Wonder
)
[1] => Array
(
[id] => 3
[rosterName] => Oriel
)
)
EDIT 2 :
What's supposed to happen is after the user logs in it has the default character id and the role id of the user that is held in the userData array. It runs the library function getRosterList. Inside that function it checks to see if the user has a role id of 4(admin) or 5(superadmin) and if they are then what I want it to do is get ALL the roster members which would include their default character and have it as the selected option. If they are not one of those two roles then I just want it to get the roster members that they control and have the preselected option as the default character id. And if they only have one character then it displays a h1 tag instead of the dropdown.
Controller:
$this->data['userData'] = $this->users->getUserByUserID($this->session->userdata('userID'));
$this->data['userRoster'] = $this->kowauth->getRosterList($this->data['userData']->usersRolesID);
Library (kowauth)
* Get roster list
*
* #param integer
* #return object/NULL
*/
function getRosterList($usersRolesID)
{
// Check args
if(!is_numeric($usersRolesID)) { throw new Exception('Non-numeric $usersRolesID provided to getRosterList()'); }
if (($usersRolesID == 4) || ($usersRolesID == 5))
{
return $this->ci->users->getAllRoster();
}
else
{
return $this->ci->users->getRosterByUserID($this->ci->session->userdata('userID'));
}
}
Model:
/**
* Get roster list
*
* #return object/NULL
*/
function getAllRoster()
{
$this->db->select('id');
$this->db->select('rosterName');
$this->db->select('rosterStatusID');
$this->db->from('rosterList');
$this->db->order_by('rosterName');
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return $query->result();
}
return null;
}
/**
* Get list of roster by user ID
*
* #return object/NULL
*/
function getRosterByUserID($userID)
{
// Check args
if (!is_numeric($userID)) { throw new Exception('Non-numeric $userID provided to getRosterByUserID()'); }
$this->db->select('id');
$this->db->select('rosterName');
$this->db->from('rosterList');
$this->db->where('userID', $userID);
$this->db->order_by('rosterName');
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return $query->result_array();
}
return null;
}
View:
<?php
echo '<pre>';
print_r($userRoster);
echo '</pre>';
if (count($userRoster) == 1)
{
echo '<h1>'.$userRoster->rosterName.'</h1>';
}
else
{
$options = array (
$userRoster['id'] => $userRoster->rosterName
);
echo form_dropdown('userCharacters', $options, '', 'id="userCharacter"');
}
?>
Anybody have any ideas on this?
You're currently passing an array of objects. I believe that your $userRoster array should be formatted like this:
Array
(
1 => 'Kid Wonder'
3 => 'Oriel'
)
Also, I believe that form_dropdown only takes four parameters and you're trying to pass it five. You might want to move that last argument into the fourth spot:
echo form_dropdown('userCharacters', $userRoster, '', 'id="userCharacter"');
Should produce:
<select name="userCharacters" id="userCharacter">
<option value="1">Kid Wonder</option>
<option value="3">Oriel</option>
</select>
Which I think is what you're going for!
http://codeigniter.com/user_guide/helpers/form_helper.html
Related
I have a class with method add() that accepts strings and arrays. I need to have an array with all users, but I cannot seem to get it. All I get is multiple arrays with all users. How could I merge those arrays into one?
class Users {
function add($stringOrArray) {
$arr = array();
if(is_array($stringOrArray)) {
$arr = $stringOrArray;
} else if(is_string($stringOrArray)) {
$arr[] = $stringOrArray;
} else {
echo('errrrror');
}
print_r($arr);
}
When I use this test:
public function testOne() {
$users = new Users();
$users->add('Terrell Irving');
$users->add('Magdalen Sara Tanner');
$users->add('Chad Niles');
$users->add(['Mervin Spearing', 'Dean Willoughby', 'David Prescott']);
This is what I get, multiple arrays but I need one array.
Array
(
[0] => Terrell Irving
)
Array
(
[0] => Magdalen Sara Tanner
)
Array
(
[0] => Chad Niles
)
Array
(
[0] => Mervin Spearing
[1] => Dean Willoughby
[2] => David Prescott
)
You can cut a lot of unnecessary bloat from your method.
You can cast ALL incoming data to array type explicitly. This will convert a string into an array containing a single element. If the variable is already an array, nothing will change about the value.
Use the spread operator (...) to perform a variadic push into the class property.
Code: (Demo)
class Users
{
public $listOfUsers = [];
function add($stringOrArray): void
{
array_push($this->listOfUsers, ...(array)$stringOrArray);
}
}
$users = new Users;
$users->add('Terrell Irving');
$users->add(['Magdalen Sara Tanner', 'Chad Niles']);
$users->add(['Mervin Spearing']);
var_export($users->listOfUsers);
Output:
array (
0 => 'Terrell Irving',
1 => 'Magdalen Sara Tanner',
2 => 'Chad Niles',
3 => 'Mervin Spearing',
)
All you need is to store the added users in a class property, for example $listOfUsers.
If adding the array you use the array_merge() function otherwise just add new user at the end of indexed array.
<?php
class Users {
// here will be all the users stored
public $listOfUsers = array();
function add($stringOrArray) {
//$arr = array();
if(is_array($stringOrArray)) {
// merge two arrays - could create duplicate records
$this->listOfUsers = array_merge($this->listOfUsers, $stringOrArray);
} else if(is_string($stringOrArray)) {
// simply add new item into the array
$this->listOfUsers[] = $stringOrArray;
} else {
echo('errrrror');
}
print_r($this->listOfUsers);
}
}
In your example you are storing the data locally within the method add() and it is not kept for future usage. This behavior is corrected using the class property $listOfUsers that can be accesed using $this->listOfUsers within the class object and if needed outside of the class.
So I have a large database (120k rows) and I'm building a little web app to make it useful for the community (astronomy based stuff). I'm new to php and am looking for a little help.
I have a search.php file and a class-search.php file and at the moment the results look like this:
2 results found
Array
(
[count] => 2
[results] => Array
(
[0] => stdClass Object
(
[disc] => LOC 7
[fstdate] => 2016
[lstdate] => 2016
[lstpa] => 170
[lstsep] => 0.4
[stype] =>
[comp] => AB
[fstmag] => 13.80
[secmag] => 14.10
[dnum] =>
[rahour] => 05
[ramin] => 38
[rasec] => 48.04
[decdeg] => -02
[decmin] => 27
[decsec] => 14.2
)
[1] => stdClass Object
(
[disc] => LOC 7
[fstdate] => 2016
[lstdate] => 2016
[lstpa] => 284
[lstsep] => 7.5
[stype] =>
[comp] => AB,C
[fstmag] => 13.20
[secmag] => 16.60
[dnum] =>
[rahour] => 05
[ramin] => 38
[rasec] => 48.04
[decdeg] => -02
[decmin] => 27
[decsec] => 14.2
)
)
)
I'm looking to tabulate the results and I have got a rough idea what I'm doing but I'm not quite getting everything joined up - can anyone suggest anything please.
The key part of search.php looks like this: (Code may not be fully accurate as I've taken out some switches and ifs to reduce post length)
<?php
//Check if search data was submitted
if ( isset( $_GET['s'] ) ) {
// Include the search class
require_once( dirname( __FILE__ ) . '/class-search.php' );
// Instantiate a new instance of the search class
$search = new search();
// Store search term into a variable
$search_term = htmlspecialchars($_GET['s'], ENT_QUOTES);
// Send the search term to our search class and store the result
$search_results = $search->search($search_term);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>WDSC search</title>
</head>
<body>
<h1>Search the WDSC</h1>
<div class="search-form">
<form action="" method="get">
<div class="form-field">
<label for="search-field">Search term</label>
<input type="search" name="s" placeholder="Enter your search term..." results="5" value="<?php echo $search_term; ?>">
<input type="submit" value="Search">
........
</form>
</div>
<?php if ( $search_results ) : ?>
<div class="results-count">
<p><?php echo $search_results['count']; ?> results found</p>
</div>
<div class="results-table">
<?php foreach ( $search_results['results'] as $search_result ) : ?>
<div class="result">
<p><?php echo $search_result->title; ?></p>
</div>
<?php endforeach; ?>
</div>
<div class="search-raw">
<pre><?php print_r($search_results); ?></pre>
</div>
<?php endif; ?>
</body>
</html>
and the key parts of class-search.php looks like this:
<?php
/**
* Performs a search
*
* This class is used to perform search functions in a MySQL database
*
*/
class search {
/**
* MySQLi connection
* #access private
* #var object
*/
private $mysqli;
/**
* Constructor
*
* This sets up the class
*/
public function __construct() {
// Connect to our database and store in $mysqli property
$this->connect();
}
/**
* Database connection
*
* This connects to our database
*/
private function connect() {
$this->mysqli = new mysqli( 'server', 'user', 'pass', 'db' );
}
/**
* Search routine
*
* Performs a search
*
* #param string $search_term The search term
*
* #return array/boolen $search_results Array of search results or false
*/
public function search($search_term) {
// Sanitize the search term to prevent injection attacks
$sanitized = $this->mysqli->real_escape_string($search_term);
// Define variable for search category from list selection
$cat = $_GET['category'];
// Run the query.
// Query for discoverer
$query = $this->mysqli->query("
SELECT disc, fstdate, lstdate, lstpa, lstsep, stype, comp, fstmag, secmag, dnum, rahour, ramin, rasec, decdeg, decmin, decsec
FROM WDS_CAT
WHERE $cat LIKE '{$sanitized}%'
");
}
// Check results
if ( ! $query->num_rows ) {
return false;
}
// Loop and fetch objects
while( $row = $query->fetch_object() ) {
$rows[] = $row;
}
// Build our return result
$search_results = array(
'count' => $query->num_rows,
'results' => $rows,
);
return $search_results;
}
}
endif;
?>
I've tried to link a table to the variable $search_results by means of
echo '<table border=1px>'; // opening table tag
echo'<th>Discoverer</th><th>First year observed</th><th>Last year observed</th><th>Last position angle</th><th>Last separation</th><th>Spectral type</th><th>Components</th><th>Primary Magnitude</th><th>Secondary magnitude</th><th>Durchmusterung number</th><th>Right ascension</th><th></th><th></th><th>Declination</th><th></th><th></th>'; //table headers
while($data = mysql_fetch_array($search_results))
{
// we are running a while loop to print all the rows in a table
echo'<tr>'; // printing table row
echo '<td>'.$data['disc'].'</td><td>'.$data['fstdate'].'</td><td>'.$data['lstdate'].'</td><td>'.$data['lstpa'].'</td><td>'.$data['lstsep'].'</td><td>'.$data['stype'].'</td><td>'.$data['comp'].'</td><td>'.$data['fstmag'].'</td><td>'.$data['secmag'].'</td><td>'.$data['dnum'].'</td><td>'.$data['ragiyr'].'</td><td>'.$data['ramin'].'</td><td>'.$data['rasec'].'</td><td>'.$data['decdeg'].'</td><td>'.$data['decmin'].'</td><td>'.$data['decsec'].'</td>'; // we are looping all data to be printed till last row in the table
echo'</tr>'; // closing table row
}
echo '</table>'; //closing table tag
?>
<?php endif; ?>
But no joy - can anyone suggest something please.
Thanks in advance
Assuming you're just trying to output the results in a HTML table...?
UPDATE:
foreach($search_results['results'] as $resultRow) {
var_dump($resultRow);
}
This should do the trick. You're returning the resultset already processed into your array so you just need to loop on that array and not call mysql_fetch_array() again
I would firstly add
var_dump($data);
exit();
right after
while($data = mysql_fetch_array($search_results))
{
to loop only once and see what each loop returns. It's probably only returning [count] and [results] arrays so you might need to loop again on [results] array. Review the PHP reference for mysql_fetch_array http://php.net/manual/en/function.mysql-fetch-array.php
e.g.
while($data = mysql_fetch_array($search_results))
{
if(is_array($data['results'])){
foreach($data['results'] as $resultRow) {
var_dump($resultRow);
}
}
Within the foreach loop you can add your HTML output as you have above
NOTE: All this is based on the assumption that mysql_fetch_array() returns the the data structure as per your first code snippet.
2 results found
Array
(
[count] => 2
[results] => Array
(
[0] => stdClass Object
(
Fixed!!
I eventually turned on my brain and worked out that the return from the dump was an object not an array, so I cast it to an array using $resultsArray = (array)$resultRow; and ran that into the table.
It's dirty, but this is now doing what I want. Thanks #JI-Web, I couldn't have done it without your help. I think I'm getting the hang of PHP now.
Onto pagination and pulling relevant data from 3rd party sources into a frame based on the results. I may be back for more help!
Since moving session handling over to the database, the $_SESSION array doesn't seem to hold any values which I think is how sessions behave in PHP once the implementation is moved to DB.
This is causing quite a headache for me now. I'm not able to access the username of the user logged in via the details stored in the DB.
Here's my implementation of a function to retrieve the details of a user from the DB.
public function getUser($id, $db) {
$dbobj->query("SELECT * FROM SESSION WHERE id = $id);
$result = $dbobj->res();
return $result['data']['use'];
}
$result holds the values int he following format
array(1) (
[0 => array(3) (
[id => (string) 3fgg67bbsd77bVVgh
[access => (string) 14567893546
[data => (string) luser|s:5"Marke";
)
)
I would like $temp to hold the value "Marke". How should I parse the resultest returned?
I'd appreciate any help please.
resultset() function might be not exist.
So you can use this code:
public function getSessionUserName($id, $dbobj) {
$lcid = $id;
$dbobj->query("SELECT * FROM SESSION WHERE id = :sessid");
$dbobj->bind(':sessid', $lcid);
// execute query
$dbobj->execute();
// Commented this line
//$result = $dbobj->resultset();
// Use fetch() method
$result = $dbobj->fetch();
if ($result) {
//$temp= $result['data']['luser'];
$temp= $result['luser']
return $temp;
}
}
$result will generate following type of output (Output will be based on fields ):
Array
(
[id] => 3fgg67bbsd77bVVgh
[0] => 3fgg67bbsd77bVVgh
[access] => 14567893546
[1] => 14567893546
[luser] => Marke
[2] => Marke
)
I am having a weird problem in my codeigniter view. In my webapp using codeigniter I'm sending an array of rows returned from codeigniter model to controller and from there to the view. My problem is that, when I print the array in view I get a 1 at the end of the array. It looks like as shown:
Array ( [0] => stdClass Object ( [id] => 12 [item_code] => code1 [item_name] => part [brand] => qwerty [quantity] => 3 [retail_price] => 123 [cost] => 145 [alert_quantity] => 10) ) 1
Even when I didn't return the row from model, Still I get this 1, when I take the count of array. I didn't understand whats wrong. I'm stuck here for last 2 days.
Here is my code:
Model: product_model.php
public function alertproducts()
{
$myQuery = "select * FROM tab_products";
$q = $this->db->query($myQuery);
if( $q->num_rows() > 0 )
{
foreach (($q->result()) as $row)
{
$qty=$row->quantity;
$alertqty=$row->alert_quantity;
if($qty<=$alertqty)
{
$id[]=$row;
}
}
if(!empty($id))
{
return $id;
}
}
return FALSE;
}
Controller:product.php
public function alertproduct()
{
$data['alertproduct']= $this->product_model->alertproducts();
$this->load->view('commons/header');
$this->load->view('productalerts',$data);
$this->load->view('commons/footer');
}
Can anybody help me with this to find where am going wrong. Thanks in advance.
That 1 at the end means that you most likely echoed your print_r. Try using var_dump instead.. also change your SQL query to this: SELECT * FROM tab_products WHERE quantity <= alert_quantity or even better use Codeigniter's active record/query builder, its way cleaner like so:
public function alertproducts() {
$this->db->select();
$this->db->from("tab_products");
$this->db->where("quantity <= alert_quantity");
$q = $this->db->get();
if ($q->num_rows() > 0) {
return $q->result_array();
}else{
return false;
}
}
i am trying to call m custom function repeatedly with same or different parameters value,inside foreach loop parameters depending upon value to key provided my foreach.
foreach ($result as $r) {
if($r->marks1==null || $r->marks2==null)
{
echo $r->p_code;
$toUpdate=$this->getResult($username,$r->p_code);
print_r($toUpdate);
}
}
but when i am printing the latest query result i am getting $toUpdate get appended by latest parameter query.
Array
(
[query] => select * from `result` where (`studentid` = ?) and `studentid` = ? and `ccode` = ? and `a_no` = ? order by `date` desc limit 1
[bindings] => Array
(
[0] => XYZ
[1] => XYZ
[2] => course123code
[3] => 12321
)
[time] => 0.18
)
my user name getting same, while course code is get overrides while finding second result.
i want to get the result getResult() inside foreach loop so that it may give the related result for different parameters value.
public function getLatestResult($username,$course_code)
{
$user=new User;
$currentDetailOfUser=$this->userCurrentDetail($username);
$userdetail=json_decode($currentDetailOfUser,true);
$username =$userdetail['username'];
$studentid =$userdetail['userid'];
$studentBatch =$userdetail['batch'];
$programCode =$userdetail['programCode'];
$activeSemester =$userdetail['activesemester'];
$condition_key=array(
'studentid' =>$studentid
);
$getCurrentResult1 =$user->getDetail('student_result',$condition_key);
$getCurrentResult2 =$user->getDetail('student_result',$condition_key);
$resultAssessment1=$getCurrentResult1->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',1)->orderBy('date','Desc')->limit(1)->get();
$resultAssessment2=$getCurrentResult2->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',2)->orderBy('date','Desc')->limit(1)->get();
$recentResult=array_merge($resultAssessment1,$resultAssessment2);
return $recentResult;
}
This is a bad practice if you are fetching data from db inside the foreach loop.
BTW you can do this by keeping all new result in same array by index its some unique value, it will be look like this-
$toUpdate=array();
foreach ($result as $r) {
if($r->marks1==null || $r->marks2==null)
{
echo $r->p_code;
$toUpdate[$r->p_code]=$this->getResult($username,$r->p_code); // added $r->p_code as index to Array - $toUpdate
}
}
print_r($toUpdate); // this will give all the related result according your parameters
[UPDATE]
Try using unset($yourarray) for your next request these array will be new and they assign the new value each time -
public function getLatestResult($username,$course_code)
{
$user=new User;
$currentDetailOfUser=$this->userCurrentDetail($username);
$userdetail=json_decode($currentDetailOfUser,true);
$username =$userdetail['username'];
$studentid =$userdetail['userid'];
$studentBatch =$userdetail['batch'];
$programCode =$userdetail['programCode'];
$activeSemester =$userdetail['activesemester'];
$condition_key=array(
'studentid' =>$studentid
);
$getCurrentResult1 =$user->getDetail('student_result',$condition_key);
$getCurrentResult2 =$user->getDetail('student_result',$condition_key);
$resultAssessment1=$getCurrentResult1->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',1)->orderBy('date','Desc')->limit(1)->get();
$resultAssessment2=$getCurrentResult2->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',2)->orderBy('date','Desc')->limit(1)->get();
unset($currentDetailOfUser);
unset($userdetail);
unset($condition_key);
unset($recentResult);
$recentResult=array_merge($resultAssessment1,$resultAssessment2);
return $recentResult;
}
Hope this can help you.