0

amigos.

Estoy empezando con Swift y pretendo rellenar mediante el método POST mi BBDD y lamentablemente no sé dónde estoy cometiendo el error, o en el php o en el swift. BBDD Mysql.

Codigo PHP

if(isset($_POST["Name"])){

    $Name=         ( empty($_POST['Name']) )             ?  NULL  : $_POST['Name'];
    $Room=         ( empty($_POST['Room']) )             ?  ""    : $_POST['Room'];
    $Teacher_Name= ( empty($_POST['Teacher_Name']) )     ?  ""    : $_POST['Teacher_Name'];


    if ($name){

        if( $conexion=mysqli_connect($hostname,$username,$password,$database) ){

            $sql= "INSERT INTO classes(Name,Room,Teacher_Name) VALUES (?,?,?)";


            if ($stmt = mysqli_prepare($conexion, $sql)) {

                mysqli_stmt_bind_param($stmt,"sss",$Name,$Room,$Teacher_Name);

                if( mysqli_stmt_execute($stmt) ) {
                    //$msg=printf("Insert", mysqli_stmt_affected_rows($stmt));
                    $msg=printf("");
                }else{
                    //$msg=printf("Error: %s ejecutando la consulta", mysqli_stmt_error($stmt));
                    $msg=printf("Account already exists");
                }

                mysqli_stmt_close($stmt);

            }else{
                $msg=printf("Error: %s preparando la consulta", mysqli_error($conexion));
            }

            mysqli_close($conexion);

        }else{
            $msg=printf("Error de conexión: %s", mysqli_connect_error());
        }

    }else{
        $msg="El nombre estaba vacío";  
    }
    //Envia un numero de error al final
    //echo $msg;

}

Codigo Swift

@IBAction func onPostTapped(_ sender: Any) {

    let parameters = ["Name": "Orlando", "Room": "RDR", "Teacher_Name": "Tea Lopez"]

    guard let url = URL(string: "http://zrerdo.com/Arcmmetry/postClasses.php") else {return}
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return }

    request.httpBody = httpBody

    let session = URLSession.shared
    //usar Data URLRequest
    session.dataTask(with: request ) { (data, response, error) in

        if let response = response {
            print(response)
        }

        if let data = data {
            do {
                //Elegimos jsonObject InputStream
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)
            }
            catch{
                print(error)
            }
        }

    }.resume()
}

Muchas gracias por adelantado.

2 respuestas 2

2

Por si te sirve de orientación, yo lo hago con PHP utilizando PDO de la siguiente manera:

Código PHP:

<?php 

//Completar con tus datos estas variables:
//DB_HOST 
//DB_NAME
//DB_USER
//DB_PASSWORD 

try{

$str_conn="mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=utf8";

$dbh = new PDO($str_conn, DB_USER, DB_PASSWORD);

}catch(PDOException $ex){
        echo 'Error al conectar a la BBDD. '.$ex->getMessage();
        die();
}

$usuario = $_REQUEST['usuario'];
$nombre = $_REQUEST['nombre'];

if (isset($usuario)){

$res=$dbh->prepare('insert into sis_registros (id_usuario, nombre) VALUES (:usuario, :nombre);');

$res->execute(array(':usuario' => $usuario, ':nombre' => $nombre));

// Cerramos la conexión y limpiamos las variables implicadas
$res->closeCursor();
$res = null;
$str_conn = null; 
$dbh = null;


} //fin del IF

?>

Y luego, desde una función Swift, inserto así los datos:

Código Swift3:

@IBAction func btn_enviar(_ sender: Any) {


    //crea NSURL
    let requestURL = URL(string: "https://localhost/pruebas/inserta_solicitud.php")

    //crea NSMutableURLRequest
    let request = NSMutableURLRequest(url: requestURL! as URL)

    //configura el método de envío
    request.httpMethod = "POST";

    //variables obtenidas de los campos de texto

    let usuarioD = usuario.text!
    let nombreD = nombre.text!


    //parámetros a enviar
    let postParameters = "usuario="+usuarioD+"&nombre="+nombreD;

    //agrega los parámetros a la petición
    request.httpBody = postParameters.data(using: String.Encoding.utf8)


    //crea una tarea que envía la petición post
    let task = URLSession.shared.dataTask(with:request as URLRequest){
        data, response, error in

        //si ocurre algún error sale
        if error != nil{
            print("Error")
            return;
        }            

    }
    //ejecuta la tarea
    task.resume()

}

Suerte!

1

Mira yo ago asi las peticiones post, si te sirve de guia, y para poder ayudarte con tu php necesito puedas probarlo con postman o algo asi para ver si si hace la insercion o ver el error que genera.

func post(){

        let postString = "email=\(email)&&password=\(password)&&device_type=ios&&device_token=\(token!)&&login_by=manual";
        //K.LOGIN = Ruta a hacer el post
        AuthProvider.Instance.callApi(postString, Route: K.LOGIN) { res in

            print(res)
            }
}
1
  • Muchas gracias me a servido muchos.
    – Fulano
    el 1 feb. 2019 a las 1:59

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.