在数据库中插入特殊字符时遇到问题。例如,如果字符串是"''kdjfg*&(^^&%%//"dfkjs/Z?!",则会将"''kdj2fg*"插入到表中。我不确定当存在特殊字符时,为什么不插入整个字符串
Swift:
let post:NSString = "a='(a)&b='(b)&c='(c)&d='(d)&username='(username)";
let url:NSURL = NSURL(string:PassURL)!
let postData = post.dataUsingEncoding(NSUTF8StringEncoding)!
let postLength = String(postData.length)
//Setting up `request` is similar to using NSURLConnection
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) {urlData, response, reponseError in
if let receivedData = urlData {
let res = response as! NSHTTPURLResponse!;
NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300) {
do {
let jsonData = try NSJSONSerialization.JSONObjectWithData(receivedData, options: []) as! NSDictionary
//On success, invoke `completion` with passing jsonData.
completion(jsonData: jsonData, error: nil)
} catch {
//On error, invoke `completion` with NSError.
completion(jsonData: nil, error: nil)
} }
else
{
completion(jsonData: nil, error: nil)
}
}
}
task.resume()
}
php:
header('Content-type: application/json');
if($_POST) {
$username = $_POST['username'];
$a = $_POST['a'];
$b = $_POST['b'];
$c = $_POST['c'];
$d = $_POST['d'];
$mysqli = new mysqli($server_url, $db_user, $db_password, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
} else {
$stmt = $mysqli->prepare("insert into testTable (a,b,c,d,postedby) VALUES (?,?,?,?,?)");
$stmt->bind_param("sssss",$a,$b,$c,$d,$username);
$stmt->execute();
$success = $stmt->affected_rows;
$id = $stmt->insert_id;
我不确定这是否是处理特殊字符的正确方式,但这就是我越过目标线的方式。
我在iOS中填充了特殊字符,使用:
a.stringByReplacingOccurrencesOfString("&", withString: "(*)*#@#@$#")
然后在php端,我用&
$newString = str_replace("(*)*#@#@$#","&",$a);
我希望其他人能在未来提供更好的