Prepending an unknown amount of database fields to array - arrays

I have a database with the following structure
user_id | cat_name | cat_slug | parent_id
-------------------------------------------
Tools | tools | 0 |
2 |Chainsaws |chainsaws | 1
etc
My end goal is to essentially have an array that has a breadcrumb trail of sorts that shows the category path, it could have anywhere from no parents to 5 levels of category parenting.
I was able to kind of get what I want.. with a few errors along the way. I keep getting a Trying to get property of non-object error. Althrough all my other attempts at returning values have failed.
My solution outputs my (semi - desired) effect underneath the errors, and with additional category breaks ( symbolized by ">" ). I was just hoping someone could help me clean it up, because I'm at a breaking point, after going about this for a few hours with no solution.
Model
function get_parent_trail($parent_id){
if ( $parent_id != 0 && $parent_id){
$parent_trail = array();
for( $i = 1; $i <= 4; $i ++ ) {
$this -> db -> select ( '*' );
$this -> db -> from ( 'categories' );
$this -> db -> where ( 'cat_id' , $parent_id );
$query = $this -> db -> get() -> row();
array_unshift( $parent_trail, $query->cat_name ) ;
$parent_id = $query->parents;
}
foreach( $parent_trail as $ti ) {
if ( $ti ) {
echo "<strong>" . $ti . "</strong> > ";
}
}
} else {
echo "<span style='color:red;'>No Parent Category</span>";
}
}
View
<table class='admin_table'>
<thead>
<th>ID</th>
<th>Name</th>
<th>Parent</th>
</thead>
<tbody>
<?php
foreach($cats as $cat){
echo "<tr>";
echo "<td>" . $cat['cat_id'] . "</td>";
echo "<td>" . $cat['cat_name'] . "</td>";
echo "<td>";
$this -> categories -> get_parent_trail( $cat['parents'] );
echo "</td>";
echo "</tr>";
}
?>
</tbody>
</table>
NOTE:
The '4' in the for loop doesn't need to be dynamic as I've set a hard limit of up to 5 categories, though there has been no need to go that far into sub-categories.
I also have an additional ">" at the end of my list, which I need to get rid of, I know the reason my way doesn't work, it's just the closest solution I could find for the time being.
End Result
Basically, I want my end result to look like;
With 2 'levels' of parent categories
id | name | slug | Parent(s)
-----------------------------------------------------------------------
1 | Electric Chainsaws | electric-chainsaws | Tools > Chainsaws

What you are wanting to do is build a recursive function.
Example of this would be:
function factorial($number)
{
if ($number < 2)
{
return 1;
}
else
{
return ($number * factorial($number-1));
}
}

After much hair pulling and several bottles of very strong rum, I was able to finally figure this out. I'm still relatively novice at using codeigniter so my solution may have some unnecessary steps to it, but I feel obliged to share what I learned. Here is my entire function.
function get_parent_trail($parent_id){
if ( $parent_id != 0 && $parent_id){
$parent_trail = array();
$inc = 0;
for( $i = 1; $i <= 4; $i ++ ) {
if ( $parent_id != 0 && $parent_id){
$this -> db -> select ( '*' );
$this -> db -> from ( 'categories' );
$this -> db -> where ( 'cat_id' , $parent_id );
$query = $this -> db -> get();
$row = $query -> row_array();
array_unshift( $parent_trail, $row['cat_name'] ) ;
$parent_id = $row['parents'];
} else {
$inc++;
}
}
$popOff = array_pop($parent_trail);
if ($inc > 2 ){
echo "<span style='color:red;'>No Parent Category</span>";
}
$string = '';
foreach( $parent_trail as $ti ) {
if ( $ti ) {
$string .= $ti.' > ';
}
}
(string) $test = substr($string, 0, -2);
echo $test;
} else {
echo "<span style='color:red;'>No Parent Category</span>";
}
}

Related

How to fetch all the coinbase pro transactions correctly in php

I have a question of coinbase pro,
How can I get all the orders/transactions from coinbase pro using php without any limit , or with any limit parameter.
I am using the following library to fetch all the coinbase pro orders , but it only gives me 100 orders from the below method.
fetch_orders
Here is the method,
$CoinbaseProtrans = $CoinbasePro->fetch_orders('ETH/USD',"",150,array('limit'=>100,'after'=>1));
echo "<pre>";print_r($CoinbaseProtrans);echo "</pre>";
Here is the error I am getting,
Fatal error: Uncaught ccxt\ExchangeError: coinbasepro after cursor value is not valid in coinbasepro.php:813
Here is the link of the library:
https://github.com/ccxt/ccxt/blob/master/php/coinbasepro.php
This question was answered here: https://github.com/ccxt/ccxt/issues/6105#issuecomment-552405563
<?php
include_once ('ccxt.php');
date_default_timezone_set ('UTC');
$exchange = new \ccxt\coinbasepro(array(
'apiKey' => 'YOUR_API_KEY',
'secret' => 'YOUR_SECRET',
// 'verbose' => true, // uncomment for debugging
// https://github.com/ccxt/ccxt/wiki/Manual#rate-limit
'enableRateLimit' => true, // rate-limiting is required by the Manual
));
$exchange->load_markets ();
// $exchange->verbose = true; // uncomment for debugging
$all_results = array();
$symbol = 'ETH/USD';
$since = null;
$limit = 100;
$params = array();
do {
// any of the following methods should work:
// $results = $exchange->fetch_orders($symbol, $since, $limit, $params);
// $results = $exchange->fetch_my_trades($symbol, $since, $limit, $params);
$results = $exchange->fetch_trades($symbol, $since, $limit, $params);
echo $exchange->iso8601($exchange->milliseconds());
echo ' fetched ' . count($results) . " results\n";
$all_results = array_merge ($all_results, $results);
if (count($results) > 0) {
$last = count($results) - 1;
echo ' last result ' . $results[$last]['id'] . ' ' . $results[$last]['datetime'] . "\n";
echo ' first result ' . $results[0]['id'] . ' ' . $results[0]['datetime'] . "\n";
} else {
break;
}
#$params['after'] = $exchange->last_response_headers['cb-after'][0];
// uncomment one of the following:
// } while (true); // fetch all results forever
} while (count($all_results) < 1000); // fetch up to 1000 results
echo "fetched " . count($all_results) . " results in total\n";
?>

How to put a database into an array

I finally succeeded in making an image carousel by using php.
The code below works, but there are no images in it.
Now I am trying to make this array to get data from a Mysql database.
Could you show me an example of how do I do it?
<?php
//MySQL database connection
$mysqli = new mysqli('localhost', 'root', '', 'webshop');
$SQL = "SELECT image FROM productlist LIMIT 5";
$result = $mysqli->query($SQL);
$array = array(
0 => "picture1.jpg",
1 => "picture2.jpg",
2 => "picture3.jpg",
3 => "picture4.jpg",
4 => "picture5.jpg",
5 => "kalle6.jpg",
);
//Goes to previous page when clicking on prev
$index = $_GET['start'];
if ($index > 0) {
echo ' prev ';
} else {
echo ' prev ';
}
//Display 3 images
$show_img = 3;
$num_img = 0;
for($i = $_GET['start']; $i<count($array) && $num_img < $show_img; $i++) {
$num_img++;
echo "<img src=".$array[$i]."/>\n";
}
for($i=$num_img; $i<$show_img;$i++) {
echo "<img src=".(count($array) - 1)."/>\n";
}
//Goes to next page when clicking on next
if ($index < count($array) - 1) {
echo ' next ';
} else {
echo ' next ';
}
?>
You should have a look at this: http://php.net/manual/en/mysqli-result.fetch-array.php
/* numeric array */
/* $row is your $array */
$row = $result->fetch_array(MYSQLI_NUM);
echo "<pre>";
print_r($row);
echo "<pre>";
This should help you get the result you want

array of ints remains undef after multiple push() calls

I'm trying to save error codes by:
#global space
my #retCodes;
#main
sub BuildInit {
my $actionStr = "";
my $compStr = "";
my #component_dirs;
my #compToBeBuilt;
foreach my $comp (#compList) {
#component_dirs = GetDirs($comp); #populates #component_dirs
}
print "Printing Action List: #actionList\n";
#---------------------------------------
#---- Setup Worker Threads ----------
for ( 1 .. NUM_WORKERS ) {
async {
while ( defined( my $job = $q->dequeue() ) ) {
worker($job);
}
};
}
#-----------------------------------
#---- Enqueue The Work ----------
for my $action (#actionList) {
my $sem = Thread::Semaphore->new(0);
$q->enqueue( [ $_, $action, $sem ] ) for #component_dirs;
$sem->down( scalar #component_dirs );
print "\n------>> Waiting for prior actions to finish up... <<------\n";
}
# Nothing more to do - notify the Queue that we're not adding anything else
$q->end();
$_->join() for threads->list();
return 0;
}
#worker
sub worker {
my ($job) = #_;
my ( $component, $action, $sem ) = #$job;
Build( $component, $action );
$sem->up();
}
#builder method
sub Build {
my ( $comp, $action ) = #_;
my $cmd = "$MAKE $MAKE_INVOCATION_PATH/$comp ";
my $retCode = -1;
given ($action) {
when ("depend") { $cmd .= "$action >nul 2>&1" } #suppress output
when ("clean") { $cmd .= $action }
when ("build") { $cmd .= 'l1' }
when ("link") { $cmd .= '' } #add nothing; default is to link
default { die "Action: $action is unknown to me." }
}
print "\n\t\t*** Performing Action: \'$cmd\' on $comp ***" if $verbose;
if ( $action eq "link" ) {
# hack around potential race conditions -- will only be an issue during linking
my $tries = 1;
until ( $retCode == 0 or $tries == 0 ) {
last if ( $retCode = system($cmd) ) == 2; #compile error; stop trying
$tries--;
}
}
else {
$retCode = system($cmd);
}
push( #retCodes, ( $retCode >> 8 ) );
#testing
if ( $retCode != 0 ) {
print "\n\t\t*** ERROR IN $comp: $# !! ***\n";
print "\t\t*** Action: $cmd -->> Error Level: " . ( $retCode >> 8 ) . "\n";
#exit(-1);
}
return $retCode;
}
Error that gets displayed:
Use of uninitialized value $maxReturnCode in concatenation (.) or
string at C:\script.pl line 66, line 415.
I can see from the first line of output though, that I get things like: Return Code: 0 Return Code: 0 Return Code: 2 ..
The issue here is that the code isn't sharing the array between threads; so because of that, each thread is modifying it's local copy of the array, not the global array as expected. The fix for this problem is to share the variable, and lock it before accessing it during the thread processing:
my #retCodes;
share(#retCodes);
...
#during the thread sub
lock(#retCodes);
push(#retCodes, ($retCode>>8));
Here's a stubbed-out runnable version that you should be able to modify a bit to do what you need:
#!/usr/bin/perl
use strict;
use warnings;
use List::Util 'max';
use threads;
#global space
my #retCodes = ();
share(#retCodes);
sub builder {
my ($comp, $cmd) = ('builder', 'test');
for my $retCode (qw/0 0 256/) {
print "\n\t\tReturn Code: " . ($retCode >>8) . "\n";
lock(#retCodes);
push(#retCodes, ($retCode>>8));
}
}
#main
builder();
# other threads started...
# wait for threads to complete...
printf "Codes: %s\n", join(', ', #retCodes);
my $maxReturnCode = max(#retCodes);
print "Highest Error Code: $maxReturnCode\n"; #<-- crashes with error below
exit($maxReturnCode);

yii database query inside loop

I didn't get the correct filter out for the following action. Here $val is an array of checked values. But the query executes only for the last element of the array even though I used the foreach loop. Please, can anyone help me?
if( isset($_POST['state']) && count($_POST['state']) > 0 ){
foreach($_POST['state'] as $row => $val ){
$criteria = new CDbCriteria;
$criteria->select='*';
$criteria->condition='pjt_user_id=:pjt_user_id && pjt_pdt_status=:pjt_pdt_status';
$criteria->params=array(':pjt_user_id'=> $user_id, ':pjt_pdt_status'=> $val);
$criteria -> order = 'pjt_id';
$projects= ProjectModel::model() -> findAll($criteria);
}
$this->render('index', array('projects'=>$projects));
Thanks Martin Komara....
I got the solution ...
I just use OR condition in SQL.
if(isset($_POST['state']) && count($_POST['state']) > 0 ){
$i = 0;
foreach($_POST['state'] as $data){
$condit[":$data"] = $data;
if($i!=0){
$var .= ' || ';
}
$var .= " pjt_pdt_status=:$data";
$i++;
}
$var = ' AND (' .$var.' )';
}
$criteria = new CDbCriteria;
$criteria->select='*';
$criteria->condition='pjt_user_id=:pjt_user_id' .$var ;
$criteria->params=$condit;
$criteria -> order = 'pjt_id';
$projects= ProjectModel::model() -> findAll($criteria);
This would be better - much more readable:
if (isset($_POST['state']) && count($_POST['state']) > 0 ) {
$criteria = new CDbCriteria;
$criteria->addInCondition('pjt_pdt_status', $_POST['state']);
$criteria->addColumnCondition(array('pjt_user_id' => $user_id));
$criteria->order = 'pjt_id';
$projects = ProjectModel::model()->findAll($criteria);
}

How do i correct jqgrid footer information?

I am using jqgrid in one of my application.
Right now i am facing a strange problem and do not know how to rectify it?
Actually in one of the reports (having multiple link) jqgrid is showing wrong footer information that is its showing Page 0 of 0 even if there are records in the table.
This is the code which runs:
if( isset($this->params['named']['ajax']) && $this->params['named']['ajax'] == '1' )
{
$this->autoRender = false;
// get how many rows we want to have into the grid - rowNum parameter in the grid
$limit = $this->params['url']['rows'];
// get index row - i.e. user click to sort. At first time sortname parameter -
// after that the index from colModel
$sidx = $this->params['url']['sidx'];
// sorting order - at first time sortorder
$sord = $this->params['url']['sord'];
$page = $this->params['url']['page'];
// if we not pass at first time index use the first column for the index or what you want
if( !$sidx ) $sidx = 1;
// calculate the number of rows for the query. We need this for paging the result
$findconditions = array();
if(!empty($this->params['named']['batch']))
array_push(&$findconditions, array('Batch.id' => $this->params['named']['batch'] ));
$row = $this->Placement->find('count',array(
'link' => array(
'Student' => array(
'Batch'
)
),
'conditions'=> $findconditions
));
$count = $row;
// calculate the total pages for the query
if( $count > 0 )
{
$total_pages = ceil($count / $limit);
}
else
{
$total_pages = 0;
}
// if for some reasons the requested page is greater than the total
// set the requested page to total page
if( $page > $total_pages ) $page = $total_pages;
// calculate the starting position of the rows
$start = $limit * $page - $limit;
// if for some reasons start position is negative set it to 0
// typical case is that the user type 0 for the requested page
if( $start < 0 ) $start = 0;
// the actual query for the grid data
$limit_range = $start . "," . $limit;
$sort_range = $this->modelClass . '.' . $sidx . " " . $sord;
$this->Placement->recursive = -1;
$where='';
if( $this->params['url']['_search'] == 'true' )
{
//pr($this->params);
$searchconditions = array();
if( isset($this->params['named']['batch']) && !empty($this->params['named']['batch']) )
{
$where.= " Batch.id =".$this->params['named']['batch'];
}
if( isset($this->params['url']['isstillworking']) && !empty($this->params['url']['isstillworking']) )
{
$where.= " AND Placement.isstillworking ='".$this->params['url']['isstillworking']."'";
}
if( isset($this->params['url']['studentname']) && !empty($this->params['url']['studentname']) )
{
$where.=" AND Student.fullname LIKE '" .$this->params['url']['studentname'] . "%'";
}
if( isset($this->params['url']['companyname']) && !empty($this->params['url']['companyname']) )
{
$where.=" AND Company.name LIKE '" .$this->params['url']['companyname'] . "%'";
}
if( isset($this->params['url']['salary']) && !empty($this->params['url']['salary']) )
{
$where.= " AND Placement.salary =".$this->params['url']['salary'];
}
if( isset($this->params['url']['contactnumber1']) && !empty($this->params['url']['contactnumber1']) )
{
$where.= " AND Student.contactnumber1 =".$this->params['url']['contactnumber1'];
}
if( isset($this->params['url']['batchname']) && !empty($this->params['url']['batchname']) )
{
$where.=" AND Batch.name LIKE '" .$this->params['url']['batchname'] . "%'";
}
$sql="SELECT Student.fullname,
Placement.isstillworking,
Company.id,
Company.name,
Placement.id,
Placement.salary,
Placement.created,
Student.id,
Student.contactnumber1,
Batch.id,
Batch.name
FROM placements Placement
INNER JOIN (
SELECT student_id, isstillworking, max( created ) AS other_col
FROM placements
GROUP BY student_id
) AS b ON Placement.student_id = b.student_id
AND Placement.created = b.other_col
INNER JOIN students Student ON ( Student.id = Placement.student_id )
INNER JOIN batches Batch ON ( Student.batch_id = Batch.id )
INNER JOIN companies Company ON ( Company.id = Placement.company_id )
WHERE ".$where.
" AND Student.type='student'
AND Student.trainingcompleted=1
ORDER BY ".$sort_range."
LIMIT ".$limit_range
;
$result=$this->Placement->query($sql);
}
else
{
$sql="SELECT Student.fullname,
Placement.isstillworking,
Company.id,
Company.name,
Placement.id,
Placement.salary,
Placement.created,
Student.id,
Student.contactnumber1,
Batch.id,
Batch.name
FROM placements Placement
INNER JOIN (
SELECT student_id, isstillworking, max( created ) AS other_col
FROM placements
GROUP BY student_id
) AS b ON Placement.student_id = b.student_id
AND Placement.created = b.other_col
INNER JOIN students Student ON ( Student.id = Placement.student_id )
INNER JOIN batches Batch ON ( Student.batch_id = Batch.id )
INNER JOIN companies Company ON ( Company.id = Placement.company_id )
WHERE Batch.id =
".$this->params['named']['batch'].
" AND Student.type='student'
AND Student.trainingcompleted=1
ORDER BY ".$sort_range."
LIMIT ".$limit_range
;
$result=$this->Placement->query($sql);
}
$i = 0;
$response->page = $page;
$response->total = $total_pages;
$response->records = $count;
//pr($result);
foreach($result as $result)
{
$response->rows[$i]['id'] = $result['Placement']['id'];
$student = "<a href='" . APP_URL . "placements/report18/studentid:" . $result['Student']['id']."'>" . $result['Student']['fullname'] . "</a>";
$company = "<a href='" . APP_URL . "companies/view/" . $result['Company']['id'] . "'>" . $result['Company']['name'] . "</a>";
$batch = "<a href='" . APP_URL . "batches/view/" . $result['Batch']['id'] . "'>" . $result['Batch']['name'] . "</a>";
$contactnumber1 =$result['Student']['contactnumber1'];
$response->rows[$i]['cell'] = array($student, $result['Placement']['isstillworking'], $result['Company']['name'], $result['Placement']['salary'], $contactnumber1, $batch);
$i++;
}
echo json_encode($response);
}
I am also attaching the screen shot for reference.
Please help me on this.
Regards,
Pankaj
Why on earth would you not use Cake's ORM layer and Pagination class? If you use Model->query() you have to escape input yourself!

Resources