getting data from mysql with php

So I want to get data from MySql I'm using PHP


<?php

// Create connection
$con=mysqli_connect("cantshowthis","hehe","sorry",":c");

// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// This SQL statement selects ALL from the table 'Registro'
$sql = "SELECT * FROM Registro";

// Check if there are results
if ($result = mysqli_query($con, $sql))
{
  // If so, then create a results array and a temporary one
  // to hold the data
  $resultArray = array();
  $tempArray = array();

  // Loop through each row in the result set
  while($row = $result->fetch_object())
  {
  // Add each row into our results array
  $tempArray = $row;
  array_push($resultArray, $tempArray);
  }

  // Finally, encode the array to JSON and output the results
  echo json_encode($resultArray);
}

// Close connections
mysqli_close($con);
?>


So i had multiples issues with Xcode that i don't understand quite well


1.- Ambiguous reference to member 'jsonObject(with:options:)'


This is the part of the code where the user MUST click the button to LOG IN

@IBActionfunc iniciarSesion(_ sender: UIButton) {
      
        if Email.text == "" || Contrasena.text == ""{
            displayAlert(title: "Información Faltante", message: "Debes porporcionar un correo y contraseña")
        }

        let myURL = NSURL(string: "https://cantshowthis.php")
        let request = NSMutableURLRequest(url: myURL! as URL)
        request.httpMethod = "POST"
        let posString = "Correo=\(Email.text)&Password=\(Contrasena.text)"
        request.httpBody = posString.data(using: String.Encoding.utf8)
        let task = URLSession.shared.dataTask(with: request as URLRequest) {
            data, response, error in
           
            if error != nil{
                print("error=\(error)")
                return
            }

            var err : NSError?
            var json = JSONSerialization.jsonObject(with: data, options: .mutableContainers, error: &err) as? NSDictionary
           
            if let parseJSON = json {
                var resultValue:String = parseJSON["status"] as! String!;
                print("message: \(resultValue) ")
               
                if (resultValue == "success")
                {
                   
                    NSUserDefaults.StandarUserDefaults().setBool(true, value(forKey: "isUserLoggedIn"): )
                NSUserDefaults.StandarUserDefaults().synchronize()
               
            }
           
            }
        }
        task.resume()
    }

this is the part where I'm getting the error because is red, I think this is an old version of coding I'm using Xcode 10

var err : NSError?
            var json = JSONSerialization.jsonObject(with: data, options: .mutableContainers, error: &err) as? NSDictionary
            
            if let parseJSON = json {
                var resultValue:String = parseJSON["status"] as! String!;
                print("message: \(resultValue) ")
                
                if (resultValue == "success")
                {
                    
                    NSUserDefaults.StandarUserDefaults().setBool(true, value(forKey: "isUserLoggedIn"): )
                NSUserDefaults.StandarUserDefaults().synchronize()
                
            }
            
            }
        }
        task.resume()

Seems you have dug out an ancient code...


You should have fix many parts other than the lines showing errors, please read my comments in the code:

    @IBAction func iniciarSesion(_ sender: UIButton) {
        
        //### User guard-let when you check sort of required condition
        guard
            let emailText = email.text, !emailText.isEmpty,
            let contrasenaText = contrasena.text, !contrasenaText.isEmpty else
        {
            displayAlert(title: "Información Faltante", message: "Debes porporcionar un correo y contraseña")
            return
        }

        let myURL = URL(string: "...your actual url here...") //### Use `URL` rather than `NSURL`
        var request = URLRequest(url: myURL!) //### Use `URLRequest` as `var` rather than `NSMutableURLRequest`
        request.httpMethod = "POST"
        let posString = "Correo=\(emailText)&Password=\(contrasenaText)" //### You need non-Optional here
        request.httpBody = posString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) {
            data, response, error in
    
            if let error = error {
                print("error=\(error)")
                return
            }
    
            guard let data = data else {
                print("Something wrong")
                return
            }
            //var err : NSError? //### You need do-try-catch instead of declaring a variable of `NSError?`
            do {
                //### No need to specify useless option: `.mutableContainers`
                let json = try JSONSerialization.jsonObject(with: data)
                
                //### Use Swift Dictionary instead of `NSDictionary`
                if let parseJSON = json  as? [String: Any]{
                    guard let resultValue = parseJSON["status"] as? String else {
                        print("No `status` in result")
                        return
                    }
                    print("message: \(resultValue) ")
                    
                    if (resultValue == "success") {
                        //### NSUserDefaults.StandarUserDefaults() has renamed to `UserDefaults.standard`
                        UserDefaults.standard.set(true, forKey: "isUserLoggedIn")
                        UserDefaults.standard.synchronize()
                    } else {
                        //### I'm not sure if you can really ignore non `success` cases
                    }
                } else {
                    //### Generally, you should better not silently ignore errors or invalid data
                    print("Result JSON is ill-formatted:", json)
                }
            } catch let err {
                print(err)
                //### Do something appropriate for JSON parsing errors...
            }
        }
        task.resume()
    }

thx for responding


i'm getting this error



Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}


all code


//
//  ViewController.swift
//  123Taxi
//
//  Created by José Raúl Toledano Rosado on 10/10/18.
//  Copyright © 2018 José Raúl Toledano Rosado. All rights reserved.
//

import UIKit
import Alamofire

class ViewController: UIViewController {

    @IBOutlet var Email: UITextField!
    @IBOutlet var Contrasena: UITextField!
    var iconClick : Bool!
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        iconClick = true
        // Do any additional setup after loading the view, typically from a nib.
    }

    
    @IBAction func verlacontra(_ sender: UIButton) {
        let userPazzword = Contrasena.text!;
        
        if(iconClick == true) {
            Contrasena.isSecureTextEntry = false
            iconClick = false
        } else {
            Contrasena.isSecureTextEntry = true
            iconClick = true
        }
        
    }
    
    
    //func para mostrar alerta si no se introduce nada
    
    @IBAction func iniciarSesion(_ sender: UIButton) {
        
        //### User guard-let when you check sort of required condition
        guard
            let emailText = Email.text, !emailText.isEmpty,
            let contrasenaText = Contrasena.text, !contrasenaText.isEmpty else
        {
            displayAlert(title: "Información Faltante", message: "Debes porporcionar un correo y contraseña")
            return
        }
        
        let myURL = URL(string: "hehe") //### Use `URL` rather than `NSURL`
        var request = URLRequest(url: myURL!) //### Use `URLRequest` as `var` rather than `NSMutableURLRequest`
        request.httpMethod = "POST"
        let posString = "Correo=\(emailText)&Password=\(contrasenaText)" //### You need non-Optional here
        request.httpBody = posString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) {
            data, response, error in
            
            if let error = error {
                print("error=\(error)")
                return
            }
            
            guard let data = data else {
                print("Something wrong")
                return
            }
            //var err : NSError? //### You need do-try-catch instead of declaring a variable of `NSError?`
            do {
                //### No need to specify useless option: `.mutableContainers`
                let json = try JSONSerialization.jsonObject(with: data)
                
                //### Use Swift Dictionary instead of `NSDictionary`
                if let parseJSON = json  as? [String: Any]{
                    guard let resultValue = parseJSON["status"] as? String else {
                        print("No `status` in result")
                        return
                    }
                    print("message: \(resultValue) ")
                    
                    if (resultValue == "success") {
                        //### NSUserDefaults.StandarUserDefaults() has renamed to `UserDefaults.standard`
                        UserDefaults.standard.set(true, forKey: "isUserLoggedIn")
                        UserDefaults.standard.synchronize()
                    } else {
                        //### I'm not sure if you can really ignore non `success` cases
                    }
                } else {
                    //### Generally, you should better not silently ignore errors or invalid data
                    print("Result JSON is ill-formatted:", json)
                }
            } catch let err {
                print(err)
                //### Do something appropriate for JSON parsing errors...
            }
        }
        task.resume()
    }  
    
    func displayAlert (title:String, message:String){
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
        self.present(alertController, animated: true, completion: nil)
        
    }
    
    
    @IBAction func forgotPass(_ sender: UIButton) {
        self.performSegue(withIdentifier: "gotoRecuperacion", sender: nil)
    }
    
    
    @IBAction func crearCuenta(_ sender: UIButton) {
        self.performSegue(withIdentifier: "gotoquieneres", sender: nil)
    }
    
    
    
    
    //funcion para el teclado que regrese
    override func touchesBegan(_ touches: Set, with event: UIEvent?) {
        self.view.endEditing(true)
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }


}



it doesn't matter if the error appears the user just need to tap and try again manually, it doesn't save it either.

sorry i don't understand quite well some of the comments I'm kinda new

The error happens when your PHP server is not generating a valid JSON, which often found in case of server side errors.


Insert this line before your line 73. and see what you get:

print(String(data: data, encoding: .utf8))


sorry i don't understand quite well some of the comments I'm kinda new

If you want to be a programmer, and not to be a c'np-er, you should better try to understand all.

Please show which comment.

this is the error that shows now


Optional("<meta charset=\"UTF-8\">{\"Email\":\"Error\",\"Password\":\"Error\"}\r\n\r\n\r\n")

Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

Optional("<meta charset=\"UTF-8\">{\"Email\":\"Error\",\"Password\":\"Error\"}\r\n\r\n\r\n")

This means your server is sending a response like <meta charset="UTF-8">{"Email":"Error","Password":"Error"}.

It definitely is not a valid JSON, as it starts with `<`.


It's your server side issue. And we are in the Apple's dev forums where we discuss and share experience about Apple's platforms.

I believe this is not a place to discuss how you fix your PHP code. Please fix it by yourself first.

thanks for the help and for encourage me to get better at programming trust me i will get better, I'm just not familiar with JSON and connections with data base.

the problem is the code because PHP is doing what is meant to do, i run a HTML code with open fields and log in successfully, maybe i didn't specifically what I'm running this code for.


what i'm trying to do is


if the user set into this two fields:

@IBOutlet var Email: UITextField!
    @IBOutlet var Contrasena: UITextField!


the JSON code checks into the php and runs into my DB for existance.

I did some research and find that i need to use JSON because my data base is MySql and doing thru PHP


that's why i don't know any of this stuff is kinda confuse for me but i'm trying

if i understood the code, this part is fine

//### User guard-let when you check sort of required condition
        guard
            let emailText = Email.text, !emailText.isEmpty,
            let contrasenaText = Contrasena.text, !contrasenaText.isEmpty else
        {
            displayAlert(title: "Información Faltante", message: "Debes porporcionar un correo y contraseña")
            return
        }
        
        let myURL = URL(string: "hehe") //### Use `URL` rather than `NSURL`
        var request = URLRequest(url: myURL!) //### Use `URLRequest` as `var` rather than `NSMutableURLRequest`
        request.httpMethod = "POST"
        let posString = "Email=\(emailText)&Password=\(contrasenaText)" //### You need non-Optional here
        request.httpBody = posString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) {
            data, response, error in
            
            if let error = error {
                print("error=\(error)")
                return
            }
            
            guard let data = data else {
                print("Something wrong")
                return
            }


because the JSON is connecting to my URL(because i'm getting the error which is set in PHP) but i'm not getting the variable to display it to the console and prepareForSeague to the next module

i might be stuck here

//var err : NSError? //### You need do-try-catch instead of declaring a variable of `NSError?`
            print(String(data: data, encoding: .utf8) as Any)
            do {
                
                let json = try JSONSerialization.jsonObject(with: data)
                
                //### Use Swift Dictionary instead of `NSDictionary`
                if let parseJSON = json  as? [String: Any]{
                    guard let resultValue = parseJSON["status"] as? String else {
                        print("No `status` in result")
                        return
                    }
                    print("message: \(resultValue) ")
                    
                    if (resultValue == "success") {
                        //### NSUserDefaults.StandarUserDefaults() has renamed to `UserDefaults.standard`
                        UserDefaults.standard.set(true, forKey: "isUserLoggedIn")
                        UserDefaults.standard.synchronize()
                    } else {
                        //### I'm not sure if you can really ignore non `success` cases
                    }
                } else {
                    //### Generally, you should better not silently ignore errors or invalid data
                    print("Result JSON is ill-formatted:", json)
                }
            } catch let err {
                print(err)
                //### Do something appropriate for JSON parsing errors...
            }
        }
        task.resume()
    }

I did some research and find that i need to use JSON because my data base is MySql and doing thru PHP


First of all, you must distinguish two things, the data sent from your app to your server, and the data sent to your server to your app.

They are usually referred as request and response respectively.


Second, JSON is just a data format, whether you should use JSON or not depends on what you want to do with the API you are calling.


because the JSON is connecting to my URL(because i'm getting the error which is set in PHP)


Your words does not make sense. You are not using JSON to make request to the server. You are using the data format called application/x-www-form-urlencoded, which is very familiar in PHP world.


but i'm not getting the variable to display it to the console and prepareForSeague to the next module


It's because your PHP server is not sending a valid JSON. Unless you fix your PHP code somewhere in your server, your app may never work. Fix your PHP code first.

you were right the connection was not correctly with my php

but still, keep getting an error it is so frustrating can't find the answer any place

session_start();
error_reporting(0);
echo '<meta charset="UTF-8">';
$host_db = "hehhee";
$user_db = ":C";
$pass_db = "hi";
$db_name = ":D";
$conexion = new mysqli($host_db, $user_db, $pass_db, $db_name);
if ($conexion->connect_error) {
die("La conexion falló: " . $conexion->connect_error);
}

$sql = "SELECT * FROM Usuarios where Correo = '".$_POST['Email']."' and Password = '".$_POST['Password']."'";
$result = $conexion->query($sql);
if ($result->num_rows > 0) {
$row = mysqli_fetch_array($result);

$response['Email'] = $row['Correo'];
$response['Password'] = $row['Password'];
}
else
{
$response['Email'] = 'Error';
$response['Password'] = 'Error';
}
echo json_encode($response);
mysqli_close($conexion);
?>

the data string was being created by

echo '';


so I deleted it and now this is what it shows


Optional("{\"Email\":\"jose.luar.1211@hotmail.com\",\"Password\":\"hi123\"}\r\n\r\n\r\n")

No `status` in result


and already update the data for preparesegue if the parse is correctly


if (resultValue == "success") {
                        //### NSUserDefaults.StandarUserDefaults() has renamed to `UserDefaults.standard`
                        UserDefaults.standard.set(true, forKey: "isUserLoggedIn")
                        UserDefaults.standard.synchronize()
                        self.performSegue(withIdentifier: "logeadoSegue", sender: nil) //segueForSucess
                    } else {
                        //### I'm not sure if you can really ignore non `success` cases
                    }
                } else {
                    //### Generally, you should better not silently ignore errors or invalid data
                    print("Result JSON is ill-formatted:", json)
                }
Accepted Answer

No `status` in result

Then your PHP server is not sending `status`. Fix your PHP server first.

getting data from mysql with php
 
 
Q