2016-05-09 2 views
-1

Попытка запускать запрос для получения user_id на основании зарегистрированного в username. users.php ....Получить текущий идентификатор пользователя через запрос SELECT

<?php 
session_start(); 
include_once 'error.php'; 

class User{ 

private $db; 
private $db_table = "users"; 

public function __construct() 
{ 
    $this->db = new DbConnect(); 
} 


public function isLoginExist($username, $password) 
{  

    $query = "select * from " . $this->db_table . " where username =  
'$username' AND password = '$password' Limit 1"; 
    $result = mysqli_query($this->db->getDb(), $query); 
    if(mysqli_num_rows($result) > 0){ 
     mysqli_close($this->db->getDb()); 
     return true; 
    }  
    mysqli_close($this->db->getDb()); 
    return false;  
} 

public function createNewRegisterUser($username, $password, $email) 
{ 

    $query = "insert into users (username, password, email, created_at, 
updated_at) values ('$username', '$password', '$email', NOW(), NOW())"; 
    $inserted = mysqli_query($this->db->getDb(), $query); 
    if($inserted == 1){ 
     $json['success'] = 1;         
    }else{ 
     $json['success'] = 0; 
    } 
    mysqli_close($this->db->getDb()); 
    return $json; 
} 



public function loginUsers($username, $password){ 

    $json = array(); 
    $canUserLogin = $this->isLoginExist($username, $password); 
    if($canUserLogin){ 
     $json['success'] = 1; 
    }else{ 
     $json['success'] = 0; 
    } 
    return $json; 
} 
} 


?> 

index.php

<?php 
session_start(); 
require_once 'users.php'; 

$username = ""; 
$password = ""; 
$email = ""; 



if(isset($_POST['username'])){ 
$username = $_POST['username']; 
} 
if(isset($_POST['password'])){ 
$password = $_POST['password']; 
} 
if(isset($_POST['email'])){ 
$email = $_POST['email']; 
} 

// Instance of a User class 
$userObject = new User(); 


// Registration of new user 
if(!empty($username) && !empty($password) && !empty($email)){ 
$hashed_password = md5($password); 
$json_registration = $userObject->createNewRegisterUser($username,  
$hashed_password, $email); 

echo json_encode($json_registration); 
} 


// User Login 
if(!empty($username) && !empty($password)) 
{ 
$hashed_password = md5($password); 


$json_array = $userObject->loginUsers($username, $hashed_password); 

session_start(); 

$_SESSION['username'] = $username; 

echo json_encode($json_array); 
} 
//var_dump($_SESSION['username']);displays current users name on android LOG 
?> 

topics.php

<?php 
session_start(); 
include_once 'error.php'; 


class Topic{ 

private $db; 
private $db_table = "topics"; 
private $db_table1 = "created_topics"; 



public function __construct() 
{ 
    $this->db = new DbConnect(); 
} 

public function createNewTopic($topic_name, $content) 
{ 
    session_start(); 
    include_once 'index.php'; 

    //query to get current logged in user_id 
    $un = "SELECT user_id FROM users WHERE username = " .  
    $_SESSION['username'] . " LIMIT 1"; 
    //running query 
    $unResults = mysqli_query($this->db->getDb(), $un); 

    //insert into db topic_name and content 
    $query = "INSERT INTO topics (topic_name, content, created_at, 
    updated_at) values ('$topic_name', '$content', NOW(), NOW())"; 

    $inserted = mysqli_query($this->db->getDb(), $query); 

    //query to insert into created_topics table with user_id and topic_id 
    $q = "insert into created_topics(user_id, topic_id,created_at) values 
    ('$unResults',LAST_INSERT_ID(),NOW())"; 

    mysqli_query($this->db->getDb(), $q); 

    if($inserted == 1){ 
     $json['success'] = 1;         
    }else{ 
     $json['success'] = 0; 
    } 

    mysqli_close($this->db->getDb()); 
    return $json; 

} 
} 
?> 

created_topic.php

<?php 
session_start(); 
require_once 'topics.php'; 

$topic_name = ""; 
$content = ""; 
$username = $_SESSION['username']; 


if(isset($_POST['topic_name'])) 
{ 
$topic_name = $_POST['topic_name']; 
} 
if(isset($_POST['content'])) 
{ 
$content = $_POST['content']; 
} 



// Instance of a Topic class 
$topicObject = new Topic(); 

// Registration of new topic 
if(!empty($topic_name) && !empty($content)) 
{ 

$json_registration = $topicObject->createNewTopic($topic_name, $content); 

echo json_encode($json_registration); 
} 

?> 

Android create_topic Страница

package com.example.mrbuknahsty.annovoteexdb; 

import android.content.Intent; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Toast; 

import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 
import org.apache.http.params.BasicHttpParams; 
import org.apache.http.params.HttpConnectionParams; 
import org.apache.http.params.HttpParams; 
import org.json.JSONException; 
import org.json.JSONObject; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
import java.util.List; 

public class createTopic extends AppCompatActivity 
{ 
protected EditText enteredTopicName,enteredContent; 

Button create; 

protected String topic_name; 

private final String serverUrl1 =  
"http://lkirkpatrick.btcwsd.com/anno/create_topic.php"; 



@Override 
protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_create_topic); 

    enteredTopicName = (EditText) findViewById(R.id.topicNameET); 
    enteredContent = (EditText) findViewById(R.id.contentEdit); 

    create = (Button)findViewById(R.id.createBtn); 

    create.setOnClickListener(new View.OnClickListener() { 

     @Override 

     public void onClick(View v) { 

      topic_name = enteredTopicName.getText().toString(); 

      String content = enteredContent.getText().toString(); 

      if(topic_name.equals("") || content.equals("")){ 

       Toast.makeText(createTopic.this, "Topic Name or Content must  
      be filled", Toast.LENGTH_LONG).show(); 

       return; 

      } 

      if(topic_name.length() <= 1 || content.length() <= 1){ 

       Toast.makeText(createTopic.this, "Topic Name or Content  
     length must be greater than one", Toast.LENGTH_LONG).show(); 

       return; 

      } 

    // request authentication with remote server4 

      AsyncDataClass asyncRequestObject = new AsyncDataClass(); 

      asyncRequestObject.execute(serverUrl1, topic_name, content); 

     } 

    }); 
} 

private class AsyncDataClass extends AsyncTask<String, Void, String> { 

    @Override 

    protected String doInBackground(String... params) { 

     HttpParams httpParameters = new BasicHttpParams(); 

     HttpConnectionParams.setConnectionTimeout(httpParameters, 5000); 

     HttpConnectionParams.setSoTimeout(httpParameters, 5000); 

     HttpClient httpClient = new DefaultHttpClient(httpParameters); 

     HttpPost httpPost = new HttpPost(params[0]); 

     String jsonResult = ""; 

     try { 

      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair> 
      (2); 

      nameValuePairs.add(new BasicNameValuePair("topic_name", 
      params[1])); 

      nameValuePairs.add(new BasicNameValuePair("content", params[2])); 

      nameValuePairs.add(new BasicNameValuePair("content", params[2])); 

      httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

      HttpResponse response = httpClient.execute(httpPost); 

      jsonResult =  
    inputStreamToString(response.getEntity().getContent()).toString(); 

     } catch (ClientProtocolException e) { 

      e.printStackTrace(); 

     } catch (IOException e) { 

      e.printStackTrace(); 

     } 

     return jsonResult; 

    } 

    @Override 

    protected void onPreExecute() { 

     super.onPreExecute(); 

    } 

    @Override 

    protected void onPostExecute(String result) { 

     super.onPostExecute(result); 

     System.out.println("Resulted Value: " + result); 

     if(result.equals("") || result == null){ 

      Toast.makeText(createTopic.this, "Server connection failed", 
     Toast.LENGTH_LONG).show(); 

      return; 

     } 

     int jsonResult = returnParsedJsonObject(result); 

     if(jsonResult == 0){ 

      Toast.makeText(createTopic.this, "Something Went Wrong", 
     Toast.LENGTH_LONG).show();   

      return; 

     } 

     if(jsonResult == 1){ 

      Intent intent = new Intent(createTopic.this, login.class); 

      intent.putExtra("USERNAME", topic_name); 

      intent.putExtra("MESSAGE", "Topic successfully created!"); 

      startActivity(intent); 

     } 

    } 

    private StringBuilder inputStreamToString(InputStream is) { 

     String rLine = ""; 

     StringBuilder answer = new StringBuilder(); 

     BufferedReader br = new BufferedReader(new InputStreamReader(is)); 

     try { 

      while ((rLine = br.readLine()) != null) { 

       answer.append(rLine); 

      } 

     } catch (IOException e) { 

// TODO Auto-generated catch block 

      e.printStackTrace(); 

     } 

     return answer; 

    } 

} 

private int returnParsedJsonObject(String result){ 

    JSONObject resultObject = null; 

    int returnedResult = 0; 

    try { 

     resultObject = new JSONObject(result); 

     returnedResult = resultObject.getInt("success"); 

    } catch (JSONException e) { 

     e.printStackTrace(); 

    } 

    return returnedResult; 

} 

} 

Все побежало отлично, пока я не добавил запроса, чтобы получить user_id from users where username = '$username'; Теперь в моем андроида журнала я только get-- Привел значение:
и мой тост говорит подключение к серверу терпит неудачу. Любая помощь была бы потрясающей.

Благодаря

+0

Чтобы устранить проблему, вы должны прочитать соответствующую часть в принятом ответе здесь http://stackoverflow.com/questions/60174/how-can-i-prevent-sql- injection-in-php –

+0

Прочитайте, но не знаете, как это относится к моему вопросу. Я appriciate помощь им просто не ясно, как это поможет мне от потери моей переменной сессии ??? Я вижу, что он повторяет мою переменную (имя пользователя) после входа в систему, но когда я иду использовать ее в другом запросе в другом php-файле, он постоянно возвращает 0 в моей БД. im получать ошибки, которые на самом деле затрудняют его работу. – luke

+0

Это поможет вам правильно выполнить запрос. то, как вы запускаете SQL на данный момент, неверно, и это является самой причиной ошибки, которую вы получаете. –

ответ

0

Вы должны прочитать о scopes in programming.

Проверьте, есть ли функция topics.php и переменные, которые вы определяете/используете там. Я уверен, вы обнаружите ошибку;)

+0

session_start(); \t $ findUser = $ _SESSION ['username']; \t \t // запрос, чтобы получить вошедшего в user_id \t \t $ ип = "SELECT user_id из пользователей, где LIMIT 1 UserName = '$ findUser'"; Я добавил _SESSION ['username'] = $ имя пользователя в моем index.php, но все равно не повезло. Я был на этом больше 2 недель, но не могу получить это имя пользователя. Пожалуйста, помогите – luke

+0

Я не уверен, что я должен искать или делать .... Всего здесь нет. – luke

+0

Трудно сказать, если вы забыли разместить некоторые части кода или если вам не хватает некоторых базовых понятий вашей логики в коде. – pocketrocket

Смежные вопросы