【问题标题】:HTTP Post to PHP file to query database and return array based on query. SwiftHTTP Post 到 PHP 文件以查询数据库并根据查询返回数组。迅速
【发布时间】:2015-11-26 05:25:48
【问题描述】:

我有一个 SQL 数据库,我可以将其拉取并显示在表格视图中。我有一个简单的 PHP 脚本来查询并返回数据库。现在查询变量在 PHP 文件中是硬编码的,但我需要能够从应用程序修改查询。我相信我需要为此使用 http 发布请求。

我已经在下面发布了 PHP 文件和视图控制器文件的全部内容。

首先是 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);
?>

现在是 swift 文件。

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

    }
}

所以基本上,我想发送一个查询变量来进行 PHP 文件查询并返回数据库的特定部分。

【问题讨论】:

  • 实际上,我检查了您的代码,您的 PHP 部分似乎还不错。究竟什么不起作用?您是否将数据接收到 $_REQUEST 中?
  • 我认为我的 Swift 方面可能是错误的。看看我说的部分 // 这是我的尝试。
  • 你应该使用下面的代码来看看你到底收到了什么
  • 我尝试了这两种方法,但我看不到任何结果。从 Xcode 我在控制台中得到以下内容,这是 'response' response = Optional( { URL: localhost:8888/service.php } { status code: 200, headers { Connection = "Keep-Alive" ;“内容长度”= 325;“内容类型”=“文本/html;字符集=UTF-8”;日期=“格林威治标准时间 2015 年 9 月 1 日星期二 12:59:14”;“保持活动”=“ timeout=5, max=98"; 服务器 = "Apache/2.2.29 (Unix) mod_fastcgi/2.4.6 mod_wsgi/3.4 Python/2.7.8 PHP/5.6.2 mod_ssl/2.2.29 OpenSSL/0.9.8zg DAV/ 2……等
  • 实际上你应该打开与你的 php 文件相同级别的 log.txt 以查看你的应用程序发送了哪些数据。你能把输出粘贴到这里吗?

标签: php sql swift


【解决方案1】:

在 PHP 中,所有的发布数据都可以在 $_POST 超级变量中找到。 在您的应用中,您发送的是"user_id_app=9"

在 PHP 中你应该有:

<?php
echo $_POST['user_id_app'];
// output 9

由于您的脚本中没有针对 sql 注入的保护,我强烈建议您转换数据:

<?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;

有更优雅的做事方式,但这应该足以满足您现阶段的需要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多