我有一个 iPhone 应用程序,我想将一些表单数据发送到我的网站(用 PHP 编写)。
//This problem has now been solved. Typo in url.. :(
NSString *urlString = "http://www.mywebsite.com/test.php";
NSUrl *url = [NSURLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *variableToSend = [NSString stringWithFormat:@"name=John"];
//I have assumed that where I write "name=John" that "name" is in Php equal
//to $_POST['name']?, and that "John" is the value of it?
[request setHTTPMethod:@"POST"];
//I don't quite understand these..
[request setValue:[NSString stringWithFormat:@"%d", [variableToSend length]] forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:[variableToSend dataUsingEncoding:NSUTF8StringEncoding]];
(void)[[NSURLConnection alloc] initWithRequest:request delegate:self];
我的 php 文件只是 $name = $_POST['name']; 并将 $name 写入数据库。我创建了一个带有 method="post"、action="" 的 <form>,并带有一个名为“name”的 textField,并且成功了。该值已发送到数据库。
我在很多答案中都看到过这个代码示例,但它确实对我有用。一些我不明白的代码行,所以我相信我如何设置 php 与如何设置代码有问题正在发送变量..有人知道我哪里出错了吗?
(这里的代码现在是手工写的,所以可能有错别字,但一切都在 xcode 中编译,如果我 NSLog(@"%@", request),我得到 "< NSURLConnection: 0x1d342c24>" 什么的.. Don不知道这是否正确..)
编辑
我的 test.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
$connection = mysql_connect("host","un","pw");
if (!$connection){
die('Error: ' . mysql_error());
}
if(isset($_POST['name']))
{
$name = $_POST['name'];
mysql_select_db("db", $connection);
mysql_query("INSERT INTO tablename(Name)
VALUES ('$name')");
mysql_close($connection);
}
?>
</body>
</html>
性病