I am fetching data from mysql and php with alamofire data is encoded in json which is fetching fine in response now i want to decode and display in tableview how to parse data and display in tableview i have search many examples but not found my solution how to decode and display data in tableview.
<?php
if($_SERVER['REQUEST_METHOD'] == "GET")
{
$conn = mysqli_connect("localhost","id15123058_root2","Ioscrud/12345","id15123058_imageupload");
$query = mysqli_query($conn,"SELECT * FROM `ioscrud`");
while($fetch = mysqli_fetch_array($query))
{
$temp[] = $fetch;
}
$json['jobs'] = $temp;
$jsonformat = json_encode($json);
echo ($jsonformat);
}
?>
This is my php code
import UIKit
class Product:Decodable
{
var name:String
var email:String
var password:String
init(name:String,email:String,password:String) {
self.name = name
self.email = email
self.password = password
}
}
This is class
import UIKit
import Alamofire
class TableViewController: UITableViewController {
#IBOutlet var tableview: UITableView!
var product = [Product]()
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
// MARK: - Table view data source
// override func numberOfSections(in tableView: UITableView) -> Int {
// // #warning Incomplete implementation, return the number of sections
// return product.count
// }
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return product.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
let url = "https://jobportal475.000webhostapp.com/IosCrud/viewData.php"
AF.request(url,method: .get).response
{response in
debugPrint(response)
if response.data != nil
{
debugPrint(response)
}
}
cell.nameLabel.text = product[indexPath.row].name
cell.emailLabel.text = product[indexPath.row].email
cell.passwordLabel.text = product[indexPath.row].password
return cell
}
}
There is library for directions you can use it if you want
https://github.com/akexorcist/GoogleDirectionLibrary
Or you can use this
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?
saddr="+latitude_cur+","+longitude_cur+"&daddr="+latitude+","+longitude));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory(Intent.CATEGORY_LAUNCHER );
intent.setClassName("com.google.android.apps.maps",
"com.google.android.maps.MapsActivity");
startActivity(intent)
Related
I get the data from JSON and also can show it in UITableView, but can I show the data where id is = 1 for example? just like SQL? Thanks for help in advance. Here is my code. I have 2 TableViews, first one holds 3 users and the 2nd one should have that user Information, but when I click on one user it shows all the information from all users.
import UIKit
struct User: Codable {
let firstName: String
let lastName: String
let email: String
let userid: String
enum CodingKeys: String, CodingKey {
case firstName = "first_name"
case lastName = "last_name"
case email = "email"
case userid = "user_id"
}
}
class tableViewCellLabels: UITableViewCell {
#IBOutlet var lbl_firstName: UILabel!
#IBOutlet var lbl_lastName: UILabel!
#IBOutlet var lbl_email: UILabel!
#IBOutlet var lbl_userid: UILabel!
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableview1: UITableView!
#IBOutlet var tableview2: UITableView!
private var dataSource = [User]() {
didSet {
self.tableview1.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableview1.dataSource = self
self.tableview1.delegate = self
let url = URL(string: "https://test.netperformers.de/users")
URLSession.shared.dataTask(with: url!, completionHandler: { [weak self] (data, response, error) in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "An error occurred")
return
}
DispatchQueue.main.async {
self?.dataSource = try! JSONDecoder().decode([User].self, from: data)
}
}).resume()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableview1.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == tableView{
print(dataSource[indexPath.row]) // your clicked user data
}else{
// Second Tableview Click Event here
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "groupCell", for: indexPath) as! tableViewCellLabels
let user = self.dataSource[indexPath.row]
cell.lbl_firstName.text = user.firstName
cell.lbl_lastName.text = user.lastName
cell.lbl_userid.text = user.userid
return cell
}
func tableView1(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == tableView{
print(dataSource[indexPath.row]) // your clicked user data
}else{
// Second Tableview Click Event here
}
}
}
You do not need a 2nd UITableVIew to show a single User, its not the correct purpose of this ui control, instead you can do one of followings:
Show UIAlertController with the user information
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let user = self.dataSource[indexPath.row]
let alertController = UIAlertController(title: user.firstName + " " + user.lastName, message: user.email, preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default)
alertController.addAction(action)
self.present(alertController, animated: true, completion: nil)
}
Create a UIViewController to have a UI that matches your needs, following is a basic example
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let user = self.dataSource[indexPath.row]
let userVC = UserViewController(user: user)
self.navigationController?.pushViewController(userVC, animated: true)
}
class UserViewController: UIViewController {
private let user: User
init(user: User) {
self.user = user
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
let nameLabel = UILabel()
nameLabel.text = self.user.firstName + " " + self.user.lastName
nameLabel.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(nameLabel)
let emailLabel = UILabel()
emailLabel.text = self.user.email
emailLabel.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(emailLabel)
let safeAreaGuide = self.view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
nameLabel.topAnchor.constraint(equalTo: safeAreaGuide.topAnchor, constant: 16.0),
nameLabel.leadingAnchor.constraint(equalTo: safeAreaGuide.leadingAnchor, constant: 16.0),
nameLabel.trailingAnchor.constraint(equalTo: safeAreaGuide.trailingAnchor, constant: 16.0),
emailLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 8.0),
emailLabel.leadingAnchor.constraint(equalTo: safeAreaGuide.leadingAnchor, constant: 16.0),
emailLabel.trailingAnchor.constraint(equalTo: safeAreaGuide.trailingAnchor, constant: 16.0)
])
}
}
If you just need a specific user you can filter the dataSource like this:
dataSource.first(where: { $0.userid == "1" })
Make use of section Header. So all section headers will list the users. In cell for row for each section you can show the information for that particular user. Also you can manage the height of the row for managing the show hide functionality.
Let me know if this helps.
You can do it with a filter array before reloading the tableview.
private var dataSource = [User]() {
didSet {
dataSource = dataSource.filter({ (item) -> Bool in
return item.userid == "3" // put your filter query here
})
self.tableview.reloadData()
}
}
Click Event
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == YourFirstTable {
print(dataSource[indexPath.row]) // your clicked user data
} else {
// Second Tableview Click Event here
}
}
I used PHP api to get data from server. I created an array on AddCircleVC()
var CircleArray: [String] = []
When i login then server returns some circle names and that name i stored in this array like below:
if let UserArray = (json as AnyObject).object(forKey: "data") as? NSArray
{
for UserDic in UserArray
{
if let circlename = (UserDic as AnyObject).object(forKey: "circleName") as? String
{
print("CircleName: \(circlename)")
self.key.CircleArray.append(circlename)
print("CircleArray: \(self.key.CircleArray)")
UserDefaults.standard.set(self.key.CircleArray, forKey: "CircleArr")
continue
}
}
}
I want to show in these circle names in MenuVC(). So i used below code:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0
{
print("CircleNumber:\(key.CircleArray.count)")
if self.expandCell
{
return ((self.selIndexPath) != nil) ? 1 : key.CircleArray.count
}
else
{
return key.CircleArray.count
}
}
else if section == 1
{
return 7
}
else
{
return 0
}
}
But every time when i login it prints circle number 0. How to show all circle names on MenuVC().
There is some ambiguity in your code thats why might I am wrong but what I understand is that you get JSON array in AddCircleVC and you want to show that JSON array in MenuVC.
So when you save all circlename in array. Simply pass this array to MenuVC like I have shown you in code given below.
And you always get circle number 0 because in MenuVC self.key.CircleArray is empty.
class AddCircleVC : UIViewController {
var CircleArray: [String] = []
func buttonLogin() {
parseJSON()
let menuVC : MenuVC // Create Object of MenuVC
menuVC.menuVcDataSource = CircleArray
/// push MenuVC
}
func parseJSON() {
if let UserArray = (json as AnyObject).object(forKey: "data") as? NSArray
{
for UserDic in UserArray
{
if let circlename = (UserDic as AnyObject).object(forKey: "circleName") as? String
{
print("CircleName: \(circlename)")
self.key.CircleArray.append(circlename)
print("CircleArray: \(self.key.CircleArray)")
UserDefaults.standard.set(self.key.CircleArray, forKey: "CircleArr")
continue
}
}
}
}
}
class MenuVC : UIViewController {
var menuVcDataSource : [String] = []
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0
{
print("CircleNumber:\(menuVcDataSource.count)")
if self.expandCell
{
return ((self.selIndexPath) != nil) ? 1 : menuVcDataSource.count
}
else
{
return menuVcDataSource.count
}
}
else if section == 1
{
return 7
}
else
{
return 0
}
}
}
My question is, how to fetch data from PHP into UIPickerView in Swift 3.0 ?
Currently, I have these code for UIPickerView to create dropdown list. Right now, I can only display the dropdown list value based on variable declare inside xcode var department = ["ICTD","FAD","PSD"]
dropdown.swift
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
#IBOutlet var departmentLbl: UITextField!
#IBOutlet var dropdownLbl: UIPickerView!
#IBOutlet var outputLbl: UILabel!
#IBOutlet var user_idLbl: UILabel!
var department = ["ICTD","FAD","PSD"]
var user_id: String!
override func viewDidLoad() {
super.viewDidLoad()
user_id = "ID001" // these value that need to be past to PHP
let url = URL(string: "http://localhost/getdepartment.php")
let session = URLSession.shared
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST"
let LoginDataToPost = "user_id=\(user_id!)"
request.httpBody = LoginDataToPost.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
if error != nil { return }
else {
do {
if let json = try JSONSerialization.jsonObject(with: data!) as? [String: String] {
DispatchQueue.main.async {
let display = Int(json["display"]!)
let realname = json["real_name"]
let department = json["dept"]
if(display == 1) {
// dropdown list value display here
return
}
else { return }
}
}
else { }
}
catch {}
}
})
task.resume()
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
var countrows : Int = department.count
if pickerView == dropdownLbl {
countrows = self.department.count
}
return countrows
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == dropdownLbl {
let titleRow = department[row]
return titleRow
}
return ""
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == dropdownLbl {
self.departmentLbl.text = self.department[row]
self.dropdownLbl.isHidden = true
}
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if (textField == self.departmentLbl) {
self.dropdownLbl.isHidden = false
}
}
}
And I have these PHP code that gives an output of
real name and department
based on user_id value from x code
getdepartment.php
<?php
$connect = mysqli_connect("","","","");
global $connect;
if (isset($_POST['user_id'])) {
$user_id = $_POST['user_id'];
$sql = "SELECT * FROM table WHERE user_id ='$user_id'";
$result = mysqli_query($connect,$sql);
if($result && mysqli_num_rows($result)>0){
while ($row = mysqli_fetch_array($result)) {
$real_namedb = $row['real_name'];
$dept_db = $row['dept'];
$output = array('real_name' => $real_namedb, 'dept' => $dept_db);
echo json_encode($output);
}
mysqli_free_result($result);
}
else { }
}
?>
These PHP gives an output of JSON data as below:
{"display":"1","real_name":"NAME TEST 1","dept":"ICTD"}
{"display":"1","real_name":"NAME TEST 2","dept":"ICTD"}
Appreciate if someone can help.
Thanks.
I believe you are supposed to create the dropdownlist based on values you received from server. Based on the code you've given in the question, I observed that you were not adding department names you got from the server to your array.
You can make following changes and observe:
if let json = try JSONSerialization.jsonObject(with: data!) as? [String: String]
{
DispatchQueue.main.async
{
let display = Int(json["display"]!)
let realname = json["real_name"]
let departmentName = json["dept"]
if(display == 1) {
// dropdown list value display here
self.department.append(departmentName)
self.dropdownLbl.reloadAllComponents() // this is reference to your pickerView. Make it global and use it
return
}else { return }
}
}
Please let me know if it resolves the problem or not...
I been trying to implement a Pull to Refresh to my tableview to refresh JSON Data from server. On what I have tried on the debug Area screen it shows me the data reloads but the Cell labels and images doesn't refresh when I make changes on the PHP file on server .... I'M USING THE CODE BELOW:
import UIKit
class JSONData: UITableViewController {
var newsList = [News]()
override func viewDidLoad() {
super.viewDidLoad()
self.loadJSONDATA()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return newsList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! NewsStrings
let s = newsList[indexPath.row] as News
cell.labellName.text = s.newsName
cell.labelDesc.text = s.newsDesc
cell.labelDate.text = s.newsDate
cell.imgvImage.image = UIImage(named: "BgIcon.jpg")
if let img = UIImage(data: s.newsImage)
{
cell.imgvImage.image = img
}else
{
self.loadImages(s, indexPath: indexPath)
}
return cell
}
///////////////// JSON DATA ////////////////////////
func loadJSONDATA()
{
let urlString = "http://example.com/folder/JSON.php"
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config, delegate:nil, delegateQueue: nil)
if let url = NSURL(string: urlString)
{
let request = NSURLRequest(URL: url)
let taskData = session.dataTaskWithRequest(request, completionHandler: {
(data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
if (data != nil)
{
var parseError:NSError?
let parsedNews = (try! NSJSONSerialization.JSONObjectWithData(data!, options: [])) as! NSDictionary
//print("JSON Data \n \(parsedNews)")
if let news:AnyObject = parsedNews["News"]
{
self.parseJSON(news)
}
} else
{
}
})
taskData.resume()
}
}
/////////// LODING JSON DATA //////////////
func parseJSON(jsonData:AnyObject)
{
if let newsData = jsonData as? [[NSObject:AnyObject]]
{
var news:News
for s in newsData {
news = News()
if let sId:AnyObject = s["NewsID"]
{
if let NewsID = sId as? String
{
print("News id = \(NewsID)")
}
}
if let sn:AnyObject = s["newsName"]
{
if let newsName = sn as? String
{
news.newsName = newsName
//println("Store id = \(storeName)")
}
}
if let sn:AnyObject = s["newsDate"]
{
if let newsDate = sn as? String
{
news.newsDate = newsDate
//println("Store id = \(storeName)")
}
}
if let sn:AnyObject = s["newsIcon"]
{
if let newsIcon = sn as? String
{
news.newsImageName = newsIcon
//println("News Icon = \(newsIcon)")
}
}
if let sn:AnyObject = s["newsDesc"]
{
if let newsIcon = sn as? String
{
news.newsDesc = newsIcon
}
}
newsList += [news]
}
NSOperationQueue.mainQueue().addOperationWithBlock(){
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
self.tableView.reloadData()
}
}
}
/////////// LODING IMAGES FROM JSON DATA //////////////
func loadImages(news:News, indexPath:NSIndexPath)
{
let urlString = news.newsImageName
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config, delegate:nil, delegateQueue: nil)
if let url = NSURL(string: urlString)
{
let request = NSURLRequest(URL: url)
let taskData = session.dataTaskWithRequest(request, completionHandler: {
(data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
if (data != nil)
{
news.newsImage = data!
let image = UIImage(data: data!)
dispatch_async(dispatch_get_main_queue(),{
if let cell = self.tableView.cellForRowAtIndexPath(indexPath) as? NewsStrings {
cell.imgvImage.image = image
}
})
} else
{
}
})
taskData.resume()
}
}
}
You can add pull to refresh within your table view like below code,
var refreshControl = UIRefreshControl()
In view did load,
self.refreshControl.addTarget(self, action: Selector("loadJSONDATA"), forControlEvents: UIControlEvents.ValueChanged)
self.addSubview(self.refreshControl) // OR self.myTable?.addSubview(self.refreshControl)
Then add this line after self.parseJSON(news)
self.refreshControl.endRefreshing()
This will be help full to you. :)
I got something to make it work, this is what I have on my viewDidLoad:
self.refreshControl?.addTarget(self, action: #selector(NewsList.handleRefresh(_:)), forControlEvents: UIControlEvents.ValueChanged)
The Function for the handleRefresh:
func handleRefresh(refreshControl: UIRefreshControl) {
newsList.removeAll() //<-This clear the whole tableview(labels, images,ect...)making table view blank
if self.refreshControl!.refreshing
{
self.loadRecords() //<-Reloads All data & labels
self.refreshControl!.endRefreshing()
}
}
The only thing is that the app crashes after doing the "Pull to refresh" multiples
I have a SQL database that I have been able to pull and display in a table view. I have a simple PHP script that queries and returns the database. Right now the query variables are hard coded in the PHP file but I need to be able to modify the query from the app. I believe I need to use http post requests for this.
I have posted below the PHP file and the view controller file in their entirety.
First the PHP.
<?php
$config = parse_ini_file("config_files/config.ini");
// Create connection
$con=mysqli_connect("localhost",$config["username"],$config["password"],$config["dbname"]);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This added as my attempt to do POST. Before I just had 9 in the query where I have the variable $user_id_app_sent_int.
$user_id_app_sent = $_REQUEST['user_id_app'];
// I did this (int) conversion because I think it is receiving form the app as a string?
$user_id_app_sent_int = (int)$user_id_app_sent;
$sql = "SELECT * FROM `invoice` WHERE `user_id` = $user_id_app_sent_int";
// 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);
?>
Now for the swift file.
import UIKit
class InvoiceListViewController: UIViewController, UITableViewDelegate {
// Custom Variable
var invoiceData = [NSDictionary]()
var arrayCount = Int()
// Table View Outlet
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// This is the main pull data section.
let url = NSURL(string: "http://localhost:8888/service.php")!
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in
// This is my attempt.
let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:8888/service.php")!)
request.HTTPMethod = "POST"
let postString = "user_id_app=9"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
print("response = \(response)")
}
task.resume()
// end post test attempt. If this section is removed, and I return the hardcoded value to the PHP file, it works fine for pulling and displaying the database data.
if let invoiceWebData = data{ // Open if let
do {
let invoiceDataPulled = try NSJSONSerialization.JSONObjectWithData(invoiceWebData, options: NSJSONReadingOptions.MutableContainers) as! [NSDictionary]
self.invoiceData = invoiceDataPulled
self.arrayCount = self.invoiceData.count
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
} // Close Do
catch {
print("JSON Serialization Failed")
}
} // Close If Let
} // Close Task
task.resume()
} // Close View Did Load
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(invoiceData)
return arrayCount
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("invoiceCell") as! InvoiceCell
let row = indexPath.row
let rowData: NSDictionary = invoiceData[row]
let userLogIn: String? = (rowData["user_id"] as? String)
if let logInUnwrapped = userLogIn {
cell.cellNameLabel.text = logInUnwrapped
}
return cell
}
}
So basically, I want to send a query variable to make the PHP file query and return specific portions of the database.
in PHP all the post data is to be found in the $_POST super variable.
In your app you are sending "user_id_app=9".
In PHP you should then have:
<?php
echo $_POST['user_id_app'];
// output 9
Since there is no protection against sql injections in your script I strongly advise you to cast the data:
<?php
// if user_id_app received by post, cast value to integer otherwise default to 0
$user_id_app = isset($_POST['user_id_app']) ? intval($_POST['user_id_app']): 0;
There are more elegant ways of doing things but this should be enough for your need at this stage.