r/simpleios • u/foxdye96 • May 30 '15
How to Connect to Mysql Server Database
I cant seem to connect to my database and right to it. this is my Code:
//php
// Create connection
$servername = "localhost";
$username = "username";
$password = "pwd";
$dbname = "test";
$name = $email = "";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully" . "<br>";
if (isset ($_POST["name"]) && isset ($_POST["email"])){
$name = $_POST["name"];
$email = $_POST["email"];
$sql = "INSERT INTO accounts (Name, Email)
VALUES ('$name', '$email')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully" . "<br>";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
//IOS
NSString *urlString = [NSString stringWithFormat:@"http://192.168.1.6/ForApp/createnewaccount.php?name=%@&email=%@", _name.text, _email.text];
NSURL * url = [NSURL URLWithString:urlString];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod:@"POST"];
0
Upvotes
3
u/[deleted] May 31 '15
I would recommend reading this post: http://stackoverflow.com/questions/11404527/how-to-connect-users-with-mysql-in-mobile-apps-login-permissions
2
u/brendan09 May 31 '15
You need to be using parameter binding for your SQL. Right now you're a prime target for SQL injection attacks, which are incredibly common. Anyone who knows how could delete everything in your database right now in a matter of seconds....or worse get a dump of your database contents.
Make sure you always sanitize input, and always bind parameters for added safety.
3
u/sveinhal May 31 '15
You're using a POST request, but encoding your parameters as if it was a GET.
NSString *urlString = @"http://192.168.1.6/ForApp/createnewaccount.php"; NSURL * url = [NSURL URLWithString:urlString];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url]; [urlRequest setHTTPMethod:@"POST"]; NSString *bodyString = [NSString stringWithFormat:@"name=%@&email=%@", _name.text, _email.text]; NSData *body = [bodyString dataUsingEncoding:NSUTF8StringEncoding]; [urlRequest setHTTPBody:body];
2
u/xauronx May 31 '15
So, just to clarify, you're trying to connect to MySql from PHP code. Then communicate with that PHP script from your iOS code.
Your question is about connecting to the MySql database, which is really a PHP question. As such, it really should be posted on a PHP subreddit. However, there are a couple tips below: