我有一个获取位置的工作代码。
我想存储来自文本字段的值(我暂时将其保留为 NULL)、我的经度、纬度和时间戳。
这是我将它发送到我的 php 文件的代码
NSString *latitude = [NSString stringWithFormat:@"%f", newLocation.coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:@"%f", newLocation.coordinate.longitude];
NSString *stringFromDate = [formatter stringFromDate:newLocation.timestamp];
NSMutableURLRequest *request =
[[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:@"http://www.yourdomain.com/locatie.php"]];
[request setHTTPMethod:@"POST"];
NSString* postString = [NSString stringWithFormat:@"%@ %@ %@", latitude, longitude, stringFromDate];
[request setValue:[NSString
stringWithFormat:@"%d", [postString length]] forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:[postString
dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
这是我的 PHP 文件中的代码。
<?php
// Connecting, selecting database
$id = $POST['id'];
$longitude = $POST['longitude'];
$latitude = $POST['latitude'];
$timestamp = $POST['stringFromDate'];
$link = mysql_connect('server', 'name', 'pass')
or die('Could not connect: ' . mysql_error());
mysql_select_db('db_name') or die('Could not select database');
// Performing SQL query
$query("INSERT INTO locatie (id, longitude, latitude, timestamp)
VALUES (NULL, $longitude,$latitude,$timestamp )");
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
echo "OK";
// Free resultset
mysql_free_result($result);
// Closing connection
mysql_close($link);
?>
我做错了什么? 感谢所有帮助。
谢谢
PS:我没有收到任何错误,唯一的问题是我的数据库保持为空
还是不行,如果有人知道我做错了什么,拜托
最佳答案
除了有关 $_POST
全局变量的其他答案外,我相信您在尝试构建查询字符串时有 2 个 PHP 错误。
您没有将查询字符串正确分配给 $query 变量。您应该使用等号将字符串分配给 $query PHP 变量。例如:
$query = "INSERT INTO ..."
您需要使用句点 (
.
) 将 PHP 变量($longitude、$latitude、$timestamp)连接到您正在构建的查询字符串中,这是 PHP 连接运算符.连接允许 PHP 动态构建字符串。$query = "INSERT INTO locatie (id, longitude, latitude, timestamp) VALUES (NULL," . $longitude . "," . $latitude . "," .$timestamp." )";
根据 $timestamp 字符串的格式和表中的数据类型,您可能需要将其用单引号引起来。 "'"。 $时间戳。 “'”
。获取 $longtitude、$latitude、$timestamp 的一些示例数据,并尝试在 phpMyAdmin 或您使用的任何数据库工具中编写 SQL 语句,以查看是否需要引号。
此外,还应解决前面提到的 SQL 注入(inject)问题。您没有清理从 $_POST 全局变量分配给 $longitude、$latitude、$timestamp PHP 变量的字符串。您将它们直接传递给 MySQL。如果字符串中存在恶意语句,这就是您可能会遇到麻烦的地方。
关于php - 从带有 PHP 的 ios 到 mySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12248744/