Android Question [SOLVED] Upload imag along with other fields

jroriz

Active Member
Licensed User
Longtime User
I'm trying to upload items stored in a customlistview.
One of these items is a photo.
Everything works fine as long as there is no photo to send.
The php code is lost when the base64 string whith the photo goes with it.
If I just send the photo, it works.
But I need to send the photo along with other fields.
Maybe using multipart, but I couldn't find a way to do that.

PHP ERROR: "SQLSTATE[HY093]: Invalid parameter number: mixed named and positional parameters"

B4X:
    Dim Cursor As Cursor
    Cursor = Main.SQL1.ExecQuery($"Select id, usuario, data, Cliente,
            Unidade, ciclo, area, subarea, formulario, peca, grupo, pergunta, resposta, foto
            FROM inspecao
            where coalesce(status, '') <> 'enviado' order by id"$)
    
    Dim data As String = "?"
    
    For i = 0 To Cursor.RowCount - 1
        Cursor.Position = i

        For y = 0 To Cursor.ColumnCount -1
            Dim coluna As String = Cursor.GetColumnName(y)
            
            data = data & coluna & "="
            
            If coluna = "foto" Then
                
                If Cursor.GetString(coluna) <> Null Then
                    Dim bmp As Bitmap = LoadBitmapResize(File.DirRootExternal, Cursor.GetString(coluna), 100dip, 100dip, True)
                
                    Dim ImageBytes() As Byte = func.BitmapToBytes(bmp)
    
                    Dim Base64String As String
                    Base64String = BytesToString(ImageBytes, 0, ImageBytes.Length, "UTF8")

                    data = data &  Base64String  & "&"
                Else
                    data = data & "&"
                End If
                
            Else
                data = data & Cursor.GetString(coluna) & "&"
            End If
            
'            Log(data)
        Next

        Dim jg As HttpJob
        jg.Initialize("", Me)

        jg.PostString(Main.URLServidor & "/app/receber.php", $"data=${data}"$)

        Wait For (jg) JobDone (jg As HttpJob)
    
        If jg.Success Then
        
            Log(jg.GetString)

        Else
            func.msg("erro 132 " & jg.ErrorMessage)
        End If

        jg.Release


    Next

PHP:
<?php

require '../inc/conexao.php';

$data = json_decode($_POST['data']);

$ix = 0;
$ult = '';

foreach ($data->root as $item) {

    // Inicialize um array vazio
    $reg = [];
    $ret = '';

    // Percorra as chaves e valores de $item
    foreach ($item as $key => $value) {

        if ($key == 'peca' and $value != $ult) {
            $ix++;
            $ult = $value;
        }
        // Adicione o valor ao array $reg usando a chave como nome do campo
        if ($key != 'id') {
            $reg[$key] = $value;
        } else {
            $ret = $ret . $value . ' ';
        }   // devolver os ids incluidos para excluir no celular
    }

    // Insira o registro no banco de dados
    inserir($reg);
}

die("$ix inspeções gravadas com sucesso.");

function inserir($data)
{
    global $database;

    // Prepare a SQL statement
    $columns = implode(", ", array_keys($data));
    $values = ":" . implode(", :", array_keys($data));
    $sql = "INSERT INTO inspecao ($columns) VALUES ($values)";

    // Prepare and execute the query
    $stmt = $database->prepare($sql);
    foreach ($data as $key => $value) {
        $stmt->bindValue(":$key", $value);
    }
    $stmt->execute();
}
 

drgottjr

Expert
Licensed User
Longtime User
the error you show refers to an sql issue, not to an upload (POST) problem.

the second sql query you show:
$sql = "INSERT INTO inspecao ($columns) VALUES ($values)";
would seem to be the one throwing the error. unless there are other queries we cannot see.
you should log $columns and $values to see if they match in number. the php error says they do not
 
Upvote 0

jroriz

Active Member
Licensed User
Longtime User
in line 27 (data = data & Base64String & "&"), if I switch from base64string (byte string) to any string (let's say "foo"), it works like a charm.
The problem is with the file that I'm trying to upload.
But searching the forum I can see I'm using the wrong aproach...
 
Upvote 0

jroriz

Active Member
Licensed User
Longtime User
Tottaly wrong aproach...
I changed the code using multipart and everything is fine now. Easier, by the way.
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…