Slim API, doesn't work after connection - mysql

I'm trying to make an API. I've follow a tutorial in OpenClassRoom to make request with MySQL, and I want an API with Slim v3.2.
So I receive the answer of the connexion, but when I want to recover data from a get I have a "Slim Application Error" And I don't know what to do with that.
I'm using MAMP instead of "php -S localhost:8080 -t public public/index.php " because I have the good connection with my database.
I show you my API:
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require '/Users/kravennagen/Downloads/Api/api/racehistory/vendor/autoload.php';
$app = new \Slim\App();
echo "hello";
try{
$bdd = new PDO('mysql:host=localhost;dbname=racehistory;charset=utf8', 'root', 'root', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
echo "connexion...";
}
catch(Exception $e){
die('Erreur connexion BDD:' . $e->getMessage());
}
echo "avant le get";
$app->get('/', function(){
$reponse = $bdd->query('SELECT * FROM user');
while($data = $reponse->fetch()){
echo $data['mail'];
echo $data['password'];
}
$reponse->closeCursor();
});
$app->get('/connexion/{identifiant}/{password}', function($login, $pass){
$reponseMail = $bdd->query('SELECT mail FROM user');
$reponsePass = $bdd->query('SELECT password FROM user');
echo "test1";
While($donnees = $reponseMail->fetch() && $donnees = $reponsePass->fetch()){
if($donnees['mail'] == $login && $donnees['password'] == $pass){
echo "true";
//return true;
}
else{
echo "false";
//return false;
}
}
$reponsePass->closeCursor();
$reponseMail->closeCursor();
});
$app->get("/register/{identifiant}/{password}", function($login, $pass){
$add = 'INSERT INTO user(mail, password) VALUES ($login, $pass)';
if(!preg_match("#^[a-z0-9._-]+#[a-z0-9._-]{2,}\.[a-z]{2,4}$#", $login))
$errors['mail'] = 'adresse mail non valide';
else if (!preg_match("#^(?=.*[A-Z])(?=.*[a-zA-Z])(?=.*\d)([\w]{8,15})$#", $pass))
$errors['password'] = "le mot de passe n'est pas conforme(majuscule au debut, de 8 a 15 caractères)";
else if($bdd->exec($add) === false){
echo "ERREUR INSERTION";
}
else{
echo "User bien ajouté la base de donnée";
}
});
$app->run();
?>

You have to inject your $bdd connection object to the route by using "use":
$app->get('/', function() use ($bdd) {

Related

How to show a message before redirecting to an other page?

I have an example page to reset password. If this user submits this form , it will show a message like "your password successfully update" and redirect to an other page. What’s wrong about my script ?
public function updatepassword(){
$this->form_validation->set_rules('newpassword','Current Password',
'required|alpha_numeric|min_length[6]|max_length[20]');
$this->form_validation->set_rules('confpassword','Current Password',
'required|alpha_numeric|min_length[6]|max_length[20]');
if($this->form_validation->run()){
$password1 = $this->input->post('newpassword');
$password2 = $this->input->post('confpassword');
$this->load->model('app_model');
$id = $this->session->flashdata('item');;
// die(var_dump($id));
if($password1 == $password2){
if($this->app_model->update_password($password1, $id)){
$this->db->where('email', $id);
$this->db->update('login', array('token' => random_string('alnum',20)));
echo 'Password Sukses Diperbaharui'and redirect('web');//here
}else{
echo 'Password Gagal Diperbaharui';
}
}else{
echo 'Password is not matching';
}
}else{
echo validation_errors();
}
}
echo ("<SCRIPT LANGUAGE='JavaScript'> window.alert('Record Updated Successfully'); window.location.href='dh_gl_sub_cat.php'; </SCRIPT>");
One of feasible ways is that using javascript to do redirection.
Add scripts to the success page and set the timeout.
<?php
public function updatepassword() {
$this->form_validation->set_rules('newpassword','Current Password', 'required|alpha_numeric|min_length[6]|max_length[20]');
$this->form_validation->set_rules('confpassword','Current Password', 'required|alpha_numeric|min_length[6]|max_length[20]');
if ($this->form_validation->run()) {
$password1 = $this->input->post('newpassword');
$password2 = $this->input->post('confpassword');
$this->load->model('app_model');
$id = $this->session->flashdata('item');;
// die(var_dump($id));
if ($password1 == $password2) {
if ($this->app_model->update_password($password1, $id)) {
$this->db->where('email', $id);
$this->db->update('login', array('token' => random_string('alnum',20)));
// add below codes
?>
Password Sukses Diperbaharui
<script>
setTimeout(() => {
document.location.href = 'web';
}, 3000);
</script>
<?php
// add above codes
} else {
echo 'Password Gagal Diperbaharui';
}
} else {
echo 'Password is not matching';
}
} else {
echo validation_errors();
}
}
?>

Ajax post using json doesnt send data or show error messages

I'm trying to send contact form data to database and get response with json.
Only error what I get is:
SyntaxError: Unexpected token T in JSON at position 0
My ajax:
$(document).ready(function(){
$('#send').on('click',function(e){
e.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
var phone = $('#phone').val();
var subject = $('#subject').val();
var message = $('#message').val();
$.ajax({
url : '<?php echo $baseurl;?>/contactus.php',
type: 'post',
dataType : 'json',
data : {name:name,email:email,phone:phone,subject:subject,message:message},
success:function(response){
if(response.type == 'error'){
output = '<div class="error">'+response.text+'</div>';
}else{
$('#form')[0].reset();
output = '<div class="success">'+response.text+'</div>';
}
$("#contact_results").html(output);
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
});
});
My PHP:
header('Content-Type:application/json');
include('include-global.php');
if($_POST){
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
print "Can't access directly!";
exit;
}
$sender_name = $_POST["name"];
$sender_email = $_POST["email"];
$phone_number = $_POST["phone"];
$subject = $_POST["subject"];
$message = $_POST["message"];
if(strlen($sender_name)<3){
$output = json_encode(array('type'=>'error', 'text' => 'First and lastname is too short!'));
die($output);
}
if(strlen($subject)<3){ //check emtpy subject
print json_encode(array('type'=>'error', 'text' => 'Subject too short'));
exit;
}
if(strlen($message)<3){ //check emtpy message
print json_encode(array('type'=>'error', 'text' => 'Message too short'));
exit;
}
try{
$database = new Connection();
$db = $database->openConnection();
$sql = "INSERT INTO contact SET name = :name, phone = :phone, subject = :subject, email = :email, message = :message";
$qry = $db->prepare($sql);
$qry -> bindParam(':name', $sender_name, PDO::PARAM_STR);
$qry -> bindParam(':phone', $phone_number, PDO::PARAM_STR);
$qry -> bindParam(':email', $sender_email, PDO::PARAM_STR);
$qry -> bindParam(':subject', $subject, PDO::PARAM_STR);
$qry -> bindParam(':message', $message, PDO::PARAM_STR);
$qry -> execute();
} catch (PDOException $e) {
echo "There is some problem in connection: " . $e->getMessage();
}
if(!$qry){
print json_encode(array('type'=>'error', 'text' => 'Error.'));
exit;
}else{
print json_encode(array('type'=>'message', 'text' => 'Thank you '. $sender_name . '.'));
exit;
}
}
I dont understand what I'am doing wrong...
Code and JSON seems to be correct, I got example from google.
Im using dataType, header content type json but still shows error.

JSON variable is not passed to ajax function

Here is the Ajax Code. I am using this ajax code to pass the details to the php page and the php file is supposed to return an array value as true or false depending on the condition. I have used json_encode but it doesn't seem to work
$.ajax({
url: "join_form.php",
type: "POST",
dataType: 'json',
data: {
name: name,
email: email,
contact: contact,
role: role,
dialcode: dialcode,
countrycode: countrycode
},
cache: false,
// var data = JSON.parse(data);
success: function(data) {
data = $.parseJSON(data);
console.log(data);
if(data.status == 'false')
{
alert("Something went wrong");
}
else
{
alert("Message submitted successfully");
$("#joinForm").trigger("reset");
}
// alert(dialcode+countrycode);
}
});
$("#joinForm").trigger("reset");
});
Here is the Php file (join_form.php).
This php file checks for validity of fields and stores a false value
in the
array on which I use json_encode function so that it can
be returned to ajax. But on returning nothing happens.
It shows blank function.
if else functions are not executed. Please help
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "kites";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
alert("Connection failed");
}
else
{
$response = array();
// Check for empty fields
if(
empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['contact']) ||
empty($_POST['role']) ||
empty($_POST['dialcode']) ||
empty($_POST['countrycode'])
)
{
echo "No arguments Provided!";
$response['status']='false';
}
else{
$name = $_POST['name'];
$email = $_POST['email'];
$contact = $_POST['contact'];
$role = $_POST['role'];
$dialcode = $_POST['dialcode'];
$countrycode = $_POST['countrycode'];
$stmt = $this->conn->prepare("SELECT email from join_form WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
// user existed
// $stmt->close();
$response['status'] = 'false';
} else {
// user not existed
// $stmt->close();
$response['status'] = 'true';
}
header("Content-Type: application/json; charset=utf-8", true);
echo json_encode($response);
$sql = "INSERT INTO join_form (name,email,contact,role,dialcode,countrycode)
VALUES ('$name','$email','$contact','$role','$dialcode','$countrycode')";
if (mysqli_query($conn, $sql)) {
$response['status'] = 'true';
}
else {
echo "Please do it again";
$response['status'] = 'false';
// echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
header("Content-Type: application/json; charset=utf-8", true);
echo json_encode($response);
}
}
?>
Remove all the un-needed echos from your php, and keep only the last one 'echo json_encode($response);'.
Than you don't need to parse the returned response in your ajax call. So you will get your status and you can do something with it.
Alternatively if you wnat also to return the messages you are echoing than you can do the following:
$response['status'] = 'false';
$response['message'] = 'No arguments Provided!';
echo json_encode(response).
And than in your ajax call response:
if(data.status == 'false')
{
alert(data.message);
}
}
NOTE: remove the 'HEADER's from your php, you also don't need this. In the ajax call you have set 'data-type = json' and this is enough. The data will be sent back with the appropriate headers automatically!
You are passing the variable to your your data:
data: {
name: name,
email: email,
contact: contact,
role: role,
dialcode: dialcode,
countrycode: countrycode
},
from where do you get those values?
If they are coming from a form you will need to refer to them:
var name = $('#name').val()
... and so on.
Maybe you already did that but You are not posting your complete code n order to give me the possibility to spot your problem. And by the way, down voting the answer before you will post the complete code in here don't really help.
If you don't post also your HTML I can not see that.
NOTE: You answer with a 'Nothing worked' doesn't really help, and you don't mention the errors you are eventually receiving, so I still have to guess.

Send parameters via POST HTTPRequest (appcelerator titanium)

I have created a page on my server (index.php) that when access by the app (via appcelerator titanium) via createHTTPClient (app.js and login.js), returns a JSON string. But i have problems when i login and send parameters via POST HTTPRequest.
index.php :
<?php
class Connect{
public function login($username, $password){
$db = mysqli_connect("mysql6.000webhost.com", "a8324766_user", "**********", "a8324766_db");
if (mysqli_connect_errno()) {
printf("Échec de la connexion : %s\n", mysqli_connect_error());
exit();
}
$sql = "SELECT *
FROM users
WHERE username ='$username'
AND password = '$password'";
$req = mysqli_query($db, $sql);
$data = mysqli_fetch_assoc($req);
if(isset($data['username'])&& !empty($data['username']) && isset($data['password'])&& !empty($data['password'])){
if (mysqli_num_rows($req) > 0){
$response = array(
"logged" => true,
"name" => $data['name'],
"email" => $data['email']);
echo json_encode($response);
}
else
{
// Else the username and/or password was invalid! Create an array, json_encode it and echo it out
$response = array(
"logged" => false,
"message" => 'Invalid Username and/or Password'
);
echo json_encode($response);
}
}else{
echo "login ou mot de passe est incorrecte";
}
}
}
$user = new Connect();
$user->login($_POST['username'], $_POST['password']);
?>
app.js :
Titanium.UI.setBackgroundColor('#fff');
var tabGroup = Titanium.UI.createTabGroup();
var login = Titanium.UI.createWindow({
title:'User Authentication Demo',
tabBarHidden:true,
url:'login.js'
});
var loginTab = Titanium.UI.createTab({
title:"Login",
window:login
});
tabGroup.addTab(loginTab);
tabGroup.open();
login.js :
var win = Titanium.UI.currentWindow;
var username = Titanium.UI.createTextField({
color:'#336699',
top:10,
left:10,
width:300,
height:40,
hintText:'Username',
keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
returnKeyType:Titanium.UI.RETURNKEY_DEFAULT,
borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED
});
win.add(username);
var password = Titanium.UI.createTextField({
color:'#336699',
top:60,
left:10,
width:300,
height:40,
hintText:'Password',
passwordMask:true,
keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
returnKeyType:Titanium.UI.RETURNKEY_DEFAULT,
borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED
});
win.add(password);
var loginBtn = Titanium.UI.createButton({
title:'Login',
top:110,
width:90,
height:35,
borderRadius:1,
font:{fontFamily:'Arial',fontWeight:'bold',fontSize:14}
});
win.add(loginBtn);
var xhr = Ti.Network.createHTTPClient({timeout:50000});
xhr.onload = function(e) {
Ti.API.info("Received text: " + this.responseText);
var json = this.responseText;
var response = JSON.parse(json);
if (response.logged == true){
alert("Welcome " + response.name + ". Your email is: " + response.email);
} else {
alert(response.message);
}
};
xhr.onerror = function(e) {
Ti.API.info('Error >>>> ' + JSON.stringify(e));
};
loginBtn.addEventListener('click',function(e){
xhr.open("POST","http://lahcene.comli.com/index.php");
var params = {
username: username.value,
password: password.value
};
alert(username.value);
alert(password.value);
xhr.setRequestHeader( 'Content-Type','application/json' );
xhr.send(params);
});
The result :
http://i.stack.imgur.com/OfByi.png
The result whene i login with username and password :
http://i.stack.imgur.com/9qm1m.png
any idea please.
The most simply answer for fix cross-domain is a LAMP or use Domain Server at Website:
Install Lamp (Linux) , Install Mamp (Mac OS) & Install Xampp (Windows)
When you install this software bundle, use your html in it :)
1º You have a problem in your send due to Content-Type must be application/x-www-form-urlencoded
2º Your function php login() return a JSON or String... must be JSON always because you use JSON.parse at xhr.onload().
echo "login ou mot de passe est incorrecte"; change to
$response = array(
"logged" => false,
"message" => 'login ou mot de passe est incorrecte'
);
echo json_encode($response);

How to I bind 'id' from mysql query to $_SESSION

I am trying to set the $_SESSION to the 'id' in the mysql query. How do I do that?
public function Login($email, $pass){
if(!empty($email) && !empty($pass)){
$st = $this->db->prepare("select email, pass, id from login where email=? and pass=?");
$st->bindParam(1, $email);
$st->bindParam(2, $pass);
$st->execute();
if ($st->rowCount() == 1){
//login correctly
$_SESSIONS['user_id'] = XXX;
header('Location: main.php');
} else{
echo "Wrong password";
}
} else {
echo "Please enter username and password";
}
}
Here's my answer:
public function Login($email, $pass){
if(!empty($email) && !empty($pass)){
$st = $this->db->prepare("select email, pass from login where email=? and pass=?");
$st->bindParam(1, $email);
$st->bindParam(2, $pass);
$st->execute();
if ($st->rowCount() == 1){
//login correctly
$_SESSIONS['user_id'] = $st->fetchALL();
header('Location: main.php');
} else{
echo "Wrong password";
}
} else {
echo "Please enter username and password";
}
}