特殊字符插入DB

时间:2015-11-17 14:26:39

标签: php ios mysql json swift

我在将特殊字符插入数据库时​​遇到问题。例如,如果字符串是“\ kdjfg *&( ^^& %% //”“dfkjs / Z ?!”,那么“\ kdjfg *”将被插入表中.Im不知道为什么在存在特殊字符时没有插入整个字符串

夫特:

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;

1 个答案:

答案 0 :(得分:0)

我不确定这是否是处理特殊字符的正确方法,但这就是我克服目标线的方式。

我使用以下方法填充iOS中的特殊字符:

a.stringByReplacingOccurrencesOfString("&", withString: "(*)*#@#@$#")

然后在php方面,我用&amp;

替换(#@#@ $#
$newString = str_replace("(*)*#@#@$#","&",$a);

我希望其他人能在未来提供更好的方式