Skip to content
Advertisement

Can’t perform a PHP POST request on mysql database

I’m struggling into do my first API in php and I’m facing some problems with a simple POST request. I’ve searched almost everywhere for some alternatives to my code, but it seems to be ok. Can you guys check it for me the last time? Thank you!

method:

function create_msg(){

    // query to insert record
    $query = "INSERT INTO
                " . $this->table_name . "
            SET
                msg_key=:msg_key, msg_id=:msg_id, msg_author=:msg_author, msg_txt=:msg_txt";
  
    // prepare query
    $stmt = $this->conn->prepare($query);
  
    // sanitize
    $this->msg_key=htmlspecialchars(strip_tags($this->msg_key));
    $this->msg_id=htmlspecialchars(strip_tags($this->msg_id));
    $this->msg_author=htmlspecialchars(strip_tags($this->msg_author));
    $this->msg_txt=htmlspecialchars(strip_tags($this->msg_txt));
  
    // bind values
    $stmt->bindParam(":msg_key", $this->msg_key);
    $stmt->bindParam(":msg_id", $this->msg_id);
    $stmt->bindParam(":msg_author", $this->msg_author);
    $stmt->bindParam(":msg_txt", $this->msg_txt);

  
    // execute query
    if($stmt->execute()){
        return true;
    }
  
    return false;
      
}

create.php:

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

include_once '../config/database.php';
include_once '../models/msg.php';

$database = new Database();
$db = $database->getConnection();

$item = new msg($db);

$data = json_decode(file_get_contents("php://input"));

$item->msg_key = $data->msg_key;
$item->msg_id = $data->msg_id;
$item->msg_author = $data->msg_author;
$item->msg_txt = $data->msg_txt;
var_dump($data);

if($item->create_msg()){
    echo 'OK';
} else{
    echo 'Not OK';
}
?>

Advertisement

Answer

ok, so I managed to resolve with this code in the config/database.php

<?php
class Database{
    private $host = 'mysql:host=localhost;dbname=my_touchy';
    private $username = 'touchy';
    private $password = '';


    public function getConnection() {
        $conn = new PDO($this->host, $this->username, $this->password);
        $conn->setAttribute( PDO::ATTR_PERSISTENT, TRUE );
        $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        return $conn;
    }
}

?>

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement