PHP和MySQL的问题

编程入门 行业动态 更新时间:2024-10-28 04:24:56
本文介绍了PHP和MySQL的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在Xcode中工作,并有一个iOS应用程序,您输入信息,应用程序通过PHP文件连接到数据库。上传时没有问题,名称或电子邮件地址。但是由于某种原因,当通过 UITextView 上传大量文本时,会出现问题。当没有标点符号时,它成功。但是当有一个句点或一个问号,它不会上传到服务器,它只是失败。但是使用电子邮件字段,当涉及句点或甚至 @ 符号时没有问题。我不熟练的PHP或MySQL后端的东西,所以我很困惑。这是php文件的代码:

if(isset($ _GET [firstName])&& ($ _GET [lastName])&&& amp; isset($ _ GET [emailAddress])&&&&&> )&&&& isset($ _ GET [iosVersion])){ $ firstName = $ _GET [firstName]; $ lastName = $ _GET [lastName]; $ emailAddress = $ _GET [emailAddress]; $ deviceType = $ _GET [deviceType]; $ problemTextField = $ _GET [problemTextField]; $ iosVersion = $ _GET [iosVersion]; } else { $ firstName =用户名; $ lastName =用户姓氏; $ emailAddress =用户电子邮件地址; $ deviceType =用户设备类型; $ problemTextField =用户问题文本字段; $ iosVersion =User ios version; } $ con = mysql_connect($ DB_HostName,$ DB_User,$ DB_Pass)或die(mysql_error mysql_select_db($ DB_Name,$ con)或die(mysql_error()); $ sql =insert into $ DB_Table(firstName,lastName,emailAddress,deviceType,problemTextField,iosVersion,Status,Second_Status)values('$ firstName','$ lastName',' $ emailAddress','$ deviceType','$ problemTextField','$ iosVersion','Unanswered','Answered'); $ res = mysql_query($ sql,$ con)或die(mysql_error()); mysql_close($ con); if($ res){ echosuccess; } else { echofailed; }

像我说的,我不会流利的PHP,拉开我的PHP文件的语法。

编辑:经过一整天的调试,我意识到,如果我把字之间的空格,一切都很好。有什么原因吗?我不想把加号放在一切之间,我知道这是不正确的。

这是我的Xcode代码:

NSString * strURL = NSString stringWithFormat:@www.website/phpFile.php?firstName=%@&lastName=%@&emailAddress=%@&deviceType=%@&problemTextField=%@&iosVersion =%@,firstName.text,lastName.text,emailAddress.text,deviceType.text,self.problemTextBox.text,iosVersion.text]; //执行php代码 NSData * dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]]; //接收returend值 NSString * strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];` pre>

解决方案

有几点意见:

  • 您说:

    但是当有一个句点或问号时,服务器,它只是失败。

    您的问题假设问题在于PHP代码,但它听起来像你可能不会正确百分比在创建请求时转义参数。值得注意的是,许多人错误地使用 stringByAddingPercentEscapesUsingEncoding (这将百分比转义一些字符,而不是其他字符)。值得注意的是,有一些合法字符在URL中有效,但在POST / GET参数中无效,因此您需要指定那些应该被百分比转义的合法字符(例如

    >

    总之,你真的想使用 CFURLCreateStringByAddingPercentEscapes ,它允许你指定每个 RFC 3986 。例如,我使用了以下 NSString 类别。

    @实现NSString(URLEncode) - (NSString *)stringForHTTPRequest { return CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)self, NULL, (CFStringRef)@:/?@!$&'()* +,; =, kCFStringEncodingUTF8) } @end

    a href =github/AFNetworking/AFNetworking =nofollow> AFNetworking ,这简化了创建请求的过程,并为您照顾。

  • 注意,这个PHP代码返回简单的字符串响应。相反,我建议创建JSON响应,这将使得Objective-C代码更容易处理和解释响应(并报告/记录错误)。例如,如果使用mysqli的过程表示:

    <?php //指定这将返回JSON 头('Content-type:application / json'); //打开数据库 $ con = mysqli_connect(localhost,user,password,database); //检查连接 if(mysqli_connect_errno()) { echo json_encode(array(success=> false,message => mysqli_connect_error(),sqlerrno=> mysqli_connect_errno())); exit; } //获取参数 $ field1 = mysqli_real_escape_string($ con,$ _REQUEST [field1]); $ field2 = mysqli_real_escape_string($ con,$ _REQUEST [field2]); //执行插入 $ sql =INSERT INTO sometable(field1,field2)VALUES('{$ field1}','{$ field2}') ; if(!mysqli_query($ con,$ sql)) { $ response = array(success=> false,message=> mysqli_error $ con),sqlerrno=> mysqli_errno($ con),sqlstate=> mysqli_sqlstate($ con)); } else { $ response = array(success=> true); } echo json_encode($ response); mysqli_close($ con); ?>

    或者,如果使用面向对象的样式:

    <?php header('Content-type:application / json'); $ mysqli = new mysqli(localhost,user,password,database); //检查连接 if($ mysqli-> connect_errno){ echo json_encode(array(success=> false,message => $ mysqli-> connect_error,sqlerrno=> $ mysqli-> connect_errno)); exit(); } //执行插入 $ sql =INSERT INTO sometable(field1,field2)VALUES(?,?); if($ stmt = $ mysqli-> prepare($ sql)){ $ stmt-> bind_param(ss,$ _REQUEST [field1],$ _REQUEST [field2]); if(!$ stmt-> execute()) $ response = array(success=> false,message=> $ mysqli-> sqlerrno=> $ mysqli-> errno,sqlstate=> $ mysqli-> sqlstate); else $ response = array(success=> true); $ stmt-> close(); } else { $ response = array(success=> false,message=> $ mysqli->错误,sqlerrno=> $ mysqli-& sqlstate=> $ mysqli-> sqlstate); } $ mysqli-> close(); echo json_encode($ response); ?>

    这样,Objective-C应用程序可以接收响应,解析JSON, code> success 以确定操作是否成功,如果错误消息不成功,请查看消息 。

  • 顺便说一句,我建议你使用 mysqli_real_escape_string

    code>或手动将参数绑定到预准备的语句,以防止SQL注入攻击或您的SQL中未转义字符串产生的意外错误。

  • d还建议您创建一个 POST 请求,而不是允许更大值的 GET 请求。

  • I am working within Xcode and have an iOS application that you input information and the app connects to a DB via a PHP file. There is no problem when uploading, a name or an email address. But for some reason when it comes to uploading a good amount of text, via a UITextView, there becomes a problem. It succeeds when there are no punctuation at all. But when there is a period, or a question mark, it does not get uploaded to the server, it just fails. But with the email field, there is no problem when it comes to periods or even that @ symbol. I am not fluent in PHP or MySQL backend stuff, so I am very confused. Here is the code for the php file:

    if (isset ($_GET["firstName"]) && isset($_GET["lastName"]) && isset($_GET["emailAddress"]) && isset($_GET["deviceType"]) && isset($_GET["problemTextField"]) && isset($_GET["iosVersion"])){ $firstName = $_GET["firstName"]; $lastName = $_GET["lastName"]; $emailAddress = $_GET["emailAddress"]; $deviceType = $_GET["deviceType"]; $problemTextField = $_GET["problemTextField"]; $iosVersion = $_GET["iosVersion"]; } else { $firstName = "User first name"; $lastName = "User last name"; $emailAddress = "User email address"; $deviceType = "User device type"; $problemTextField = "User problem text field"; $iosVersion = "User ios version"; } $con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error()); mysql_select_db($DB_Name,$con) or die(mysql_error()); $sql = "insert into $DB_Table (firstName, lastName, emailAddress, deviceType, problemTextField, iosVersion, Status, Second_Status) values('$firstName','$lastName', '$emailAddress','$deviceType','$problemTextField','$iosVersion', 'Unanswered', 'Answered')"; $res = mysql_query($sql,$con) or die(mysql_error()); mysql_close($con); if ($res) { echo "success"; }else{ echo "failed"; }

    Like I said, I am not fluent in PHP, so please be nice when pulling apart my syntax for the PHP file.

    EDIT: After a whole day of debugging, I have realized that if I take away spaces from in between words, everything is fine. Is there a reason for this? I don't want to have to put plus's in between everything, I know that is not correct.

    Here is my Xcode code:

    NSString *strURL = [NSString stringWithFormat:@"www.website/phpFile.php?firstName=%@&lastName=%@&emailAddress=%@&deviceType=%@&problemTextField=%@&iosVersion=%@", firstName.text, lastName.text, emailAddress.text, deviceType.text, self.problemTextBox.text, iosVersion.text]; // to execute php code NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]]; // to receive the returend value NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];`

    解决方案

    A couple of observations:

  • You said:

    But when there is a period, or a question mark, it does not get uploaded to the server, it just fails.

    Your question presumes that the problem rests in the PHP code, but it sounds like you might not properly be percent escaping the parameters when creating the request. Notably, many people erroneously use stringByAddingPercentEscapesUsingEncoding (which will percent escape some characters, but not others). Notably, there are "legal" characters that are valid in a URL, but are not valid within a POST/GET parameter, so you need to specify those "legal" characters that should also be percent escaped (e.g. ?, &, +, etc.) within a parameter.

    In short, you really want to use CFURLCreateStringByAddingPercentEscapes, which allows you to specify additional characters that should be escaped per RFC 3986. For example, I've used the following NSString category.

    @implementation NSString (URLEncode) - (NSString *)stringForHTTPRequest { return CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, NULL, (CFStringRef)@":/?@!$&'()*+,;=", kCFStringEncodingUTF8)); } @end

    Or use a framework like AFNetworking which simplifies the process of creating requests and takes care of this for you.

  • Note, this PHP code is returning simple string response. Instead, I'd suggest creating JSON response, which will make it easier for the Objective-C code to handle and interpret the response (and report/log the error). For example, if using the procedural rendition of mysqli:

    <?php // specify that this will return JSON header('Content-type: application/json'); // open database $con = mysqli_connect("localhost","user","password","database"); // Check connection if (mysqli_connect_errno()) { echo json_encode(array("success" => false, "message" => mysqli_connect_error(), "sqlerrno" => mysqli_connect_errno())); exit; } // get the parameters $field1 = mysqli_real_escape_string($con, $_REQUEST["field1"]); $field2 = mysqli_real_escape_string($con, $_REQUEST["field2"]); // perform the insert $sql = "INSERT INTO sometable (field1, field2) VALUES ('{$field1}', '{$field2}')"; if (!mysqli_query($con, $sql)) { $response = array("success" => false, "message" => mysqli_error($con), "sqlerrno" => mysqli_errno($con), "sqlstate" => mysqli_sqlstate($con)); } else { $response = array("success" => true); } echo json_encode($response); mysqli_close($con); ?>

    Or, if using the object-oriented style:

    <?php header('Content-type: application/json'); $mysqli = new mysqli("localhost", "user", "password", "database"); // check connection if ($mysqli->connect_errno) { echo json_encode(array("success" => false, "message" => $mysqli->connect_error, "sqlerrno" => $mysqli->connect_errno)); exit(); } // perform the insert $sql = "INSERT INTO sometable (field1, field2) VALUES (?, ?)"; if ($stmt = $mysqli->prepare($sql)) { $stmt->bind_param("ss", $_REQUEST["field1"], $_REQUEST["field2"]); if (!$stmt->execute()) $response = array("success" => false, "message" => $mysqli->error, "sqlerrno" => $mysqli->errno, "sqlstate" => $mysqli->sqlstate); else $response = array("success" => true); $stmt->close(); } else { $response = array("success" => false, "message" => $mysqli->error, "sqlerrno" => $mysqli->errno, "sqlstate" => $mysqli->sqlstate); } $mysqli->close(); echo json_encode($response); ?>

    This way, the Objective-C app can receive the response, parse the JSON, and look at success to determine whether the operation was successful or not, and look at message for the error message if it wasn't successful. This just permits a more robust conversation between app and server.

  • By the way, I'd suggest that you use mysqli_real_escape_string or manually bind parameters to a prepared statement to protect against SQL injection attacks or unintended errors arising from unescaped strings in your SQL.

  • I'd also suggest you create a POST request rather than a GET request which allows larger values.

  • 更多推荐

    PHP和MySQL的问题

    本文发布于:2023-11-22 03:03:50,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1615728.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:PHP   MySQL

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!