【问题标题】:Why is my single quotation mark (') not getting encoded?为什么我的单引号 (') 没有被编码?
【发布时间】:2014-10-28 04:35:43
【问题描述】:

我有以下代码将我的 UITextView 文本转换为编码的 NSString,我可以将其与其他内容一起插入到我的数据库中。插入工作得很好,除非有一个单引号......然后它不起作用。当我 NSLog 编码 NSString 时,' 甚至没有转换成任何东西。因此,当它执行 Web 服务器请求时,url 仍然在其中,这导致它失败......为什么单引号没有事先编码?这是我的代码(我也不是很擅长 php):

iOS:

NSString *encodedString = (NSString 
*)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
  NULL, (CFStringRef)self.textView.text,     NULL,  (CFStringRef)@"!*'();:@&=+$,/?%#[]",      kCFStringEncodingUTF8 ));          
  NSString *strURL = [NSString stringWithFormat:@"http://example.org/postText.php?thePost=%@&byUserID=%@&nickname=%@", encodedString, [UniqueUserIdentification getUserID], nickname];

php:

<?php

$con=mysqli_connect("editout","editout","editout","editout");    
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$thePost = $_GET["thePost"];
$byUserID = $_GET["byUserID"];
$nickname = $_GET["nickname"];

mysqli_query($con,"INSERT INTO MyTable
VALUES ('$thePost', '$byUserID', '$nickname', 0, 0)");    
mysqli_close($con);

?>

【问题讨论】:

  • 与其从 iOS 应用程序进行验证,为什么不将其移至 PHP?您也应该准备/执行查询。
  • 尝试在我的 GET 之后添加它,但它仍然不起作用:$thePost = $mysqli->real_escape_string($thePost);
  • 我明白了。谢谢!原来我没有正确更新 php 脚本,所以它甚至没有识别新脚本 XD

标签: php ios mysql objective-c encoding


【解决方案1】:

您的 SQL 错误。

$thePost = $_GET["thePost"];

您将 GET 数据分配给 $thePost,但这是 url 解码的。

例如,$thePost 是“Let's go!”,所以你的 SQL 变成:

INSERT INTO MyTable
VALUES ('Let's go', '$byUserID', '$nickname', 0, 0)"

显然有语法错误。

您需要使用mysqli_real_escape_string 转义字符串。

看看this post

【讨论】:

    【解决方案2】:

    在客户端,它编码为 ' %27,它是正确的。但是在服务端,你的sql用错了。urlencode

    【讨论】:

    • urlencode 仅适用于 url。对于其他领域,它会造成混乱的局面。参数化查询是要走的路。 url 不是他插入的唯一字段。
    • 你看到他的代码了吗,他也编码参数。使用编码结果发布到服务器。服务器代​​码错误。
    • ^他在服务器中收到错误。这告诉你什么?
    • ' 在sql中,它有一定的含义,代表一个字符串引号。所以服务器可以获取值,但是代码:mysqli_query($con,"INSERT INTO MyTable VALUES('$thePost',' $byUserID', '$nickname', 0, 0)");错了。
    • 打印那个 sql ,它可能像这样 INSERT INTO MyTable VALUES(''fdsaf','32','fdsa',0,0) ,它的值中有乘 ',所以数据库会说错。它应该转义 ' 在 sql 字符串中。
    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    相关资源
    最近更新 更多