MySQL connection to PHP - 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/

Related

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';
}
?>
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;
}
}
?>

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.

POST data is not being received in API call

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

How to insert json array into mysql database

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."));
}
}

Json returns 'null'

I am currently using Phonegap along with xcode to make an IPhone App.
I'm just trying a simple Json call to get a query from a database (php) and it's returning Null.
I have Whitelisted the domain in the .plist file for phonegap. Here is m code:
$.getJSON('"http://slc0013.pickaweb.co.uk/~bengeor1/fixtures.php",', function(data) {
alert(data); //uncomment this for debug
//alert (data.item1+" "+data.item2+" "+data.item3); //further debug
$('#resultLog').html("<p>item1="+data.id+" item2="+data.home_team+" item3="+data.away_team+"</p>");
});
PHP code:
<?php
header("Access-Control-Allow-Origin: *");
ini_set('display_errors',1);
error_reporting(E_ALL);
// Set your return content type
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
$db = "localhost";
$db_name = "xxx";
$db_user = "xxx";
$db_pwd = "xxxx";
$con = mysql_connect($db, $db_user, $db_pwd);
if (!$con) {
$status = 11; //database error
}
$db_selected = mysql_select_db($db_name, $con);
if (!$db_selected) {
}
$query = "SELECT * FROM Fixtures";
$result = mysql_query($query);
mysql_close();
$num = mysql_numrows($result);
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows)
?>
If you run just the php file it displays the correct results.
Would appreciate your help.
Thanks.
Try to replace the first line:
$.getJSON('"http://slc0013.pickaweb.co.uk/~bengeor1/fixtures.php",', function(data) {
to this:
$.getJSON("http://slc0013.pickaweb.co.uk/~bengeor1/fixtures.php", function(data) {
Looks like you are having problem with url '"http://slc0013.pickaweb.co.uk/~bengeor1/fixtures.php",' should be "http://slc0013.pickaweb.co.uk/~bengeor1/fixtures.php" I guess

Categories