Angular 6/PHP Http failure during parsing for - php

I am currently learning angular 6 and have problems with my connection to the database.
addData(nachname: any, vorname: any, telefon: any) {
return this.client.post('http://localhost/api/add.php', {
nachname,
vorname,
telefon
}).subscribe((data) => {
console.log(data);
});
}
<?php
header("Access-Control-Allow-Credentials: true");
header('Content-type: application/json');
header("Access-Control-Allow-Origin: ".((isset($_SERVER['HTTP_ORIGIN'])) ?
$_SERVER['HTTP_ORIGIN'] : "*"));
header('Access-Control-Allow-Headers: X-Requested-With, content-type,
access-control-allow-origin, access-control-allow-methods, access-control-
allow-headers');
$db = mysqli_connect("localhost", "root", "", "telefonauskunft");
if(!$db){
exit("Verbindungsfehler: ".mysqli_connect_error());
}
$db -> set_charset('utf8');
$model = json_decode(file_get_contents("php://input"));
$sql = "Insert Into telefonauskunft ('Nachname', 'Vorname', 'Telefon')
Values ('$model -> Nachname', '$model -> Vorname', '$model ->
Telefon');";
if($model->Nachname){
$qry = $db->query($sql);
}
$db->close();
?>
These are my codes. I got a normal select query with this.client.get (...).
Unfortunately I get with this code
error
:
{error: SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at XMLHttp…,
Http failure during parsing for
Where is my problem? I thank you in advance for answers and help

You should print something out in your PHP file, for instance a boolean value stating that the database query was successful. Ideally, you should follow common JSON API guidelines, cf. http://jsonapi.org/format/upcoming/
print json_encode($db->query($sql));

Related

How do I insert simple rows of json data into a mysql table using PHP? [duplicate]

Hi I'm trying to insert the json array into my MySQL database. I'm passing the data form my iphone there i have converted the data into json format and I'm passing the data to my server using the url its not inserting into my server.
This is my json data.
[{"name":"0","phone":"dsf","city":"sdfsdf","email":"dsf"},{"name":"13123123","phone":"sdfsdfdsfsd","city":"sdfsf","email":"13123123"}]
This is my Php code.
<?php
$json = file_get_contents('php://input');
$obj = json_decode($data,true);
//Database Connection
require_once 'db.php';
/* insert data into DB */
foreach($obj as $item) {
mysql_query("INSERT INTO `database name`.`table name` (name, phone, city, email)
VALUES ('".$item['name']."', '".$item['phone']."', '".$item['city']."', '".$item['email']."')");
}
//database connection close
mysql_close($con);
//}
?>
My database connection code.
<?php
//ENTER YOUR DATABASE CONNECTION INFO BELOW:
$hostname="localhost";
$database="dbname";
$username="username";
$password="password";
//DO NOT EDIT BELOW THIS LINE
$link = mysql_connect($hostname, $username, $password);
mysql_select_db($database) or die('Could not select database');
?>
Please tell where I'm doing wrong in the above code basically I'm not a php developer I'm mobile application developer so I'm using the php as a server side scripting please tell me how to resolve this problem.
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
I think you are passing the wrong variable. You should pass $json in json_decode as shown above.
You are missing JSON source file. Create a JSON file then assign it to var data:
<?php
require_once('dbconnect.php');
// reading json file
$json = file_get_contents('userdata.json');
//converting json object to php associative array
$data = json_decode($json, true);
// preparing statement for insert query
$st = mysqli_prepare($connection, 'INSERT INTO users(firstname, lastname, gender, username) VALUES (?, ?, ?, ?)');
// bind variables to insert query params
mysqli_stmt_bind_param($st, 'ssss', $firstname, $lastname, $gender, $username);
// processing the array of objects
foreach ($data as $user) {
$firstname = $user['firstname'];
$lastname = $user['lastname'];
$gender = $user['firstname'];
$username = $user['username'];
// executing insert query
mysqli_stmt_execute($st);
}
There is no such variable as $data. Try
$obj = json_decode($json,true);
Rest looks fine. If the error still persists, enable error_reporting.
Its simple you can insert json datatype as below. reference link: click here for more details
insert into sgv values('c-106', 'admin','owner',false,'[{"test":"test"},
{"test":"test"}]',0,'pasds');
$string=mysql_real_escape_string($json);
header("Access-Control-Allow-Origin: http://localhost/rohit/");
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");
//files needed to connect to database
include_once 'config/database.php';
include_once 'objects/main.php';
//get Database connection
$database = new Database();
$db = $database->getConnection();
//instantiate product object
$product = new Product($db);
//get posted data
$data = json_decode(file_get_contents("php://input"));
//set product property values
$product->b_nm = $data->Business_Name;
$product->b_pno = $data->Business_Phone;
$product->b_ads = $data->Business_Address;
$product->b_em = $data->Business_Email;
$product->b_typ = $data->Business_Type;
$product->b_ser = $data->Business_Service;
$name_exists = $product->nameExists();
if($name_exists){
echo json_encode(
array(
"success"=>"0",
"message" => "Duplicate Record Not Exists."
)
);
} else{
if($product->b_nm != null && $product->b_pno != null && $product->b_ads != null && $product->b_em != null && $product->b_typ != null && $product->b_ser != null){
if($product->create()){
//set response code
http_response_code(200);
//display message: Record Inserted
echo json_encode(array("success"=>"1","message"=>"Successfully Inserted"));
}
}
else{
//set response code
http_response_code(400);
//display message: unable to insert record
echo json_encode(array("success"=>"0","message"=>"Blank Record Not Exists."));
}
}

MySQL connection to PHP

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/

Getting a http_response_code(404) when trying to pass a record id dynamically in phpmyadmin. Am trying to integrate MySQL on-pre with Salesforce

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.

How to delete record from table using Angular http.delete with PHP backend?

I am trying to delete a record from the database table using Angular on frontend and PHP on the backend. I am passing the id through URL and trying to get it back with $_GET['id'] but it doesn't work (no error in console).
PHP API:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: DELETE");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
require_once("includes/initialize.php");
$db = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbdatabase) or die('Could not connect to database');
$data = json_decode(file_get_contents("php://input"));
$id;
if (isset($_GET['id'])) {
$id = $_GET['id'];
}
// update the ECD
if(ECD::deleteECD($id)){
echo '{';
echo '"message": "The center was deleted."';
echo '}';
}
// if unable to update the ECD, tell the user
else{
echo '{';
echo '"message": "Unable to delete the center."';
echo '}';
}
And Angular http.delete:
deleteCenter (id: number): Observable<{}> {
const url = `${this.D_ROOT_URL}${id}`;
return this.http.delete(url);
}
I tested the URL to make sure it's passing the correct URL.
The delete() method returns a cold observable, which means that the HTTP request is not sent until someone subscribes to the observable. You should write this:
return this.http.delete(url).subscribe();

Getting Blank record for this code

Look at this code, i am getting empty record in database.
$firstname=isset($_POST['firstname'])?mysql_real_escape_string($_POST['firstname']):"";
this line not giving first name but it gives blank value not the value that i am trying to insert into the database.
whats wrong in this code?
create.php
<?php
include_once('confi.php');
if($_SERVER['REQUEST_METHOD']=='POST')
{
$firstname=isset($_POST['firstname'])?mysql_real_escape_string($_POST['firstname']):"";
$lastname=isset($_POST['lastname'])?mysql_real_escape_string($_POST['lastname']):"";
$email=isset($_POST['email'])?mysql_real_escape_string($_POST['email']):"";
$password=isset($_POST['password'])?mysql_real_escape_string($_POST['password']):"";
$status=0;
$query = "INSERT INTO users (firstname,lastname,email,password,status) VALUES ('$firstname','$lastname','$email','$password','$status')";
$insert = mysql_query($query);
if($insert)
{
$data=array("result"=>1,"message"=>"successfully added!");
}
else
{
$data=array("result"=>0,"message"=>"Error!");
}
}
else
{
$data=array("result"=>0,"message"=>"Request Method is Wrong!");
}
mysql_close($conn);
/* JSON Response */
header('Content-type: application/json');
echo json_encode($data);
?>
confi.php
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db('tuts_rest', $conn);
?>
Add the following lines in your php file and remove header access you have already added
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS')
{
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers:
{
$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}

Categories