Inserting data into MySQL using PDO for PHP Xcode
I'm really trying to figure out why the code below doesn't insert the date I'm posting?
<?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'];
etc. I am hardcoding the values, so I could:
$Name = 'Jane';
It adds data to the database, but with $ _POST it doesn't work in the execution line.
My Xcode looks like this:
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 looked through a lot of tutorials and questions on SO and I can't see what the problem is.
source to share
Your HTTP request is sent using the GET protocol, but you are accessing your data using the POST protocol. You have three possible fixes,
-
Change PHP to read data with GET
$ email = $ _GET ['email'];
-
Change PHP to be mode agnostic (my preference)
$ email = $ _REQUEST ['email'];
-
Change the iPhone app to send by message.
source to share
You seem to be issuing a request get
, not a request post
, which means yours $_POST
is undefined, which is probably causing PDO errors. Instead, you should get values ββfrom a global variable $_GET
:
$Name = $_GET['Name'];
$Last = $_GET['Last'];
$email = $_GET['email'];
$pwd = $_GET['pwd'];
$userID = $_GET['userID'];
source to share