Vue.js 2 + API created with PHP microframework Slim - javascript

I'm learning how to create an API and connect it with Vue.js application.
I need to create a users' registration form.
Is it correct if I create an API with PHP and then connect it to my Vue.js in order to register users. An API will be connected to MySQL db.
Here's my db.php class:
class DB {
private $dbhost = 'localhost';
private $dbuser = 'root';
private $dbpass = '';
private $dbname = 'organization';
public function Connect() {
$mysqli = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
if ($mysqli->connect_errno) {
echo "Не удалось подключиться к MySQL: (".$mysqli->connect_errno.") ".$mysqli->connect_error;
}
return $mysqli;
}
}
And this is one of routes:
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
$app = new \Slim\App;
$app->get('/api/customers', function(Request $request, Response $response) {
$db = new DB();
$db = $db->Connect();
$sql = "SELECT * FROM workers";
$result = $db->query($sql);
echo json_encode($result->fetch_assoc());
$db->close();
});

Related

Post method return Json data keeps on looping

So, I am building a website that tries to first post an id from the front end then on the php file. The post method return a questions that is base on the id that is send to the backend and query through the database. This is my code
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: access");
header("Access-Control-Allow-Methods: GET,POST");
header("Content-Type: application/json; charset=UT-8");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$servername = "localhost";
$username = "root";
$password = "";
$database= "credentials";
// Create connection
$db = mysqli_connect($servername, $username, $password, $database);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
$postdata = file_get_contents("php://input");
if(isset($postdata) && !empty($postdata)){
$request = json_decode($postdata);
$quizID = $request->QuizID;
$sql = "SELECT * FROM question WHERE QuizID='$quizID'";
$result = mysqli_query($db,$sql);
if(mysqli_num_rows($result)>0){
$json_array = array();
while($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
$response = ["data"=>"valid","quiz"=>$json_array];
echo json_encode($response);
}else{
$response = ["data"=>"invalid"];
echo json_encode($response);
}
}
?>
The front end was successfully return the JSON data but it keeps looping non stop. Why is that happening, I tried running the query first then I store in variable but still it keeps looping.
This is my front end code
useEffect(()=>{
console.log("use effect");
const sendData = {
QuizID: localStorage.getItem("quizID")
}
console.log("adad")
axios.post("http://localhost/pepep/fetchLesson.php", sendData).then(res=>{
console.log("post success");
console.log(res.data.quiz[0]);
setQuestion([res])
})
})
Can anyone help me with this ?
You have setQuestion([res]) which will set the state to a new value.
Setting the state will trigger a re-render.
Your useEffect call doesn't have a dependency array, so it will run on every render.
Add a dependency array with a list of variables that should trigger the function when they change.
Since you don't appear to be using any external variables, it looks like that should be none.
useEffect( () => { /* ... */ }, [] );

Database won't connect, no results returned

So I've got three PHP files, and I'm trying to connect my database through these files. It won't seem to connect, I'm trying to connect it so then my ajax in my javascript file will hopefully work.
BaseClass.php:
<?php
require("Conn.php");
require("MySQLDao.php");
$handle = fopen("php://input", "rb");
$raw_post_data = '';
while (!feof($handle)) {
$raw_post_data .= fread($handle, 8192);
}
fclose($handle);
if (empty($raw_post_data))
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "No Data Recieved";
echo json_encode($returnValue);
return;
}
else
{
$dao = new MySQLDao();
if ($dao->openConnection() == false)
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "Connection Could Not Be Established Between Server And Database";
echo json_encode($returnValue);
}
else
{
//Decodes data, dont change
$body = json_decode($raw_post_data, true);
$recieved = $body["data"];
//Gets the result of a query
//$result = $dao->MySQLDaoMethodName(parameters);
//Return the result of the query
echo json_encode($result);
}
$dao->closeConnection();
return;
}
?>
When I run this in chrome all it shows is:
{"status":false,"title":"Error","message":"No Data Recieved"}
MySQLDao.php:
<?php
//Class for holding queries
class MySQLDao
{
var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $mysqli = null;
var $dbname = null;
var $result = null;
//constructor
function __construct()
{
$this->dbhost = Conn::$dbhost;
$this->dbuser = Conn::$dbuser;
$this->dbpass = Conn::$dbpass;
$this->dbname = Conn::$dbname;
}
//Attempt a connection to the database
public function openConnection()
{
//Try and connect to the database
$this->mysqli = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
//If the connection threw an error, report it
if (mysqli_connect_errno())
{
return false;
}
else
{
return true;
}
}
//Get method for retrieving the database conection
public function getConnection()
{
return $this->mysqli;
}
//Close the connection to the database
public function closeConnection()
{
//If there is a connection to the database then close it
if ($this->mysqli != null)
$this->mysqli->close();
}
//-----------------------------------QUERY METHODS-------------------------------------
public function getResults($data)
{
$sql = "SELECT room.room_description FROM room WHERE room.room_id = 1";
$result = $this->mysqli->query($sql);
//if (mysql_num_rows($result) == 1) {
// $obj = mysql_fetch_object($result, 'obResults');
//}
echo json_encode($result);
echo($result);
}
}
?>
Nothing shows when I run this in chrome. Even when I put echo statements in some of the functions.
Conn.php:
<?php
class Conn
{
public static $dbhost = "***";
public static $dbname = "***";
public static $dbuser = "***";
public static $dbpass = "";
}
?>
part of my test.html:
function callPHP() {
$.ajax ({
type: "GET",
datatype: "application/json",
url: "MySQLDao.php",
data: { action : 'getResults()' },
//error: function(err){console.log(err)},
success: function(output) {
console.log(output);
}
//error, function(err){console.log(err)}
});
}
I basically just want to be able to write query methods and transport the results from these querys to my js, this is because I have a few graphs in my javascript and I want to get data from the database. All this code doesn't produce any errors I believe but it's just not returning anything back.
All help appreciated! Thanks!

How to Get the Id from angular app for Update and how to Get the Data from HTTP Post into the PHP file?

I am trying to update and Add Data from my angular app to Server using PHP.
I am Struck at how to give the URL Id from the angular app for update and how to get the values from Http POST into php for inserting into table. This is my code:
getEmployee(id : number){
const eurl='http://localhost/Angular/UpdateEmployee?id='
const url= `${eurl}${id}`
return this.http.get(this.empurl)
.map(response => response.json().data as Data)
.catch(this.HandleError)
}
This is my PHP for Update:
<?php
$successreturn[]=array(
"id"=>"any",
"firstname"=>"any",
"lastname"=>"any",
"dateofbirth"=>"any",
"city"=>"any",
"gender"=>"any");
header("Access-Control-Allow-Origin: *");
$id=$_GET['id'];
$servername="localhost";
$username="root";
$password="sandeepchetikam";
$dbase="mydb";
$conn=mysqli_connect($servername,$username,$password,$dbase);
if (!$conn) {
echo "Connection Problem".mysqli_connect_error($conn);
}
$sql= "SELECT * FROM Employees WHERE id='$id'";
$result = mysqli_query($conn,$sql);
$count = mysqli_num_rows($result);
$value=0;
if(!$result){
echo "Connection Failed " .mysqli_connect_error($result);
}
while($row = mysqli_fetch_assoc($result)){
$successreturn[$value]['id']=$row['id'];
$successreturn[$value]['firstname']=$row['firstname'];
$successreturn[$value]['lastname']=$row['lastname'];
$successreturn[$value]['dateofbirth']=$row['dateofbirth'];
$successreturn[$value]['city']=$row['city'];
$successreturn[$value]['gender']=$row['gender'];
$value++;
};
echo json_encode($successreturn);
?>
Code for addEmployees:
addEmployees(data: Data): Observable<Data>{
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
return this.http.post(this.empurl,data,options)
.map(this.extractData)
.catch(this.HandleError)
}
I would like to know how to write the link for the getEmployee() function.
And how to write PHP for addEmployees.

Why does my website think the $http request is cross domain?

In my website I'm calling to a php page at http://domain.com/angulartest/js/services/index.php
from a service in the same folder.
app.factory('vakmannen', ['$http', function($http) {
return $http.get('http://www.domain.com/angulartest/js/services/index.php')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
and this is my php
<?php
header("Access-Control-Allow-Origin: http://www.domain.com/angulartest/");
$servername = "localhost";
$username = "XXXXX";
$password = "XXXXX";
$dbname = "XXXXX";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM XXXX";
$result = $conn->query($sql);
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
?>
But every time the $http.get runs Firefox tells me the CORS header isn't right, I've tried it on Chrome too but to no avail.
Any help will be greatly appreciated!
If the angular app is in the same folder, you can use relative URLs. You can even remove the Access-Control-Allow-Origin header.
app.factory('vakmannen', ['$http', function($http) {
return $http.get('/angulartest/js/services/index.php')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);

Accessing MySQL database in d3.js with php file

I need some help with MySQL and D3 with a php file.
I am trying to get access to my database using D3. I have created a php file where I make the connection to MySQL.
My problem is however that I get an empty array when printing out my output to the console from D3. I can't seem to find what I am doing wrong. Below is my code for both the D3 call and the php file: (I have appropriate names from username, password and database name.)
<?php
$host = "localhost";
$port = 8889;
$username = "********";
$password = "********";
$database="***datebasename***";
if (!$server) {
die('Not connected : ' .mysql_error());
}
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
if (isset($_GET['type'])) {
$type = $_GET['type'];
} else {
$type = "null";
echo "Type not passed";
}
if($type=='load'){
$string = '';
$gene = $_GET["gene"];
$data = $_GET["data"];
$myquery = "select gene_data.gene_data from genes inner join gene_data on genes.id=gene_data.g_id where genes.name ='$gene' and genes.type='$data'";
$query = mysql_query($myquery);
if ( !$myquery || !$query) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
}
?>
My file are all running from a server. The MySQL server is also on the same server, so I jut call localhost to get access. Also since I need several different parameters for my SQL calls I send the values from D3 ("gene" and "human").
The following the call I make from D3:
d3.json("getdata.php?type=load&gene=CLL5&data=human", function(error, data) {
console.log(data);
});
Also it is worth mentioning that my query is tested and works.
Some help would be greatly appreciated! Any ideas on how to debug with and prints or write.outs would be appretiated as well!

Categories