0

I'm learning Angular 8 and now trying to send a post request from localhost to the api on shared hosting (tried on localhost before the server). I had the issue of origin source and fixed by installing Moesif Orign & CORS Changer extension for chrome. I have this code now

    onCreatePost(userData: { username: string; email: string, password: string, school: string }) {
    console.log(userData);
    this.http.post('http://example.net/insert.php', userData).subscribe( (response) => {
      console.log(response);
    });
  }

Here's the userData log

{username: "test name", email: "user@mail.com", password: "123456", school: "test school"}

I try to save the post data first before handling it

$postData = $_POST;
$q = $db->prepare("insert into post (data) value ('$postData')");
$q->execute();
$result['message'] = "test message";
echo json_encode($result);

but I get Array as a result in the field. I changed it too json_encode($_POST) but I get [] in the field. I can't find the data sent in the post request why is that?

Nicolas
  • 8,077
  • 4
  • 21
  • 51
PHP User
  • 2,350
  • 6
  • 46
  • 87
  • 1
    Fixing a CORS issue by downloading an extension is far from a solution. Do you expect all of your user to download the extension aswell ? You should try to fix the issue rather than using developpement tool to go around them. – Nicolas Jan 20 '20 at 14:44
  • 2
    Also, you code is vulnerable to [sql injection](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) you should always bind your paramters when using SQL statement. – Nicolas Jan 20 '20 at 14:46
  • can you please share Array data which you are getting ? – Piyush Jain Jan 20 '20 at 14:49
  • 1
    @Nicolas it's just to solve the connection from localhost while developing and testing and I know there's no security I'm just testing send data from Angular to PHP while learning – PHP User Jan 20 '20 at 14:52
  • I don't think your SQL is correct. First, you have a typo where `value` should be `values`: `insert into post (data) values ('$postData')`, but `$postData` should be an object and you're treating is as a string. Have you logged what you are receiving in `$_POST` to make sure you are getting the correct info from your post? That should be your first step before you move on to worrying about how you are using that data. – Ashley Jan 20 '20 at 15:02
  • 1
    _“but I get Array as a result in the field”_ - of course you do, because `$postData` is an array, but you are forcing it into a string context here - which in PHP, always results in the word “Array”. Your SQL query makes no sense to begin with, if you want to insert values into _multiple_ columns here. – 04FS Jan 20 '20 at 15:04
  • See this tutorial https://www.techiediaries.com/php-angular/ – Abdulwehab Jan 28 '20 at 07:00

0 Answers0