Android Question Post Strings to php / sql

Peter Lewis

Active Member
Licensed User
Longtime User
Hi Guys,

I am new to B4A eventhough I have purchased it over 2 years ago and have done all the updates.

The problem I have is trying to get some data from my app to a SQL database.

What I have done so far

Created Database with PHP and HTML file with a form and tested that it updates the Database - Works
Used URL string with data in browser and updates the database - Works

Tried to send the data from my app - Dows not Work - inserts a Blank record.

http://www.himel.co.za/sen_post.php?Barc=LEW901&Location=Durbs&User=Peter (Works)

Here is the code I used. Please if anyone can help point me in the right direction , I am sure it is something very small

Lib enabled are : Core (ver 6.80) and OKHttpUtils2 (ver 2.4)

Thank you in advance

B4X:
#Region  Project Attributes
    #ApplicationLabel: Post Info
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim job2 As HttpJob
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.

End Sub


Sub Activity_Create(FirstTime As Boolean)
    job2.Initialize("Job2", Me)
    job2.PostString("http://www.himel.co.za/sen_post.php","Barc=LEW019&Location=PMB&User=Peter")


End Sub
Sub JobDone (Job As HttpJob)
    Log("JobName = " & Job.JobName & ", Success = " & Job.Success)
    If Job.Success = True Then
            
    Else
        Log("Error: " & Job.ErrorMessage)
        ToastMessageShow("Error: " & Job.ErrorMessage, True)
    End If
    Job.Release
End Sub

[07-Mar-2017 12:51:36 Etc/GMT] PHP Notice: Undefined index: Barc in /home/himelcoz/public_html/sen_post.php on line 11
[07-Mar-2017 12:51:36 Etc/GMT] PHP Notice: Undefined index: Location in /home/himelcoz/public_html/sen_post.php on line 12
[07-Mar-2017 12:51:36 Etc/GMT] PHP Notice: Undefined index: User in /home/himelcoz/public_html/sen_post.php on line 13

are the errors I am getting on the server.

I would have thought it might have been my php code , but then it works using the url string

Change the Barc value to add more to the database or it will reject with a duplicate error
 
Last edited:

Peter Lewis

Active Member
Licensed User
Longtime User
Yes, here it is

I removed the priv info

B4X:
<?php
$servername = "localhost";
$username = "    ";
$password = " ";
$database = "  ";

$value = $_GET['Barc'] ;
$value2 = $_GET['Location'] ;
$value3 = $_GET['User'] ;

// Create connection
$conn = new mysqli($servername, $username, $password , $database);


$sql = "INSERT INTO tracking (barc, location, user)
VALUES ('$value', '$value2', '$value3')";


if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();

?>
 
Last edited:
Upvote 0

Peter Lewis

Active Member
Licensed User
Longtime User
HI

I put in the <code> and the </code>

I read online that is how to use it.

Is that correct ?

I eventually found it is "[ code ]" and "[ /code ] " and repaired the posts.

Thank you
 
Last edited:
Upvote 0

seanfogg

Member
Licensed User
Longtime User
Use my code below to Safely get $_GET and $_POST variables doesn't matter how you call the php file then.

PHP:
<?php

function SafeVar($TheVar,$DefaultVal="") {
    $tmpVal = $_POST[$TheVar];
    if (!$tmpVal) {
        $tmpVal = $_GET[$TheVar];
        if (!$tmpVal) {
            $tmpVal = $DefaultVal;
        }
    }
    return $tmpVal;
}

$value = Safevar("Barc");

?>
 
Upvote 0

Peter Lewis

Active Member
Licensed User
Longtime User

Thank you , I will try it
 
Upvote 0

KMatle

Expert
Licensed User
Longtime User
The name of the method is PostString so everything is sent as one string. Use

B4X:
$json = file_get_contents("php://input");

to get the string's content. Why is the variable called $json?

See this (I'm lazy and came to this code which is always the same in my apps using post methods) Hint: Of course my real code for a login is another (safety). Don't use it 1:1 !

B4X:
    Dim JsonList as List, JsonMap as Map
    JsonList.Initialize
    JsonMap.Initialize
    JsonMap.put("Action", "Login")
    JsonMap.put("username", "Klaus")
    JsonZeileMap.put("pw", "123456")
 
    JsonList.add(JsonMap)

    Dim JSONGenerator As JSONGenerator
    JSONGenerator.Initialize2(JsonList)

    Dim JSONstring As String
    JSONstring = JSONGenerator.ToString
    Log(JSONstring)
 
    Dim LoginJob As HttpJob
         LoginJob.Initialize("LoginJob", Me)
        LoginJob.PostString(Servername & "/login/login.php", JSONstring)

What it does:

- create a simple List (="array")
- create a map
- put each key/value pair in that map
- add the map to the list (there's no limit except the server's config about the max post-size)
- convert the list containing the map to a JSON formatted string

On the PHP side:

B4X:
$json = file_get_contents("php://input");
$jsall = array();
$jsone = array();
$jsall=json_decode($json, true);
$jsone=$jsall[0]; //just for ONE single map
$action = $jsone["Action"];
$username = $jsone["username"];
$pw = $jsone["pw"];

- the string is decoded from a JSON string to an array -> $jsall
- in $jsone put the first array (=our map)
- the single variable can be accessed by it's name (=key)

"Action" is used to identify the function. I use a SWITCH ... CASE ... block later.

Advantage:

- If I need to insert 20 rows in a database I will have a LIST with 20 maps (just fill $jsone in a loop -> $jsall[0] to $jsall[19] in that case)
- as I use one string only, it can be Base64 encoded and/or encrypted, etc.
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…