I've created a web service with the following code:
class WebUser {
public $USERID;
}
class UseridService
{
public $username = "my_user";
public $password = "my_pw";
public $server = "my_remote_server";
public $databasename = "my_database";
public $tablename = "my_table";
function __construct ()
{
$this->con = mssql_connect($this->server, $this->username, $this->password) or die('Connection failed!');
mssql_select_db($this->databasename);
}
public function getUserid ()
{
$sql = "Select top 10 USERID FROM my_table";
$result = mssql_query($sql);
$rows = array();
while ($row = mssql_fetch_assoc($result))
{
$storage = new WebUser();
$storage->USERID = $row['USERID'];
$rows[] = $row;
}
mssql_close($this->con);
return $rows;
}
}
For now in flash builder 4.5, I want to output the top 10 userids into a List component in my canvas. I can assure everyone that the PHP webservice code I wrote works and returns an array of WebUser() objects with just the USERID string inside.
There is a lot of documentation online for MySQL and how they simply "drag and drop" the webservice into a list and it "magically" works. Despite trying to follow their conventions using MSSQL instead, I simply cannot get it working.
I was hoping if anyone can offer a piece of advice on what to do? Even if it's not an answer itself, does anyone know any online documentation that works specifically with Flashbuilder/PHP/MSSQL?
Go to the source! Adobe Documentation on setting this up:
http://www.adobe.com/devnet/flash-builder/articles/flashbuilder-php-part1.html
They walk you through hooking up a service in Flashbuilder, connecting your data objects, and displaying them.
I know what you're asking asks for MSSQL, but the database you use on the back-end doesn't matter. What matters is serializing your object from the server-side to the client-side (i.e. PHP to AS3) which means matching the objects on both ends or finding a way to convert them (i.e. JSON-encoded objects in a REST-based web service can be de-serialized quite smoothly using the as3core library as an example).
Related
I am right now trying to write a PHP class that executes database information. Yet I feel like I am doing something majorly wrong! It seems like what you would have to type in to get it to work is too much. Here is a example of what it looks like:
<?php
class database {
public $query_type = "";
public $database_name = "";
public $database_items_query = array();
public $database_where = "";
public function __construct($query_type, $database_name, $database_items_query, $database_where) {
$this->query_type = $query_type;
$this->query_name = $query_name;
$this->query_items_query = $query_items_query;
$this->query_where = $query_where;
}
public function database_query($query_type, $database_name, $database_items_query, $database_where) {
if ($query_type == "select") {
return $sqlquery = "SELECT ($database_items_query) FROM $database_name WHERE $database_where";
}
elseif ($query_type == "update") {
return $sqlquery = "UPDATE $databasename ";
}
}
}
$username = new database("");
?>
So for the beginning you would have to type in just this to get it to work the first function?
$username = new database("select","users","username","id");
So basically with what I have so far, what am I doing wrong? Sorry if this does not make sense :(
Ok I can see what you are trying to do, A constructor is normally used to "Create" a object. When the object is created then you have the opportunity to store values inside it so you dont have to
re-enter them, You only have to call a constructor once in a objects lifetime, and you can reuse all the methods multiple times.
soo... if you change your method declaration for database_query to something along these lines:
public function database_query($database_items_query = $this->database_items_query, $database_where = $this->query_where) {
$query_type = $this->query_type;
$database_name = $this->database_name;
Then you would be using the class variables as default values so your code would be something along the lines of
$columns = array("Name","Description");
$db = new database("SELECT","my_db",$columns,"1=1");
$db->database_query(); // returns name and description from all rows
$db->database_query(array("*") ); // returns all columns and rows
$db->database_query(array("*"),"id=7"); // returns all columns where id = 7
$other_db = new database("SELECT","my_other_db",$columns,"1=1");
$db->database_query(array("id") ); // calling database_query on first object instance
$other_db->database_query(array("*") ); // calling database_query on second object instance
When using objects/classes you have to remember that you can declare variables which belong to a given instance of the object so you can re
Dunno about you but when I was your age I was writing a fair bit of C, and to get introduced to OO I was described classes as being structs with function pointers inside.
If trying to learn OO I would reccomend taking a look at java since there is a lot of first principals OO stuff out there, then once comfortable with that style of code
taking what you have learned across to the language which you know a bit better (in your case PHP.)
I am having the worst time with this after searching for hours and hours.
My connection to Amazon RDS credentials are correct, however, I cannot pull any data and I get a 500 error from the following.
I've made this in the most raw of coding to avoid any CI mistakes, On my model I have:
class Foreclosure_model extends CI_Model {
public function __construct() {
parent::__construct();
$this->db = $this->load->database('aws');
}
function get_sql_results($state,$county){
return $this->db->query("select State, County from foreclosure_properties where State = 'CA' AND County = 'del norte'");
}
}
Then on my controller I have:
$this->data['listings'] = $this->foreclosure_model->get_sql_results($state,$county);
on my aws connection information I have:
$db['aws']['hostname'] = 'XXXXXXXXXXXXX.us-west-2.rds.amazonaws.com';
$db['aws']['username'] = 'XXXXXXXX';
$db['aws']['password'] = 'XXXXXXXX';
$db['aws']['database'] = 'xxxxxx_xxxxxx';
$db['aws']['dbdriver'] = 'mysql';
$db['aws']['dbprefix'] = '';
$db['aws']['pconnect'] = TRUE;
$db['aws']['db_debug'] = TRUE;
$db['aws']['cache_on'] = FALSE;
$db['aws']['cachedir'] = '';
$db['aws']['char_set'] = 'utf8';
$db['aws']['dbcollat'] = 'utf8_general_ci';
$db['aws']['swap_pre'] = '';
$db['aws']['autoinit'] = TRUE;
$db['aws']['port'] = 3306;
I have tried doing this exact same connection directly with Navicat to test the sql connection and query, it works successfully. I cannot seem to get this to run in Codeigniter.
The result when run on Codeigniter is a 500 error.
Any assistance is greatly appreciated.
As you're using more than one connection, you'll want to pass in a second parameter of 'TRUE' to return the database object.
$this->db = $this->load->database('aws', TRUE);
If you don't pass this, then the database object is not returned and therefor you can't call any of the functions (such as get(), query() etc).
You can read more about multiple connections here:
https://ellislab.com/codeigniter/user-guide/database/connecting.html
Hope this helps - let me know how you get on!
Note: It may be worth mentioning it may make things easier if instead of assigning the database to $this->db, you chose another name such as $this->aws_db as then you're not overwriting the $this->db object for your default database. Probably not a big issue, but may make it easier to troubleshoot as your project grows.
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.
after searching for a long time got this great article its really very nice
but i am facing a bit problem here in my stuff as u have used direct mysql query in api i have used stored procedure in here and every time i have to compare two XML before and after even for a single short and sweet query so is there any alternative for this process but which is this secure
please chk this out u will get i more clearly
database testing in php using phpunit,simpletest on api haveing stored procedure
or how shall i compare to xml files before and after api function call(the function contains the stored procedure)
means i am able to get the before state with mysql-dump but the after but not getting the instant after xml state
sorry for the English but tried my best
thanks for the help friend
have to write an unit test test for the api function
public function delete($userId)
{
// this function calls a stored procedure
$sql = "CALL Delete_User_Details(:userId)";
try {
$db = parent::getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("userId", $userId);
$stmt->execute();
$id = $stmt->fetchObject();
if ($id == null) {
$delete_response->createJSONArray("DATABASE_ERROR",0);
} else {
$delete_response->createJSONArray("SUCCESS",1);
}
} catch (PDOException $e) {
$delete_response->createJSONArray("DATABASE_ERROR",0);
}
return $delete_response->toJSON();
}
i have writen this unit test for it now want to write an dbunit for it
public function testDeleteUser()
{
$decodedResponse = $response->json();
$this->assertEquals($response->getStatusCode(), 200);
$this->assertEquals($decodedResponse['status']['StatusMSG'], 'SUCCESS');
$this->assertEquals($decodedResponse['status']['Code'], '1');
}
help guyss
u can just simply test it before by calling the query like
$sql = "select * from user";
and compare it with BeforeDeleteUser.xml
And the Call Ur stored procedure
$sql = "CALL Delete_User_Details(:userId)";
And for the after case just repeat the before one again
$sql = "select * from user";
and compare it with AfterDeleteUser.xml
see the logic is very simple if u have 5 Users in BeforeDeleteUser.xml and it results true and after the call of CALL Delete_User_Details(:userId) stored procedure , the AfterDeleteUser.xml should contain only 4 user (or maybe idDelete field to 0 that depends on ur implementation)
We are considering the use of Microsoft Dynamics GP 10 Web Services and will want to use PHP to create / update customers and sales... So the question is: Is this possible and if so does anyone know of good documentation out there?
I am not finding anything out there with using PHP, another part of this question would be security credentials and if PHP can correctly pass the needed login and fully interact with GP's web service?
Any ideas or known resources?
For what it's worth, I use a set of stored procedures called eConnect to do GP integrations. It may not be the most elegant solution, but it works fairly good. eConnect is also documented pretty well by Microsoft.
If you choose to use this kind of integration, it is wise to get familiar with the Dexterity Application. Learning the Dexterity Application helps a lot with object and table mappings and it should be a free download from Customer Source.
Here is an example of an eConnect stored procedure to create a customer record:
$sql = "declare #p115 int
set #p115=0
declare #p116 varchar(255)
set #p116=''
exec dbo.taUpdateCreateCustomerRcd
#I_vCUSTNMBR = '123456',
#I_vCUSTNAME = 'Company Name',
#O_iErrorState = #p115 OUTPUT,
#oErrString = #p116 OUTPUT
select #p115, #p116";
To execute it just do something like the following (using PHP ADODB in this example):
gp_execute_sp($sql);
function gp_execute_sp($sql, $transactions = true) {
global $DBGP;
if($transactions)
$DBGP->StartTrans();
$rs = $DBGP->Execute($sql);
if(is_object($rs) && !$rs->EOF) {
if($rs->fields['computed'] != 0) {
if($transactions)
$DBGP->FailTrans();
throw new Exception(get_error_desc($rs->fields['computed']));
}
} elseif(!is_object($rs)) {
if($transactions)
$DBGP->FailTrans();
throw new Exception("Database Connection Error.");
} else {
if($transactions)
$DBGP->FailTrans();
throw new Exception("Stored proceedure did not return a result.");
}
if($transactions)
$DBGP->CompleteTrans();
}
function get_error_desc($value) {
global $DBGP;
if(is_numeric($value)) {
$result = "No Error Available";
$sql = "SELECT ErrorDesc FROM DYNAMICS..taErrorCode WHERE ErrorCode=?";
$rs = $DBGP->execute($sql, array($value));
if(!$rs->EOF) {
$result = $rs->fields['ErrorDesc'];
}
} else {
$result = $value;
}
return $result;
}
I have not yet used Dynamics GP but based on my reding of the developer guide there is a legacy endpoint and a native endpoint but both are SOAP services so I see no reason why you couldn't use PHP's SOAP client.
$client = new SoapClient('http://machine_name:<port_number>/Dynamics/GPService');
$result = $client->GetCompanyList(...);
I do not know what goes at ..., but again there is no reason the above shouldn't be possible since SOAP is designed to work with most languages including PHP, it just won't be as simple as it could be.
EDIT: It may be helpful to use a WSDL to PHP class generator. See: generate php code from wsdl