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

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

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.

codeIgniter how can i create session into login controller

How can I create login session name? I tried but it didn't work for me.
Here is my code:
loginModel
public function login($name, $pass){
$this->db->select("username", "password");
$this->db->from("users");
$this->db->where("username", $name);
$this->db->where("password", $pass);
$query = $this->db->get();
$ret = $query->row();
if($query->num_rows() == 1){
return true;
}
else {
return false ;
}
}
loginControler;
public function checkLogin(){
$this->form_validation->set_rules("username", "Username", "required");
$this->form_validation->set_rules("password", "Password", "required");
if($this->form_validation->run() == false){
$this->load->view("login");
}
else {
redirect("SiteCont/index");
}
}
public function verifyUser(){
$name = $this->input->post("username");
$pass = $this->input->post("password");
$this->load->model("loginModel");
if($this->loginModel->login($name, $pass)){
return true;
}
else {
$this->form_validation->set_message("verifyUser", "geçersiz kullanıcı adı veya porala");
return false;
}
Only I need something ;
if($this->session->userdata('name')){
//show dashboard
}
else {
//show login
}
in the login page.
loginModel
public function login($name, $pass){
$this->db->select("username", "password");
$this->db->from("users");
$this->db->where("username", $name);
$this->db->where("password", $pass);
$query = $this->db->get();
$ret = $query->row();
if($query->num_rows() == 1){
//set the session data (you can add more values to array according to your needs)
$data = array(
'user_id' => $ret->user_id, //change your actual user id field
);
$this->session->set_userdata($data);
//set the session data
return true;
}
else {
return false ;
}
}
To check
if($this->session->userdata('user_id')){
//redirect to dashboard
}
else{
//redirect to login
}
This will work properly. Change name of variables according to your needs.

Slim API, doesn't work after connection

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) {

Cannot pass whitespace separated value to Query

My project with PHP and MySql stuck here ,
$searchfriend = "Jason";
$status = query("SELECT status FROM users.profile WHERE name = ?" , $searchfriend );
The above statement works quite well.
When I replace,
$searchfriend = "Jason R"
It's not working. What is the solution ?
I have created my own query function with PDO.
function query()
{
$sql = func_get_arg(0);
$parameters = array_slice(func_get_args(), 1);
static $handle;
if (!isset($handle))
{
try
{
$handle = new PDO("mysql:dbname=" . DATABASE . ";host=" . SERVER, USERNAME, PASSWORD);
$handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (Exception $e)
{
trigger_error($e->getMessage(), E_USER_ERROR);
exit;
}
}
$statement = $handle->prepare($sql);
if ($statement === false)
{
trigger_error($handle->errorInfo()[2], E_USER_ERROR);
exit;
}
$results = $statement->execute($parameters);
if ($results !== false)
{
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
else
{
return false;
}
}