我有一个SQL数据库,我能够在表视图中拉出并显示。我有一个简单的PHP脚本,用于查询和返回数据库。现在查询变量在PHP文件中是硬编码的,但我需要能够从应用程序修改查询。我相信我需要使用http post请求。
我已经在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文件查询并返回数据库的特定部分。
答案 0 :(得分:0)
所有的帖子数据都可以在$ _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;
有更优雅的做事方式,但这足以满足您现阶段的需求。