MODx querying custom db table - pdo

See the code below. I'm trying to get some data from a database is modx. The data is there, meaning, when i query the database in phpmyadmin, i get results. I can't figure out why it doesnt work in modx.
$sql = 'SELECT * FROM orders ORDER BY created DESC LIMIT 1';
$stmt = $modx->prepare($sql);
$stmt->execute();
// Put data in array
$order_data = $stmt->fetch(PDO::FETCH_ASSOC);
if ($order_data == '') {
return 'Resultset empty for user '. $user_id.'.<br />'.$sql;
} else {
return 'Data found!';
}

Perhaps try using xPDO:
$sql = 'SELECT * FROM orders ORDER BY created DESC LIMIT 1';
$c = new xPDOCriteria($modx,$sql);
if ($c->stmt && $c->stmt->execute()) {
$order_data = $c->stmt->fetch(PDO::FETCH_ASSOC);
var_dump($order_data);
}

You need to loop through your output, the result will be an array of arrays.
The below example will return the data and present it according to a chunk format
<?php
$sql = "SELECT * FROM `table_name`";
$query = $modx->query($sql);
$rows = array();
if ($query) {
// loop through the result set and inspect one row at a time
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
array_push($rows, $row);
$output .= $modx->getChunk($tpl,$row);
}
}
$output = "<table border=\"1\" cellpadding=\"5\" >
<th>ID</th><th>row1_Head</th><th>row2_Head</th><th>row3_Head</th><th>row4_Head</th><th>row5_Head</th>
$output</table>";
return $output;
This is an example of the chunk:
<tr>
<td>[[+id]]</td> <td>[[+row1]]</td> <td>[[+row2]]</td> <td>[[+row3]]</td> <td>[[+row4]]</td> <td>[[+row5]]</td>
</tr>
Now in a resource call your snippet like
[[!Snippet_name? &tpl=`chunk_name`]]

$sql = 'SELECT * FROM orders ORDER BY created DESC LIMIT 1';
Assume your schema is like
<?xml version="1.0" encoding="UTF-8"?>
<model package="your_package_name" baseClass="xPDOObject" platform="mysql" defaultEngine="MyISAM" version="1.1">
<object class="Orders" table="orders" extends="xPDOSimpleObject">
<field key="order_no" dbtype="varchar" precision="255" phptype="string" null="false" />
<!-- and everything else below -->
</object>
<!-- and everything else below -->
</model>
What you need to do is as simple as this:
$modx->addPackage('your_package_name'); // Add your table schema to MODX object
$orders = $modx->getCollection('Orders'); // class's name, not table's name
$output = '';
if ($orders){
$outputArray = array();
foreach ($orders as $order) {
$orderArray = $order->toArray();
$outputArray[] = $modx->getChunk('your_row_chunk_name', $orderArray);
}
$wrapper = array(
'orders' => #implode("\n", $outputArray);
);
$output = $modx->getChunk('your_wrapper_chunk_name', $wrapper);
}
return $output;

Related

if condition in sql | codeigner

I have 2 table, one for:
user information
second for:
"user last activity"
I have code to fetch and display all user on the page, each user should display his state, - everything is work as shown in my code
BUT
I want to make my code clean, so I want to move the "if
condition" in my view page to model page when the state is empty in
the table,
I want to display all my user with users state in my page without
using if condition in the view page.
My code:
DataBase:
My Page:
View:
<?php foreach($Users as $c){ ?>
<th>Firstname</th>
<th>Lastname</th>
<th>Last Activity Time</th>
<th>State</th>
<th>User ID</th>
</tr>
<tr>
<td><?php echo $c->email ?></td>
<td><?php echo $c->type ?></td>
<td><?php echo $c->last_activity ?></td>
<td>
<!-- this code is run good , but i want to change it to contolloer to make the code clean ,
and if i changed to controller hw i can call the state here -->
<?php $current_timestamp = strtotime(date("Y-m-d H:i:s") . '- 10 second');
$current_timestamp = date('Y-m-d H:i:s', $current_timestamp);
if($c->last_activity > $current_timestamp)
{
echo "online";
}
else
{
echo "offline";
} ?>
Model:
public function getAllUsers() //from 1 table
{
$this->db->select('m.user_id, m.email , m.type, u.last_activity ,u.id ,u.state');
$this->db->from('tbl_user m');
$this->db->join('tbl_user_activity u ', 'u.user_id = m.user_id' ,'LEFT');
$this->db->select_max('u.last_activity');
// $this->db->where($where);
$this->db->group_by('m.user_id');// add group_by
$query = $this->db->get();
foreach ($query as $c)
{
$current_timestamp = strtotime(date("Y-m-d H:i:s") . '- 10 second');
$current_timestamp = date('Y-m-d H:i:s', $current_timestamp);
if('$c->last_activity' > $current_timestamp) //try
{ // here must to be function to checl the last user activity and get it
// here must to set the u.state to online
}
else if($query < $current_timestamp) //try
{
}
}
return $query->result();
What if you check and set "state" in your MODEL/CONTROLLER page
MODEL PAGE
<?php
//your code,
$last_activity = $c->last_activity; //make sure it won't return NULL
if($last_activity > $current_timestamp) { //return true if online,
$state = "online";
}else{
$state = "offline";
}
//your code,
?>
just read the state in your VIEW page
VIEW PAGE
<?php
//your code,
$new_state = $c->state; //so $new_state = "online" or $new_state = "offline"
//your code,
?>
Try this.
It will create a new collection of data with a new row called 'state';
The return value is an array so you should probably change your view to loop an array instead of an object.
$query = $this->db->get()->result_result_array();
$new_record = array();
foreach($query as $old_record)
{
$current_timestamp = strtotime(date("Y-m-d H:i:s") . '- 10 second');
$current_timestamp = date('Y-m-d H:i:s', $current_timestamp);
if('$c->last_activity' > $current_timestamp) //try
{
$new_record[]['state'] = 'online';
$new_record[] = $old_record;
}
else if($query < $current_timestamp) //try
{
$new_record[]['state'] = 'offline';
$new_record[] = $old_record;
}
}
return $new_record;

get table rate shipping data in Woocommerce REST API

I am trying to get all active shipping methods in Woocommerce REST API. How can I achieve this. I am new to woocommerce REST API, Any help is much appreciated.
I want response something like this -
{
"shipping_methods": {
"method_id": "method_title"
}
}
I , finally, come up with the solution. It may help others.
Below is complete code to get all table rate shipping data including shipping zones, shipping methods by zone and rates by zone -
header('Content-type: application/json');
$json_file=file_get_contents('php://input');
$jsonvalue= json_decode($json_file,true);
global $wpdb;
global $woocommerce;
$active_methods = array();
$shipping_methods = $woocommerce->shipping->load_shipping_methods();
//echo "<pre>";print_r($shipping_methods);
foreach ( $shipping_methods as $id => $shipping_method ) {
if ( isset( $shipping_method->enabled ) && 'yes' === $shipping_method->enabled ) {
$data_arr = array( 'title' => $shipping_method->title, 'tax_status' => $shipping_method->tax_status );
if($id=='table_rate'){
$raw_zones = $wpdb->get_results("SELECT zone_id, zone_name, zone_order FROM {$wpdb->prefix}woocommerce_shipping_zones order by zone_order ASC;");
//echo "<pre>";print_r($raw_zones);
$shipping = array();
$shippingarr = array();
foreach ($raw_zones as $raw_zone) {
$zones = new WC_Shipping_Zone($raw_zone->zone_id);
$zone_id = $zones->zone_id;
$zone_name = $zones->zone_name;
$zone_enabled = $zones->zone_enabled;
$zone_type = $zones->zone_type;
$zone_order = $zones->zone_order;
$shipping['zone_id'] = $zone_id;
$shipping['zone_name'] = $zone_name;
$shipping['zone_enabled'] = $zone_enabled;
$shipping['zone_type'] = $zone_type;
$shipping['zone_order'] = $zone_order;
$shipping_methods = $zones->shipping_methods;
foreach($shipping_methods as $shipping_method){
$methodid = $shipping_method["number"];
$raw_rates[$methodid]['rates'] = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}woocommerce_shipping_table_rates WHERE shipping_method_id={$methodid};",ARRAY_A);
}
$shipping['shipping_methods'] = $raw_rates;
$raw_country = $wpdb->get_results("SELECT location_code FROM {$wpdb->prefix}woocommerce_shipping_zone_locations WHERE zone_id={$zone_id};",ARRAY_N);
$shipping['countries'] = $raw_country;
$shippingarr[] = $shipping;
}
$data_arr['shipping_zones'] = $shippingarr;
}
$active_methods[ $id ] = $data_arr;
}
}
if(!empty($shippingarr)){
$result['success']='true';
$result['error']="0";
$result['msg']='Shipping methos found.';
$result['data']=$active_methods;
}else{
$result['success']='true';
$result['error']="0";
$result['msg']='Shipping methos found.';
$result['data']= array();
}
echo json_encode($result); `

How to assign data to excel sheets in alphabetical order in PHPExcel

I am trying to create excel generated file. I want to get usernames from database and then print names according to each letter in alphabet. I am able to create sheets in alphabetical order but cant print names on each sheet.
Here is what i have so far:
<?php
require_once ('PHPExcel/Classes/PHPExcel.php');
include('inc/database_connection.php');
$conn = mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, DATABASE_NAME);
$conn->set_charset('utf8_unicode_ci');//if not by default
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
$F = $objPHPExcel->getActiveSheet();
$Letter='B';
$Number=2;
for($i=321; $i<347; $i++)
{
$F = $objPHPExcel->createSheet($i); //Setting index when creating
$F->setCellValue('A1', "Username")
->setCellValue('B1', "Project")
->setCellValue('C1', "Processes");
$request="SELECT username FROM user WHERE username LIKE '".chr($i+32)."%'";
$result= $conn->query($request);//get the result (ressource)
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
$username=$row["username"];
$F->setCellValue('A'.$Number, ' '.$username.' ');
$F->getRowDimension('1')->setRowHeight(20);
$F->getColumnDimension($Letter)->setWidth(30);
++$Number;
}
} else
{
echo "0 results";
}
$F->setTitle(chr($i));
}
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="HeadCount.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
?>
Is there way to print usernames for each spreedsheet? Thank you.
Problem was solved by removing if statement
$objPHPExcel = new PHPExcel();
$F = $objPHPExcel->getActiveSheet();
for($i=321; $i<347; $i++)
{
$Letter='B';
$Number=2;
$F = $objPHPExcel->createSheet($i); //Setting index when creating
$objPHPExcel->setActiveSheetIndex(1);
$F->setCellValue('A1', "Username")
->setCellValue('B1', "Project")
->setCellValue('C1', "Processes");
$request="SELECT username FROM user WHERE username LIKE '".chr($i+32)."%'";
$result= $conn->query($request);//get the result (ressource)
// output data of each row
while($row = $result->fetch_assoc())
{
$username=$row["username"];
$F->setCellValue('A'.$Number, ' '.$username.' ');
$F->getRowDimension('1')->setRowHeight(20);
$F->getColumnDimension($Letter)->setWidth(30);
++$Number;
}
$F->setTitle(chr($i));
}

How can I unserialize data from database after it was serialized

try {
if (isset($_SESSION['list']) > 0) {
$test = serialize($_SESSION["list"]);
$sQuery = "INSERT INTO table (id, date) VALUES ('$test', NOW())";
$oStmt = $db->prepare($sQuery);
$oStmt->execute();
}
else {
echo 'No data';
}
}
In my database I see this:
1 a:1:{i:1;s:1:"5";} 2011-12-21
The $_SESSION['list'] stores ID and the QUANTITY.
The data a:1:{i:1;s:1:"5";} is as follow: i=id, s=id:"quantity", I read this as id=1 and the quantity of id=1 is 5, am I correct?
Now I want select the data and unserialize the array.
try {
$sQuery = "SELECT * FROM table";
$oStmt = $db->prepare($sQuery);
$oStmt->execute();
while($aRow = $oStmt->fetchALL(PDO::FETCH_ASSOC)) {
$id = unserialize($aRow['id']);
foreach($id as $id => $quantity) {
echo $id.', ';
}
}
}
catch(PDOException $e) {
$sMsg = '<p>
Regelnummer: '.$e->getLine().'<br />
Bestand: '.$e->getFile().'<br />
Foutmelding: '.$e->getMessage().'
</p>';
trigger_error($sMsg);
}
What am I doing wrong or what can I do so I can select the ID and QUANTITY from database?
The serialization/deserialization part looks fine to me, but the $oStmt->fetchALL( I think should be $oStmt->fetch(, and in foreach($id as $id => $quantity) { use another variable to hold the key instead of id, like foreach($id as $key => $quantity) {.
Also, you don't echo the quantity anywhere. Change echo $id.', '; to echo $key.' '.$quantity; or something and tell us what the output is so we can help further.

codeigniter pagination for a query

So far found plenty of help to get the pagination working for a get(table) command.
What I need is to pick only few of the entries from a couple of linked tables based on a sql where statement.
I guess the query command is the one to use but in this case how do I do the pagination since that command does not take extra parameters such $config['per_page']
Thanks for the help
Without any more info to go on I think that what you're looking for is something like the following.
public function pagination_example($account_id)
{
$params = $this->uri->ruri_to_assoc(3, array('page'));
$where = array(
'account_id' => $account_id,
'active' => 1
);
$limit = array(
'limit' => 10,
'offset' => (!empty($params['page'])) ? $params['page'] : 0
);
$this->load->model('pagination_model');
$data['my_data'] = $this->pagination_model->get_my_data($where, $limit);
foreach($this->uri->segment_array() as $key => $segment)
{
if($segment == 'page')
{
$segment_id = $key + 1;
}
}
if(isset($segment_id))
{
$config['uri_segment'] = $segment_id;
}
else
{
$config['uri_segment'] = 0;
}
$config['base_url'] = 'http://'.$_SERVER['HTTP_HOST'].'/controller_name/method_name/whatever_your_other_parameters_are/page/';
$config['total_rows'] = $this->pagination_model->get_num_total_rows();// Make a method that will figure out the total number
$config['per_page'] = '10';
$this->load->library('pagination');
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
$this->load->view('pagination_example_view', $data);
}
// pagination_model
public function get_my_data($where = array(), $limit = array())
{
$this->db
->select('whatever')
->from('wherever')
->where($where)
->limit($limit['limit'], $limit['offset']);
$query = $this->db->get();
if($query->num_rows() > 0)
{
$data = $query->result_array();
return $data;
}
return FALSE;
}
This should at least get you on the right track
If this isn't what you're asking I'd happy to help more if you can be a little more specific. How about some of your code.
The only other options that I can think of would be to either code a count in your select statement or not limit the query and use array_slice to select a portion of the returned array.