简体   繁体   English

使用PDO for PHP Xcode将数据插入MySQL

[英]Inserting Data to MySQL using PDO for PHP Xcode

I am really struggling trying to understand why the below code does not insert the date I am sending? 我真的很难理解为什么下面的代码没有插入我发送的日期?

<?php
$servername = "servername";
$username = "username";
$password = "passwrd";
$dbname = "dbname";


$conn  = new PDO ("mysql:host=$servername;dbname=$dbname", $username, $password); 
$conn ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$Name = $_POST['Name'];
$Last = $_POST['Last'];
$email = $_POST['email'];
$pwd = $_POST['pwd'];
$userID = $_POST['userID'];

$sql = "INSERT INTO Users (Name, Last, email, password, userID) VALUES (:var1, :var2, :var3, :var4, :var5) "; 

$q = $conn -> prepare($sql);

$q -> execute (array(':var1' => $Name,
               ':var2' => $Last,
               ':var3' => $email,
               ':var4' => $pwd,
               ':var5' => $userID));

?>

If instead of 如果不是

$Name = $_POST['Name']; 

and so on ... I hard code the values, so I might have: 等等......我对这些值进行硬编码,所以我可能会:

$Name = 'Jane';

It adds the data to the database, but with $_POST, it fails at the execute line. 它将数据添加到数据库,但是使用$ _POST,它在执行行中失败。

My Xcode looks like: 我的Xcode看起来像:

NSString *strURL = [NSString stringWithFormat:@"http://www.myserver/AddUser.php?Name=%@&Last=%@&email=%@&pwd=%@&userID=%@", Name, Last, email, pwd, userID];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];

I have gone through numerous tutorials and questions in SO and I can't see what the problem is. 我在SO中经历了大量的教程和问题,我无法看出问题所在。

It seems as though you're issuing a get request, not a post request, which means your $_POST is undefined, which is probably what's causing PDO's errors you're seeing. 好像你发出了一个get请求,而不是post请求,这意味着你的$_POST是未定义的,这可能是导致你看到的PDO错误的原因。 Instead, you should retrieve the values from the $_GET global variable: 相反,您应该从$_GET全局变量中检索值:

$Name = $_GET['Name'];
$Last = $_GET['Last'];
$email = $_GET['email'];
$pwd = $_GET['pwd'];
$userID = $_GET['userID'];

Your HTTP request is being sent using the GET protocol, but you are accessing your data using the POST protocol. 您的HTTP请求是使用GET协议发送的,但您使用POST协议访问数据。 You have three potential fixes, 你有三个潜在的修复,

  1. Change PHP to read data using GET 更改PHP以使用GET读取数据

    $email = $_GET['email']; $ email = $ _GET ['email'];

  2. Change PHP to be agnostic to mode (my preference) 将PHP更改为与模式无关(我的偏好)

    $email = $_REQUEST['email']; $ email = $ _REQUEST ['email'];

  3. Change your iPhone app to send using post. 将您的iPhone应用更改为使用帖子发送。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM