Swift httppost data not inserting to MySQL database
If having the server just echo the request works, then the problem rests within the server, not the client code. I would suggest adding some error handling in the PHP code:
<?php
// specify that this will return JSON
header('Content-type: application/json');
// open database
$con = mysqli_connect("localhost","user","password","notify");
// 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["firstName"]);
$field2 = mysqli_real_escape_string($con, $_REQUEST["lastName"]);
// perform the insert
$sql = "INSERT INTO user (first_name, last_name) 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);
?>
Notes:
I wouldn't recommend logging in as
root
.Make sure you use
mysqli_real_escape_string
to protect yourself against SQL injection attacks (see point 1).I don't know if your
user
table has other fields in it, but if so, you might want to specify the column names in theinsert
statement. Even if you only have those two columns, it's a good way to "future-proof" your code.Note, I've changed this to generate JSON response. I do that because it makes it easier for the client code to parse and handle the response. I'll leave the
NSJSONSerialization
to you.
Trying to insert data from Swift into a MySQLi database using POST request via php
You are not executing your query in the PHP code, try to edit your code like this:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connection = new mysqli("localhost", "knockyou_seb", "*******", "knockyou_classroomGrades");
$id = $_POST['id'] ?? 13;
$firstName = $_POST['firstName'] ?? 'Test';
$lastName = $_POST['lastName'] ?? 'McTest';
$subject = $_POST['subject'] ?? 'Test Subject';
$grade = $_POST['grade'] ?? 5;
$sql = $connection->prepare("INSERT INTO Students (id, first_name, last_name, subject, grade) VALUES (?, ?, ?, ?, ?)");
$sql->bind_param("isssi", $id, $firstName, $lastName, $subject, $grade);
$sql->execute();
$sql->close();
$connection->close();
Every time I try to post data to MySQL database using Swift and Alamofire the data appears null?
You should use parameterized queries to prevent sql injection. Here is a link that you should read through and then bookmark so you have it for quick reference.
https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection
I updated your code using parameterized queries as a model for you to examine.
$item1 = $_POST['title'];
$item2 = $_POST['link'];
$item3 = $_POST['available_shares'];
$item4 = $_POST['risk'];
$item5 = $_POST['description'];
$item6 = $_POST['postID'];
$item7 = $_POST['price'];
$item8 = $_POST['timestamp'];
// Create connection
$mysqli=mysqli_connect("localhost","username","password","database");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "INSERT INTO `TB_POSTS`
(
postID,
timestamp,
link,
price,
title,
available_shares,
risk,
description
) VALUES(?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $mysqli->prepare($query); //Prepare
$stmt->bind_param("ssssssss", $item6, $item8, $item2, $item7, $item1, $item3, $item4, $item5); //Bind
$stmt->execute();//Execute
if($stmt->affected_rows === 0) exit('Nothing was inserted.'); //Check to see if it worked
$stmt->close();
Related Topics
Parametrized Pdo Query and 'Limit' Clause - Not Working
How to Password Protect Folder/Page Using PHP Without a Db or Username
Configure Multiple Databases in Zf2
_Construct() VS Sameasclassname() for Constructor in PHP
Why Is Constructing Pdo Connection Slow
PHP Warning: Move_Uploaded_File() Unable to Move
How to Return Back Twice in Laravel
Submitting JSON Data via Jquery Ajax.Post to PHP
How to Easily Switch Between PHP Versions on MAC Osx
Detecting Image Type from Base64 String in PHP
Encrypt Files Using Pgp in PHP
Ssl Error Ssl3_Get_Server_Certificate:Certificate Verify Failed
Does PHP Execution Stop After a User Leaves the Page
Access Variables from Parent Scope in Anonymous PHP Function