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';
}
?>
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;
}
}
?>
Related
I am having some issues with connecting my MySQL table to my php connection script. I am receiving this error whenever I attempt to test the code. (I am using Angular, MySQL Workbench, and php).
zone-evergreen.js:2845 POST http://localhost/angular_admin/php/login.php net::ERR_CONNECTION_REFUSED
The code that is attempting to make the connection with the MySQL server is the database.php script.
<?php
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Credentials: true');
header("Access-Control-Allow-Methods: PUT, GET, POST, DELETE");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header("Content-Type: application/json; charset=UTF-8");
$db_host = 'localhost:3306';
$db_username = 'root';
$db_password = '';
$db_name = 'users';
$mysqli = new mysqli($db_host, $db_username, $db_password,$db_name);
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
?>
I manually entered a test record within side of my table on the MySQL: test, test#website.com, and test. I used that to login when I received the error listed above. My login.php script looks like this:
<?php
include_once("database.php");
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
if(isset($postdata) && !empty($postdata))
{
$pwd = mysqli_real_escape_string($mysqli, trim($request->password));
$email = mysqli_real_escape_string($mysqli, trim($request->username));
$sql = "SELECT * FROM users where email='$email' and password='$pwd'";
if($result = mysqli_query($mysqli,$sql))
{
$rows = array();
while($row = mysqli_fetch_assoc($result))
{
$rows[] = $row;
}
echo json_encode($rows);
}
else
{
http_response_code(404);
}
}
?>
And of course my users.ts script looks like this:
export class Users {
public Id: number;
public name: string;
public pwd:string;
public email:string;
constructor(Id:number,name: string,pwd:string,email:string) {
this.Id = Id;
this.name = name;
this.pwd = pwd;
this.email = email;
}
}
I have verified that my MySQL Workbench is running as: root, localhost:3306, the name of the schema is users (my database.php script may be looking for the wrong database name?). Is there any steps I am missing to ensure that the database is accessible by the php script? I am running the angular server using Node.js following the steps mentioned on this article https://fahmidasclassroom.com/register-and-login-system-using-angular-8-php-and-mysql/
I am trying to update one particular record or row corresponding to a id passed dynamically. There is a record belonging to that id. When I give the URL followed with the "?id=3", I am getting a 404 error, saying no such record exists. Would like to know what error I have done. The following is my code.
<?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 '../objects/constitute.php';
$database = new Database();
$db = $database->getConnection();
$constitute = new Constitute($db);
$data = json_decode(file_get_contents("php://input"));
$constitute->id = isset($_GET['id']) ? $_GET['id'] : die();
$constitute->name = $data->name;
$constitute->address = $data->address;
$constitute->constitution_type = $data->constitution_type;
$constitute->organisation_id = $data->organisation_id;
if($constitute->update()){
http_response_code(200);
echo json_encode(array("message" => "Constitute was updated."));
}
else{
http_response_code(503);
echo json_encode(array("message" => "Unable to update constitute."));
}
?>
The following is the update() method:
function update(){
$query = "UPDATE
" . $this->table_name . "
SET
name = :name,
address = :address,
constitution_type = :constitution_type,
organisation_id = :organisation_id
WHERE
id = ?";
$stmt = $this->conn->prepare($query);
$this->id=htmlspecialchars(strip_tags($this->id));
$this->name=htmlspecialchars(strip_tags($this->name));
$this->address=htmlspecialchars(strip_tags($this->address));
$this->constitution_type=htmlspecialchars(strip_tags($this->constitution_type));
$this->organisation_id=htmlspecialchars(strip_tags($this->organisation_id));
$stmt->bindParam(':id', $this->id);
$stmt->bindParam(':name', $this->name);
$stmt->bindParam(':address', $this->address);
$stmt->bindParam(':constitution_type', $this->constitution_type);
$stmt->bindParam(':organisation_id', $this->organisation_id);
if($stmt->execute()){
return true;
}
return false;
}
Also when i try to pass the updated record in postman, I am getting success code. But the record does not get saved.
Please let me know where I have done mistakes.
I am building a user api and one of the task is to create user by inserting a user into the database but while I came up with a code it worked, but it returned 400 bad request as oppose to 200 ok status
create_user.php
<?php
// required headers
header("Access-Control-Allow-Origin: http://localhost/portal/user/");
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");
// database connection will be here
// files needed to connect to database
include_once 'config/database.php';
include_once 'objects/user.php';
// get database connection
$database = new Database();
$db = $database->getConnection();
// instantiate product object
$user = new User($db);
// submitted data will be here
// get posted data
$data = json_decode(file_get_contents("php://input"));
// set product property values
$user->first_name = $data->first_name;
$user->last_name = $data->last_name;
$user->email = $data->email;
$user->password = $data->password;
$user->mobile_no = $data->mobile_no;
// use the create() method here
// create the user
if(
!empty($user->first_name)&&
!empty($user->last_name)&&
!empty($user->email)&&
!empty($user->password)&&
!empty($user->mobile_no)&&
$user->create()
){
// set response code
http_response_code(200);
// display message: user was created
echo json_encode(array("message" => "User was created."));
}
// message if unable to create user
else{
// set response code
http_response_code(400);
// display message: unable to create user
echo json_encode(array("message" => "Unable to create user."));
}
user.php (class)
<?php
// 'user' object
class User{
// database connection and table name
private $conn;
private $table_name = "users";
// object properties
public $uid;
public $first_name;
public $last_name;
public $email;
public $password;
public $mobile_no;
// constructor
public function __construct($db){
$this->conn = $db;
}
// create() method will be here
// create new user record
function create(){
// insert query
$query = "INSERT INTO " . $this->table_name . "
SET
first_name = :first_name,
last_name = :last_name,
email = :email,
password = :password,
mobile_no = :mobile_no";
// prepare the query
$stmt = $this->conn->prepare($query);
// sanitize
$this->first_name=htmlspecialchars(strip_tags($this->first_name));
$this->last_name=htmlspecialchars(strip_tags($this->last_name));
$this->email=htmlspecialchars(strip_tags($this->email));
$this->mobile_no=htmlspecialchars(strip_tags($this->mobile_no));
$this->password=htmlspecialchars(strip_tags($this->password));
// bind the values
$stmt->bindParam(':first_name', $this->first_name);
$stmt->bindParam(':last_name', $this->last_name);
$stmt->bindParam(':email', $this->email);
$stmt->bindParam(':mobile_no', $this->mobile_no);
// hash the password before saving to database
$password_hash = password_hash($this->password, PASSWORD_BCRYPT);
$stmt->bindParam(':password', $password_hash);
// execute the query, also check if query was successful
if($stmt->execute()){
return true;
}
return false;
}
}
?>
I expect to see a status code of 200 ok since i have inserted some values inside the body of the postman request. it was suppose to return 400 bad request if the values are empty
I have built an API on PHP. While sending a POST request, variables provided in POST url are not being received and input data-set is empty. data variable in below provided create.php is empty.
If we supply hard coded data in create PHP file, then it is working fine.
Below is my main data.php file code. Which contains the function for creating the product using POST variables.
<?php
class Data{
private $conn;
private $table_name = "data";
public $id;
public $email;
public $address;
public $lasttx;
public $created;
public function __construct($db){
$this->conn = $db;
}
function create(){
$query = "INSERT INTO " . $this->table_name . " SET email=:email,
address=:address, lasttx=:lasttx, created=:created";
$stmt = $this->conn->prepare($query);
$this->email=htmlspecialchars(strip_tags($this->email));
$this->address=htmlspecialchars(strip_tags($this->address));
$this->lasttx=htmlspecialchars(strip_tags($this->lasttx));
$this->created=htmlspecialchars(strip_tags($this->created));
$stmt->bindParam(":email", $this->email);
$stmt->bindParam(":address", $this->address);
$stmt->bindParam(":lasttx", $this->lasttx);
$stmt->bindParam(":created", $this->created);
if($stmt->execute()){
return true;
}
return false;
}
Below is the code of create.php which is being called in API calls. This file receives data and calls create function in data.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 '../objects/data.php';
$database = new Database();
$db = $database->getConnection();
$data1 = new Data($db);
$data = json_decode(file_get_contents("php://input"), true); // THIS VARIABLE is EMPTY while calling API.
$data1->email = $data["email"];
$data1->address = $data["address"];
$data1->lasttx = $data["lasttx"];
$data1->created = date('Y-m-d H:i:s');
if($data1->create()) {
echo '{';
echo '"message": "Product was created."';
echo '}';
}
else{
echo '{';
echo '"message": "Unable to create product."';
echo '}';
}
?>
Please Advise. Many thanks.
u
as you point out in your comment the form variables are submitted via the URL. In your above script, you're trying to parse a JSON object that is the payload of the request. And that's just not where these parameters are - hence you don't get any data from there.
To access variables from the URL in PHP, all you need to do is to get them from the $_GET array. e.g. the email would be in $_GET["email"].
so this part here:
$data = json_decode(file_get_contents("php://input"), true); // THIS VARIABLE is EMPTY while calling API.
$data1->email = $data["email"];
$data1->address = $data["address"];
$data1->lasttx = $data["lasttx"];
$data1->created = date('Y-m-d H:i:s');
will become:
# $data = json_decode line goes away
$data1->email = $_GET["email"];
$data1->address = $_GET["address"];
$data1->lasttx = $_GET["lasttx"];
$data1->created = date('Y-m-d H:i:s');
hope this helps
Matthias
I have logged mu user (in login.php) and start session, before redirect to another page (accueil.php)/
In login.php : My Session exists, my cookies exists.
In accueil.php : My Session exists, my cookies doesn't exists.
==> I started my Session at the top of my second page./
==> I tried different way to use Location in vain :
header('Location: http://localhost/monsite/accueil.php');/
OR
header('Location: accueil.php');
==>Anyway : it returns "undefined index username".
I don't understand. Have you any ideas please?!
Here is my code :
Login.php :
$username = $_GET['username'];
$password = $_GET['password'];
$sql = $connection->query("SELECT username, password FROM login WHERE username = '$username' && `password`= '$password';");
while ($result = $sql->fetch()){
$data = array('username' => $result['username'],
'password' => $result['password']);
}
try{
if($data['username'] !== $username && $data['password'] !== $password ) {
throw new Exception('Login incorrect', 500);
}
else{
session_start();
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
setcookie('maSession', $_SESSION['username'], time()+3600 , '/');
header('Location: http://localhost/monsite/accueil.php');
}
}
catch(Exception $e){
header("HTTP/1.1 500 Internal Server Error");
echo 'error: '.$e->getMessage();
}
Accueil.php :
``
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
include_once('accueil.php');
require_once('db.php');
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$connection = new PDO("mysql:host=$HOST;dbname=$DBNAME", $USER, $PASS);
if(isset($_SESSION)) {
$username = $_SESSION['username'];
echo $username;
}
else{
echo 'no session';
}
}
->var_dump($_SESSION) : returns empty array.
->$_SESSION['username'] : returns undefined index undername.
Thank you !
Try
<?php
//Check session if not already started, then start it.
if(session_id() == '')
{
session_start();
}
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
include_once('accueil.php');
require_once('db.php');
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$connection = new PDO("mysql:host=$HOST;dbname=$DBNAME", $USER, $PASS);
// Check session 'username' it was not empty
if(!empty($_SESSION['username'])) {
$username = $_SESSION['username'];
echo $username;
}
else{
echo 'no session';
}
}
?>