Send data from VBA (excel) to php and vice versa - php

Basically I want to communicate with a MYSQL server using php as the middle-ware.
I cannot connect directly to the database due to drivers needing to be installed and our IT will not allow drivers to be installed on our company computers.
I understand how to insert data using vba ->php->mysql but I cannot figure out how to get data from mysql to excel. vba->php->mysql->php->vba.
I want to do a query and send the results to vba excel.
Here is the VBA Code that works but it also sends multiple spaces back as well. Im not sure if this is the correct way to do this.
Private Sub ExtractPHP()
Dim item As String
Dim objHTTP As Object
Dim URL As String
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
URL = "http://localhost/php/requestdata.php"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencode"
objHTTP.send ("")
Worksheets("hiddendata").Range("k4").Value = Replace(objHTTP.responseText, " ", "")
End Sub
The PHP code is as follows.
<?php
$con = mysqli_connect("localhost","root","","php") or die("Connection was not created!");
$select = "select name FROM users where id=5";
$run = mysqli_query($con,$select);
$value = mysqli_fetch_array($run);
$result = $value["name"];
echo $result;
?>
Result that is placed in the excel file has multiple spaces below the text. Is this the correct way to communicate between excel and mysql?

I am not sure about the VBA method and what exactly you need to do but one solution would be to write requestdata.php to parse the result of your query into a .csv file and then load that into Excel via VBA. Parsing the result array into the .csv plain text format is made even more trivial by the fact that PHP already has a function fputcsv($file, $records) to use (documentation).

i can help you 10% cause i programming in several languages but nothing vba/excell .I programming in php too...anyway my answer for you is :
Let say you create in C: a new folder and you create a runme.bat file there.
Using one methods to run a external .bat file and to grab external result from that runme.bat more or less like in
Execute a command in command prompt using excel VBA
Wait for shell command to complete
you can use like me a method to run from that batch php cli:
you can drop runme.php in that folder as well:
<?php
if(isset($argv[1])){
echo($argv[1]);
//here you can drop some mysql
}
?>
then you should understand how to reconfiger php ini to connect to mysql ,some problems you can dare are
PHP: mysql_connect() won't work via command line
if you put a command like this one i already check via windows cmd and works
c:\xampp\php>php "c:\test\runme.php" yep2
and you are getting "yep2"
as c:\test\ 's runme.bat version :
rem #echo off
set parameter=%1
set PHP_BIN="c:\xampp\php\php.exe"
set script=%cd%\runme.php
%PHP_BIN% %script% %parameter%
and for test we call it in cmd : runme yep2
with the result: yep2
then with the batch modiffied you can fill data in mysql let's say you will call that not runme.php but putmysqldata.php .
at this point creating another file php to read from mysql (even you use only one file php to write or read by calling it by different parameter) so you will be able to read from mysql
so isn't easy if you don't know much vba or how to do it.
following these steps i think if you know some vba more than me you can figure out the shortest way.

Related

Python json.load() doesn't work in PHP exec()

I have a python script that I wish to run from PHP using the exec() function. What the Python script does is it gets some data from a web API, stores the data in temporary files, then reads the files and puts some data in a csv file. The script runs fine when I test it alone. Now, I want to run it through exec(). When I first tried, I thought that the script wasn't running at all, but then I looked a bi further and realized that the script WAS in fact running, but stopped somewhere during the execution.
I then tried to redirect the output to a txt file with > output.txt to see where it went wrong. When I checked in the file and debugged a bit, I realized that the problem was the function json.load() in my Python script. The strange thing is that in the output.txt file, there is no error message displayed.
Here is what the output.txt file looks like.
And here is the python function that contains json.load().
def get_json_files_data(path, min = 1):
json_files = find_files(path, "json", min)
json_data = dict()
print("===========================================")
print("= Converting JSON data into Python object =")
print("===========================================")
for file in json_files:
base = os.path.basename(file) # name with extension (ex. 'file.json')
id = os.path.splitext(base)[0] # name without extension (ex. 'file') in this case, the names are the trip ids
opened_file = open(file)
print(10)
json_data[id] = json.load(opened_file) # get the json data as a python dict
print(11)
return json_data
I also tried to change the permission of the json files to 777, but that doesn't resolve the problem.
Does anyone have any idea? Let me know if any more code is needed.
Thanks a lot
I finally managed to make it work. Here's the solution if anyone is wondering.
The problem was the encoding. It was somehow different depending on how I was running the script. What I did was simply to specified the encoding with encoding='utf-8'. Here's what my code looks like now.
def get_json_files_data(path, min = 1):
json_files = find_files(path, "json", min)
json_data = dict()
print("===========================================")
print("= Converting JSON data into Python object =")
print("===========================================")
for file in json_files:
base = os.path.basename(file) # name with extension (ex. 'file.json')
id = os.path.splitext(base)[0] # name without extension (ex. 'file') in this case, the names are the trip ids
with open(file, 'r', encoding='utf-8') as opened_file:
json_data[id] = json.load(opened_file) # get the json data as a python dict
return json_data

Start with Couchbase N1QL query in xampp

I was trying to query data from Couchbase server using PHP and N1QL. Please see the code below.
<?php
$cluster = new CouchbaseCluster('127.0.0.1:8091');
$bucket = $cluster->openBucket('travel-sample');
$q = CouchbaseN1qlQuery::fromString("SELECT * FROM `travel-sample`")->consistency(CouchbaseN1qlQuery::REQUEST_PLUS);
$res = $bucket->query($q);
var_dump($res);
?>
Unfortunately, this return NULL. I am usinf Couchbase server 3.0 and PHP SDK. Cam someone help me to correct my N1QL query ?
Regards,
Tismon Varghese
First of all, i was using Couchbase 3.0, so i'm suppose to use N1QL DP3. So i downloaded DP3 from the below URL
https://s3.amazonaws.com/query-dp3/couchbase-query_dev_preview3_x86_win.zip
Extract it, put it on the directory where Couchbase installed (This is not necessary i guess). Extracted directory contains two directories; data and static in addition to a start_turotial.bat and some other files.
Since the .bat file is connected to data directory, we have to change this to get data from Couchbase server. For that, do the following.
Take a backup of the .bat file; right click on it and select 'edit'
change the line cbq-engine -couchbase dir:data to cbq-engine -couchbase http://127.0.0.1:8091/ and save it
Double click on the bat file so that a console window will be popped up (This should be open as long as the query runs). I addition to this, a webpage also opens automatically in your browser; if not, follow the instruction on the popped console window.
..and you are good to go!!!
Regards,
Tismon Varghese.

JSON.php decode behavior different between servers

I have the following problem : On my local development server PHP 5.3.10 / Apache 2 every things goes right. When I run the same code with the production server PHP Version 5.2.13 / Apache 2 the code fail but on certain conditions not always.
More details :
The context : I have a dojox.data.grid table on the screen that can be updated. The modified data is correctly passed to the server as a JSON string. Like this :
data = {
"deletedItems":{}
,"newItems":{}
,"modifiedItems":{
"2890":{"idFacture":"2890"
,"idClient":"175"
,"idAffaire":"1323"
,"idContrat":"2234"
,"raisonSociale":"xxxxxx"
,"nomAffaire":"xxxxxx"
,"nrFacture":"xxxxx"
,"dateFacture":"2012-12-06"
,"montantFacture":"160000.00"
,"pourcentageFacture":"64.88"
,"pourcentageCalcule":"32.44"
,"noteFacture":""
,"dateTransfert":""
,"aTransferer":true
,"typeDocument":"Facture"
,"factureSoldee":false
,"montantTotalHeures":"0.00"
,"pourcentageTotalHeures":"0.00"
,"montantTotalMateriel":"0.00"
,"pourcentageTotalMateriel":"0.00"
,"montantTotalSousTraitance":"160000.00"
,"pourcentageTotalSousTraitance":"40.94"
}
,"2892":{"idFacture":"2892"
,"idClient":"50"
,"idAffaire":"1649"
,"idContrat":"2713"
,"raisonSociale":"xxxxx"
,"nomAffaire":"xxxxx"
,"nrFacture":"xxxxx"
,"dateFacture":"2012-12-07"
,"montantFacture":"12004.50"
,"pourcentageFacture":"0.00"
,"pourcentageCalcule":"41.94"
,"noteFacture":""
,"dateTransfert":""
,"aTransferer":true
,"typeDocument":"Facture"
,"factureSoldee":false
,"montantTotalHeures":"12004.50"
,"pourcentageTotalHeures":"41.95"
,"montantTotalMateriel":"0.00"
,"pourcentageTotalMateriel":"0.00"
,"montantTotalSousTraitance":"0.00"
,"pourcentageTotalSousTraitance":"0.00"
}
}
}
You can see that the data contains three elements "deletedItems" (empty), "createdItems" (empty) and "modifiedItems".
In the php code i have the following commands :
$srvJson = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
$data = $srvJson->decode($data);
Where $data is filled like above. Normally after that last statement the folowing PHP variables are set :
$data["deletedItems"]
$data["createdItems"]
$data["modifiedItems"]
Here is the problem : if on the production server there are a lot of modified rows (about > 30) in the table, the modified data is correctly passed to the serveur BUT $data["modifiedItems"] is not set ??? If I just modify the dataset for a few rows $data["modifiedItems"] is well set.
I can modify the whole data set piece per piece, but not the whole dataset in one time.
I suppose this is a question of server settings but what ?
I would appreciate any suggestion.
Best regards,
Roger
PS : Sorry for my english
Since it is not valid JSON (checked with http://jsonlint.com/) the results of json_decode() in PHP 5.3.10 and PHP 5.2.13 are different!
While 5.3 returns nothing 5.2.13 returns the initial string. Probably your code has somewhere some error corrections...
See the different results of the different PHP version on 3v4l.org!
When us remove data = from your JSON does not throw errors..
Based on your above issue, you can check following things on server
magic_quotes are open or closed on server similiar to local server
Does Services_JSON is compitable to PHP 5.3
Services_JSON is pear php library so please check that it is working properly with all extension of php
http://pear.php.net/bugs/search.php?cmd=display&package_name%5B%5D=Services_JSON
Or you can use the default php json library for encode and decode
May this will help you

Get windows title using php doesn't work on browser call

My problem is I need to fetch FOOBAR2000's title because that including information of playing file, so I create a execute file via Win32 API(GetWindowText(), EnumWindows()) and it's working good.
TCHAR SearchText[MAX_LOADSTRING] = _T("foobar2000");
BOOL CALLBACK WorkerProc(HWND hwnd, LPARAM lParam)
{
TCHAR buffer[MAX_TITLESTRING];
GetWindowText(hwnd, buffer, MAX_TITLESTRING);
if(_tcsstr(buffer, SearchText))
{
// find it output something
}
return TRUE;
}
EnumWindows(WorkerProc, NULL);
Output would look like "album artis title .... [foobar2000 v1.1.5]"
I created a php file like test.php, and use exec() to execute it.
exec("foobar.exe");
then in console(cmd) I use command to execute it
php test.php
It's working good too, same output like before.
Now I use browser(firefox) to call this php file(test.php), strange things happened.
The output only foobar2000 v1.1.5, others information gone ...
I think maybe is exec() problem? priority or some limitation, so I use C# to create a COM Object and register it, and rewrite php code
$mydll = new COM("FOOBAR_COMObject.FOOBAR_Class");
echo $mydll->GetFooBarTitle();
still same result, command line OK, but browser Fail.
My question is
Why have 2 different output between command line and browser. I can't figure it out.
How can I get correct output via browser.
or there is a easy way to fetch FOOBAR2000's title?
Does anyone have experience on this problem?
== 2012/11/28 edited ==
follow Enno's opinion, I modify http_control plug-in to add filename info, original json info is "track title".
modify as following
state.cpp line 380 add 1 line
+pb_helper1 = pfc::string_filename(pb_item_ptr->get_path());
pb_helper1x = xml_friendly_string(pb_helper1);
# 1: when firefox opens the php and it gets executed, it the context depends on the user which runs the php-container (apache), this is quite different from the commandline call which gets executed in your context
# 2 and 3: there seems to be more than one way for getting the title: use the foobar-sdk and create a module which simply reads the current title per api, then write your result in an static-html-document inside your http-root-folder OR use the http-client inside the sdk, with it, you do not need a wabserver, even better use a already implemented module: for instance foo_upnp or foo-httpcontrol
Good luck!
If your webserver runs as a service, in windows you need to enable "allow desktop interaction" for the service. Your php script runs as a child of the webserver process when requested via browser.

writing a structured ini file from scratch via PhP

Im creating a picture viewer for a friend of mine but i am unable to use a database because his hosting doesn't allow one.
So im left trying to use ini files but i dont know how to write a structured ini file using php..i have successfully put together a script to read it via parse_ini_file() and break it down into it seperate categories and keys but i need to know how to write the acctuall structure if there isn't one already.
For example
[flowerpics]
picone = filelocation
pictwo = filelocation
[artpics]
picone = filelocation
this is how im basing my parse_ini_file() script for ...so what if he wants to add a whole new category to this file ..lets say he wants to add "Rockandrollpics" ...how can i go about adding that into an ini file?
If I were you, I would consider using some standard - like JSON, YAML, or even BJSON - it's almost as simple as INI files, but gives you more control about structuring the data. Your example with JSON:
"flowerpics"
{
"picone" : "filelocation";
"pictwo" : "filelocation";
}
"artpics"
{
"picone" : "filelocation";
}
If you don't use Mysql you can try to use SqlLite instead of.
You needn't anything except php extension sqllite.
Look at http://php.net/manual/en/book.sqlite.php for more info.

Categories