How to export data from user modx database to form? - php

I've table in modx database (orders), and i need to export data from that db to table at site.
I pushing into db with following snipept
<?php
function agregarCargas( &$fields )
{
global $modx;
// Init our array
$dbTable = array();
$dbTable['subject'] = $modx->db->escape($fields['subject']);
$dbTable['fullname'] = $modx->db->escape($fields['fullname']);
$dbTable['message'] = $modx->db->escape($fields['message']);
// Run the db insert query
$dbQuery = $modx->db->insert($dbTable, 'orders' );
return true;
}
?>
How can i export from DB? Snippet or? Thanks.

(Old thread, just for new folks trying to tackle this...)
Looking at the API you're using I'm guessing you are stuck with an old MODx version. (Evolution)
You should take a look at the API::DB docs for MODX Evolution
Something along the lines of the following would fill your HTML table:
$res = $modx->db->select("subject, fullname", 'orders');
$res_rows = $modx->db->makeArray($res);
$rows = "";
for($n=0;$n<count($res_rows);$n++){
$rows .= "<tr><td>".$res_rows['subject']."</td><td>".$res_rows['fullname']."</td></tr>\n";
}
return $rows;
(Of course you should use chunks instead of hardcoded HTML)

Related

How to get entire MongoDB collection with PHP

Using the following code, I can grab a node from a collection:
<?php
$user = "xxxx";
$pwd = 'xxxx';
if (isset($_POST['needleID'])) {
$needleID = $_POST['needleID'];
} else {
echo "needle ID not set";
}
//Manager Class
$connection = new MongoDB\Driver\Manager("mongodb://${user}:${pwd}#localhost:27017");
// Query Class
$filter = ['id'=> $needleID];
$query = new MongoDB\Driver\Query($filter);
// Output of the executeQuery will be object of MongoDB\Driver\Cursor class
$rows = $connection->executeQuery('DBNAME.DBCOLLECTION', $query);
// Convert rows to Array and send result back to javascript as json
$rowsArr = $rows->toArray();
echo json_encode($rowsArr);
?>
However, what I'm really looking to do is get everything from the DBCOLLECTION.
I'm kind of at a loss on how to do this. A few searches either go over my head or are for older versions of the PHP driver, such as this one fetch all data from mongodb collection
If you query on a specific ID, then you will only receive the document with that ID as its value. If you want to retrieve all document in a collection, leave the filter empty, i.e. with $filter = [];.
It is better to use mongoexport for exporting collections. On large collections your code will be slow and will timeout. Consider using pagination for results.

Design pattern for PHP classes sharing data from SQL queries

I'm a beginner to OOP. The following is the jist of my code, which I am trying to find a proper design pattern for:
class data {
public $location = array();
public $restaurant = array();
}
$data = new data;
$query = mysqli_query($mysqli, "SELECT * FROM restaurants");
//actually a big long query, simplified for illustrative purposes here
$i = 0;
while ($row = mysqli_fetch_array($query)) {
$data->location[] = $i.')'.$row['location']."<br>";
$data->restaurant[] = $row['restaurant']."<br>";
$i++;
}
I'd like to access the data class from another PHP page. (To print out information in HTML, hence the tags). I prefer not to run the query twice. I understand that classes are created and destroyed in a single PHP page load. I'd appreciated design pattern guidance for managing HTTP application state and minimizing computer resources in such a situation.
If you store the data object in a $_SESSION variable, you will have access to it from other pages and upon refresh. As mentioned in other post and comments, you want to separate out the HTML from data processing.
class data {
public $location = array();
public $restaurant = array();
}
// start your session
session_start();
$data = new data;
$query = mysqli_query($mysqli, "SELECT * FROM restaurants");
//actually a big long query, simplified for illustrative purposes here
$i = 0;
while ($row = mysqli_fetch_array($query)) {
$data->location[] = $i.')'.$row['location'];
$data->restaurant[] = $row['restaurant'];
$i++;
}
// HTML (separate from data processing)
foreach ($data->location as $location) {
echo $location . '<br />';
}
// save your session
$_SESSION['data'] = $data;
When you wish to reference the data object from another page
// start your session
session_start();
// get data object
$data = $_SESSION['data'];
// do something with data
foreach($data->location as $location) {
echo $location . '<br />';
}
SELECT data in database is rather inexpensive, in general speaking. You didn't need to worry about running the query twice. MySQL will do the caching part.
From your codes, you mixed up database data with HTML. I suggest to separate it.
// fetch data part
while ($row = mysqli_fetch_array($query)) {
$data->location[] = $row['location'];
$data->restaurant[] = $row['restaurant'];
}
// print HTML part
$i = 0;
foreach($data->location as $loc) {
echo $i . ')' . $loc . '<br />';
}
First you say this:
I'm a beginner to OOP.
Then you say this:
I prefer not to run the query twice. I understand that classes are
created and destroyed in a single PHP page load.
You are overthinking this. PHP is a scripting language based on a user request to that script. Meaning, it will always reload—and rerun—the code on each load of the PHP page. So there is no way around that.
And when I say you are overthinking this, PHP is basically a part of a L.A.M.P. stack (Linux, Apache, MySQL & PHP) so the burden of query speed rests on the MySQL server which will cache the request anyway.
Meaning while you are thinking of PHP efficiency, the inherent architecture of PHP insists that queries be run on each load. And with that in mind the burden of managing the queries falls on MySQL and on the efficiency of the server & the design of the data structures in the database.
So if you are worried about you code eating up resources, think about improving MySQL efficiency in some way. But each layer of a L.A.M.P. stack has its purpose. And the PHP layer’s purpose is to just reload & rerun scripts in each request.
You are probably are looking for the Repository pattern.
The general idea is to have a class that can retrieve data objects for you.
Example:
$db = new Db(); // your db instance; you can use PDO for this.
$repo = new RestaurantRepository($db); // create a repo instance
$restaurants = $repo->getRestaurants(); // retrieve and array of restaurants instances
Implentation:
class RestaurantRepository {
public function __construct($db) {
$this->db = $db;
}
public function getRestaurants() {
// do query and return an array of instances
}
}
Code is untested and may have typos but it's a starter.
Saving the query results to a $_SESSION variable in the form of an array results in not having to re-run the query on another page. Additionally, it manages state correctly as I can unset($_SESSION['name']) if the query is re-run with different parameters.
I can also save the output of class data to a session variable. It seems to me that this design pattern makes more sense than running a new query for page refreshes.

Limit the database access though PHP

For a plugin system I am writing, I need to write a database API. But I want to restrict database access, so plugins can't see other tables than the ones they created through a specific function. How would I enable plugins to use SQL, but not give them full access at the same time?
Here is some code, it may not be working, but it shows the idea behind it:
class Api_Database {
private $pluginid;
function __construct($pluginid) {
$this->pluginid = $pluginid;
}
function query($sql, $tablename) {
$db = new Sys_Database;
$db->query(str_replace('{table}', $pluginid.$tablename, $sql));
}
}
Am I thinking in the right direction here? How would you create such a system, only more secure?
The idea is to create a table containing the list of created tables linked to the user...
Something like :
privileges
user_id
table_name
And in your query
SELECT FROM privileges WHERE user_id = '{user_id}' and table_name = '{table}';
And after check if the row exist. If yes, the user have the right to use the table!
class Api_Database {
private $pluginid;
function __construct($pluginid) {
$this->pluginid = $pluginid;
}
function query($sql, $tablename) {
$hasPrivilege = $this->checkPrivileges($tablename, $userid);
if(!$hasPrivilege) return false; //for example
$db = new Sys_Database;
$db->query(str_replace('{table}', $pluginid.$tablename, $sql));
}
function checkPrivileges($table, $user_id) {
$db = new Sys_Database;
$result = $db->query('SELECT id FROM privileges WHERE user_id = "'.$user_id.'" AND table_name = "'.$table.'"');
return ($result && $result->num_rows);
}
}
EDIT
So if I understand correctly, you are using a PHP plugin to access SQL data, but you can't or doesn't want to change it.
You cant' add SQL users too, and you wan't to restrict PHP Dev to make some queries in some table via PHP?? Hum... Impossible!
Because to be able to disallow database table access, YOU HAVE TO MANIPULATE PHP OR MYSQL USERS...
Or if I'm wrong, sorry, it's difficult to follow you!

How to populate a dropdown list from the database table in SugarCRM Community 6.5?

I've asked this question in the SugarCRM forums, but have been unable to find the answer as well. I am trying to populate a dropdown list in SugarCRM Community 6.5. I am using PHP5, MySQL and Apache. I created a custom dropdown list named 'oz_accounts' in the dropdown editor, created a new field in the custom module, Machines, that I built and associated the field with the Edit, Quick Create, Detail and List views based on the dropdown menu. Here is the code that I used, the result is a blank dropdown menu:
<?php
require_once('include/entryPoint.php');
$db = & DBManagerFactory::getInstance();
$myQuery = "SELECT name FROM accounts";
$Result = $db->query($myQuery);
$new_array = array();
while($row = $db->fetchByAssoc($Result)) {
$new_array[$row['key']] = $row['value'];
}
$GLOBALS['app_list_strings']['oz_accounts'] = $new_array;
Could someone please advise on what I'm doing incorrectly? I tested the query in phpmyadmin, and it retrieves the result i'm looking for, so I'm assuming that I must be making a mistake somewhere in the PHP code, possibly connecting to the database.
I posted directions on how to do this here some time ago: http://www.eggsurplus.com/content/populate-a-dropdown-from-the-database/
What you need to do is to create a custom util function and then tell your vardefs for that field to call the custom util function.
//custom/Extension/application/Ext/Utils/getAccounts.php
function getAccounts(){
static $accounts = null;
if(!$accounts){
global $db;
$query = "SELECT id, name FROM accounts";
$result = $db->query($query, false);
$accounts = array();
$accounts[''] = '';
while (($row = $db->fetchByAssoc($result)) != null) {
$accounts[$row['id']] = $row['name'];
}
}
return $accounts;
}
Name of the file doesn't matter. Make sure to include opening PHP tags. Run a Repair/Rebuild so that it builds custom/application/Ext/Utils/custom_utils.ext.php.
Then in the vardef definition for that field set the function to getAccounts:
'function' => 'getAccounts',
Repair/Rebuild will be needed after the vardef change.
the problems is in process definition the list not showing

Get value from Cassandra with PHPCASSA

I recently switched to PHPCassa to manage db connection in my PHP platform.
This is the code i'm using:
$indexExpression = new IndexExpression("Username", $username);
$indexClause = new IndexClause(array($indexExpression));
$cf = new ColumnFamily($this->cassandra, "Users");
$rows = $cf->get_indexed_slices($indexClause);
The problem is that actually $rows is not an array containing the data i'd like to fetch but it contains an IndexedColumnFamilyIterator object.
I'm I doing something wrong?
Thanks for helping.
Since you already cross-posted to the user mailing list (tisk, tisk :), I'll link to the answer and copy the answer here for others: https://groups.google.com/forum/?fromgroups#!topic/phpcassa/RrYTQc_jQ7s
It returns an iterator so that it can break up the query into manageable chunks (100 rows, by default) automatically.
$row_iterator = $cf->get_indexed_slices($indexClause);
foreach ($row_iterator as $key => $columns) {
// do stuff
}

Categories