private void timer1_Tick(object sender, System.EventArgs e)
{
int iIdx;
int[] iData;
bool[] bData;
if (m_bRegister) // Read registers (4X references)
{
// read register (4X) data from slave
if (adamTCP.Modbus().ReadHoldingRegs(m_iStart, m_iLength, out iData))
{
m_iCount++; // increment the reading counter
txtStatus.Text = "Read registers " + m_iCount.ToString() + " times...";
// update ListView
label1.Text = HttpGet("http://127.0.0.1/misc/api1.php?value0=" + iData[0].ToString());
label2.Text = HttpGet("http://127.0.0.1/misc/api1.php?value1=" + iData[1].ToString());
label3.Text = HttpGet("http://127.0.0.1/misc/api1.php?value2=" + iData[2].ToString());
label4.Text = HttpGet("http://127.0.0.1/misc/api1.php?value3=" + iData[3].ToString());
label5.Text = HttpGet("http://127.0.0.1/misc/api1.php?value4=" + iData[4].ToString());
for (iIdx = 0; iIdx < m_iLength; iIdx++)
{
listViewModbusCur.Items[iIdx].SubItems[2].Text = iData[iIdx].ToString(); // show value in decimal
listViewModbusCur.Items[iIdx].SubItems[3].Text = iData[iIdx].ToString("X04"); // show value in hexdecimal
}
How do i send array using httpget method? The code on top show that i'm sending data one by one. I need to send it in array and retrieve it back in api,php so that i could insert it into database in one row. currently, it's 1 data for 1 row.
Here is a example to convert array to json in PHP
$arr=array(
"varl1"=>1,
"varl2"=>"example",
"varl3"=>3,
);
$json_arr=json_encode($arr);
Now you can send $json_arr
and then you can decode it using json_decode()
you should passing 'value0' become just one querystring, ex : value[]
so the url will become
http://127.0.0.1/misc/api1.php?value[]="+ iData[0].ToString()"&value[]="+ iData[1].ToString() and etc what you want to send it "
or you should use http_build_query to the param array data
the code you show is php ??
the api maybe php but the code style more like .NET c#
correct me if im wrong.
//Update Response
string[] param = new string[(how many your counter param)];
param [0] = "test0";
param [1] = "test1";
param [2] = "test2";
in my example i give you 3
string sParams = JsonConvert.SerializeObject(param) ;
HttpGet("http://127.0.0.1/misc/api1.php?value=" + sParams);
Related
I am posting data from Vb.net client to a PHP rest api but for some reason the json_decode is not working on the passed string.
The code to post to the server is :
Dim payload As String = "{""key"":""Test"",""bookings"":" & txtUpload.Text & "}"
Dim request As WebRequest = WebRequest.Create(String.Format(baseAPIImportUrl))
' Set the Method property of the request to POST.
request.Method = "POST"
' Create POST data and convert it to a byte array.
Dim byteArray() As Byte = Encoding.UTF8.GetBytes(payload)
' Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded"
' Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length
' Get the request stream.
Dim dataStream As Stream = request.GetRequestStream
' Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length)
' Close the Stream object.
dataStream.Close()
' Get the response.
Dim response As WebResponse = request.GetResponse
' Display the status.
MessageBox.Show(CType(response, HttpWebResponse).StatusDescription)
' Get the stream containing content returned by the server.
dataStream = response.GetResponseStream
' Open the stream using a StreamReader for easy access.
Dim reader As StreamReader = New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd
' Display the content.
' Console.WriteLine(responseFromServer)
MessageBox.Show(responseFromServer)
' Clean up the streams.
reader.Close()
dataStream.Close()
response.Close()
The values that are being passed :
{"key":"91a1522Test",
"bookings":
{"booking":[{"ClassId":"4", "ClassName":"THOASC", "YearWeek":"1751"}]} }
On the PHP side I do :
$bookings = $_POST->bookings
$data = json_decode($bookings,true);
$total = count($data['booking']);
The $total should show 1 as there is 1 item in the booking array but it always is shows 0
$_POST->bookings - this is your problem. -> is the object access operator, but in PHP, $_POST is not an object but an array.
If you were submitting this value as part of form data, you would normally access it via array syntax (e.g. $_POST['bookings']), but from your VB code, you're actually posting the JSON string as the POST body itself.
In PHP, you can access the raw POST body like this:
$bookings = file_get_contents('php://input');
The rest of your code should then work as usual.
Edit: actually, you've got a typo in there as well. Try
$total = count($data['bookings']);
// or
$total = count($data['bookings']['booking']);
There is a json array there also. Try this.
<?php
$data='{"key":"91a1522Test",
"bookings":
{"booking":[{"ClassId":"4", "ClassName":"THOASC", "YearWeek":"1751"}]} }';
$data = json_decode($data,true);
echo '<pre>';
print_r($data);
$total = count($data['bookings']['booking']);
echo $total;
$data = json_decode($bookings,true);
Here as per the php documentation sencond argument in json_decode function denotes whether return output as an object or as an array
argument 2 = true ( will return array )
argument 2 = false ( will return object , it is the default value)
The json_decode produces the following array
Array
(
[key] => 91a1522Test
[bookings] => Array
(
[booking] => Array
(
[0] => Array
(
[ClassId] => 4
[ClassName] => THOASC
[YearWeek] => 1751
)
)
)
)
Hence it should be accessed like count($data['bookings']['booking'])
The code below gets all the rows in my Android SQLite database and covert it to JSON Array. Now I want to get the JSON Array using PHP to store it to my online database. What should I do? Please help.
This is the code that I use:
private JSONArray getResults()
{
String myPath = this.getDatabasePath("cart.db").toString();// Set path to your database
String myTable = CartContract.CartEntry.TABLE_NAME;//Set name of your table
SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
String searchQuery = "SELECT * FROM " + myTable;
Cursor cursor = myDataBase.rawQuery(searchQuery, null );
JSONArray resultSet = new JSONArray();
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
for( int i=0 ; i< totalColumn ; i++ )
{
if( cursor.getColumnName(i) != null )
{
try
{
if( cursor.getString(i) != null )
{
Log.d("TAG_NAME", cursor.getString(i) );
rowObject.put(cursor.getColumnName(i) , cursor.getString(i) );
}
else
{
rowObject.put( cursor.getColumnName(i) , "" );
}
}
catch( Exception e )
{
Log.d("TAG_NAME", e.getMessage() );
}
}
}
resultSet.put(rowObject);
cursor.moveToNext();
}
cursor.close();
Log.d("FINAL RESULT", resultSet.toString() );
return resultSet;
}
This is the output:
FINAL RESULT: [{"id":"1","food_id":"52","food_price":"30","food_name":"Pink Lemonade","quantity":"5","amount":"150","special_request":""},{"id":"2","food_id":"51","food_price":"30","food_name":"House Blend Iced Tea","quantity":"3","amount":"90","special_request":""}]
and I want to put these values here: (online database)
attached picture
how should I do that?
UPDATE: I already send the result of my JSONArray and stored it in "$data" but my problem now is how to insert the values to my online database. By the way, in my PHP code, here is where I store the JSONArray as a string:
$data = $_POST["data"];
UPDATE: I already made it! Thanks for noticing and answering my question
I will give you some general guidelines. Sending JSON on HTTP calls can get weird because it can contain characters that are special to HTTP. To get around this, encode the JSON with Base 64 on Android and decode it in PHP.
I assume that you can figure out how to base64 encode with Java.
On PHP, you get back your original JSON.
$originalJson = base64_decode($inputFromAndroid);
$object = json_decode($originalJson, true);
// Now you have the data as a PHP array.
Like we can do easily in php with mysql we execute a query and then run a while loop on that to print all result records of that query. How do we perform this function in vb.net (2008) with ms access db. here is my code which I use for printing now
sql = "SELECT * From Inventory "
Dim da As New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Inventory")
Label1.Text = ds.Tables("Inventory").Rows(0).Item(2)
Label2.Text = ds.Tables("Inventory").Rows(1).Item(2)
Label3.Text = ds.Tables("Inventory").Rows(2).Item(2)
Try this :
Dim rowCount As Integer = ds.Tables('Inventory').Rows.Count
Dim Labels() As Label = {Label1, Label2, Label3}
foreach label As Label In Labels
label.Test = ds.Tables('Inventory').Rows(Array.IndexOf(Labels, label)).Item(2)
Next
Or if you want to get the Labels() array dynamically by getting all the Labels on your form, replace this with Line 2 of the above :
Dim Labels() As Label
For Each ctrl In Form1.Controls
If TypeOf ctrl Is TextBox Then
nextNum = Labels.Length +1
ReDim Preserve Labels(nextNum)
TeamIndex(nextNum) = ctrl
End If
Next
Note: I am limited to PHP <-> VBA. Please do not suggest anything that requires an Excel Addon, or any other language/method.
I have a function that connect to a specified URL, submits data, and then retrieves other data. This works great. I'm trying to write it so i can use it as a generic function I can use to connect to any file I need to connect to - each would return different data (one could be user data, one could be complex calculations etc).
When it retrieves the data from PHP, is there a way to dynamically set the variables based on what is received - even if i do not know what has been received.
I can make PHP return to VBA the string in any format, so I'm using the below as an example:
String that is received in vba:
myValue1=Dave&someOtherValue=Hockey&HockeyDate=Yesterday
If i were to parse this in PHP, I could do something similar to (not accurate, just written for example purposes);
$myData = "myValue1=Dave&someOtherValue=Hockey&HockeyDate=Yesterday"
$myArr = explode("&",$myData)
foreach($myArr as $key => $value){
${$key} = $value;
}
echo $someOtherValue; //Would output to the screen 'Hockey';
I would like to do something similar in VBA. The string I am receiving is from a PHP file, so I can format it any way (json etc etc), I just essentially want to be able to define the VARIABLES when outputting the string from PHP. Is this possible in VBA?.
The current state of the function I have that is working great for connections is as below:-
Function kick_connect(url As String, formdata)
'On Error GoTo connectError
Dim http
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "POST", url, False
http.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
http.send (formdata)
kick_connect = http.responseText
Exit Function
connectError:
kick_connect = False
End Function
Ultimately, I want to be able to do something like
sub mySub
myData = "getId=" & Range("A1").Value
myValue = kick_connect("http://path-to-my-php-file.php",myData)
if myValue = False then
'Handle connection error here
exit sub
end if
'do something snazzy here to split "myValue" string (eg "myValue1=Dave&someOtherValue=Hockey&HockeyDate=Yesterday") into own variables
msgbox(myValue1) 'Should output "Dave"
end sub
Obviously I could put the values into an array, and reference that, however I specifically want to know if this exact thing is possible, to allow for flexibility with the scripts that already exist.
I hope this makes sense, and am really grateful for any replies i get.
Thank you.
You can use a Collection:
Dim Tmp As String
Dim s As String
Dim i As Integer
Dim colVariabili As New Collection
Tmp = "myValue1=Dave&someOtherValue=Hockey&HockeyDate=Yesterday"
Dim FieldStr() As String
Dim FieldSplitStr() As String
FieldStr = Split(Tmp, "&")
For Each xx In FieldStr
FieldSplitStr = Split(xx, "=")
colVariabili.Add FieldSplitStr(1), FieldSplitStr(0)
Next
Debug.Print colVariabili("myValue1")
Debug.Print colVariabili("someOtherValue")
Debug.Print colVariabili("HockeyDate")
It's ok if you don't have the correct sequence of var...
I am not sure if this can help you, but as far as I understand your question you want to be able to create the variables dynamically based on the query string parameters. If so then here is example how to add this variables dynamically. Code needs standard module with a name 'QueryStringVariables'. In this module the query string will be parsed and each query string parameter will be added as get-property. If you wish to be able to change the value as well then you will need to add let-property as well.
Add reference to Microsoft Visual Basic For Applications Extensibility
Option Explicit
Private Const SourceQueryString As String = "myValue1=Dave&someOtherValue=Hockey&HockeyDate=Yesterday"
Sub Test()
Dim queryStringVariablesComponent As VBIDE.vbComponent
Dim queryStringVariablesModule As VBIDE.CodeModule
Dim codeText As String
Dim lineNum As Long: lineNum = 1
Dim lineCount As Long
Set queryStringVariablesComponent = ThisWorkbook.VBProject.VBComponents("QueryStringVariables")
Set queryStringVariablesModule = queryStringVariablesComponent.CodeModule
queryStringVariablesModule.DeleteLines 1, queryStringVariablesModule.CountOfLines
Dim parts
parts = Split(SourceQueryString, "&")
Dim part, variableName, variableValue
For Each part In parts
variableName = Split(part, "=")(0)
variableValue = Split(part, "=")(1)
codeText = "Public Property Get " & variableName & "() As String"
queryStringVariablesModule.InsertLines lineNum, codeText
lineNum = lineNum + 1
codeText = variableName & " = """ & variableValue & ""
queryStringVariablesModule.InsertLines lineNum, codeText
lineNum = lineNum + 1
codeText = "End Property"
queryStringVariablesModule.InsertLines lineNum, codeText
lineNum = lineNum + 1
Next
DisplayIt
End Sub
Sub DisplayIt()
MsgBox myValue1 'Should output "Dave"
End Sub
I am having a problem passing an array variable from Flash (AS2) to PHP. In action script I have several arrays defined like this
output["px1"]
output["px2"]
output["px3"]
and then I use the following code to pass the variables into a php file
output.sendAndLoad("orders/print2cart.php",output,"POST");
I want to know how to get the data from the array in PHP. I have tried using $_POST['px1'], $_POST['output']['px1'], $_POST['output'] but I cannot seem to get any data. Any ideas as to what I can change to get the desired result?
Thanks!
EDIT: Just noticed that I one of the other variables in output (output.username) is also not being sent to PHP, despite it showing up in flash. Using the following code to alert to flash and it does show all the variables correctly.
getURL("javascript:alert('Print Stamp: " + output.PrintStamp + " User: " + output.username "')");
EDIT: Seems like once I send a pretty long array (or a string for that matter) none of the other fields associated with the LoadVars variable are sent either. I googled it up for limits and it says text limits are ~ 63000. Still not sure if that is the problem
Try it as a String.
Use Array.join(); in flash and send the value returned by that, then use explode() in PHP convert it back to an array.
var dataOut:LoadVars = new LoadVars();
var dataIn:LoadVars = new LoadVars();
dataOut.info = your_array.join("#");
vars.sendAndLoad("url", dataIn, "post");
dataIn.onLoad = function(go:Boolean):Void
{
if(go)
{
trace('success');
}
else trace('connection failed');
}
The PHP:
<?php
$str = $_POST["info"];
$myarray = explode($str);
?>
Since there were no other alternatives and I went through a lot of stuff before finally concluding that Arrays of large sizes cannot be passed through from AS2 to PHP very easily. My array was actually an image converted to pixels, so what I did was that I split the array into 2 pieces and posted to the PHP file twice instead of only once. Another alternative would be to split and post the array to a text file first and then read that text file directly from PHP.
You can do the same as you would do with HTML, by naming your parameters "array[0]", "array[1]", etc... :
var urlVariable:URLVariables = new URLVariables();
urlVariable["phpArray[0]"] = "arrayEntry0";
urlVariable["phpArray[1]"] = "arrayEntry1";
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest("http://yourserver.com/phpScript.php");
request.method = URLRequestMethod.POST;
request.data = urlVariable;
loader.load(request);
then serverside you can verify the result received by php script :
print_r($_POST);
it should output :
Array
(
[phpArray] => Array
(
[0] => arrayEntry0
[1] => arrayEntry1
)
)
and for multiple dimension array you can use :
urlVariable["phpArray[0][0]"]