2013-02-16 36 views
0

如果有人能夠幫助我解決這個問題,我真的很感激它 - 我幾乎已經開始工作了!讀取會話變量以寫入數據庫

基本上,我做了一段時間我自己的應用程序想法,我這樣做的原因是因爲我是編程新手,所以我覺得它會教我很多關於不同的元素(即添加,更新和刪除記錄)。

所以在這個例子中,我有一個用戶登錄成功,並且它創建了一個正在被其他表單傳遞的會話。我希望他們能夠增加一筆交易 - 我幾乎擁有這筆交易,但似乎與其中一部分鬥爭。

我的HTML代碼:

<!DOCTYPE html> 
<html> 
<head> 
<title>Find A Deal</title> 
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/> 
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" /> 
<link rel="stylesheet" href="http://localhost/findadeal/themes/deal.css" /> 
<style> 
    #login-button { 
     margin-top: 30px; 
    }   
</style> 
<script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js"></script>  
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script> 
<script src="js/custom3.js"></script> 
<script src="js/custom4.js"></script> 

     <?php 
    if(!isset($_SESSION)){ 
    session_start(); 
     } 

    if(isset($_SESSION['username'])){ 
     /* User is logged in */ 
     echo "IT WORKS!"; 
     } ?> 

</head> 


<body> 
<div data-role="page" id="login"> 
    <div data-theme="a" data-role="header"> 
     <h3>Find A Deal</h3> 
    </div> 

    <div data-role="content"> 

     <label for="username">Enter your username:</label> 
     <input type="text" value="" name="username" id="username"/> 
     <label for="password">Enter your password:</label> 
     <input type="password" value="" name="password" id="password"/> 
     <a data-role="button" id="login-button" data-theme="b">Login</a> 
    </div> 

    <div data-theme="a" data-role="footer" data-position="fixed"> 

    </div> 
</div> 

<!--Newly rendered page after successful login!--> 

<div data-role="page" id="index"> 
    <div data-theme="a" data-role="header"> 
     <h2>Find A Deal</h2> 
    </div> 

    <div data-role="content"> 

      <?php 
    if(!isset($_SESSION)){ 
    session_start(); 
     } 

    if(isset($_SESSION['username'])){ 
     echo "IT WORKS!"; 
     } ?> 


    <h3></h3> 
    <a href="#view" data-role="button" data-icon="search">View Deals</a> 
    <a href="#add" data-role="button" data-icon="plus">Add Deals</a> 

    </div> 
</div> 

<!--View Deal Page--> 

    <div data-role="page" id="view"> 
    <div data-role="header"> 
     <h2>Find A Deal</h2> 
    </div> 

    <div data-role="content"> 

      <?php 
    if(!isset($_SESSION)){ 
    session_start(); 
     } 

    if(isset($_SESSION['username'])){ 
     echo "IT WORKS!"; 
     } ?> 


    <h3></h3> 
    <p>test so I know I'm onto a new page</p> 
    <a href="#view" data-role="button" data-icon="search">View Deals</a> 
    <a href="#add" data-role="button" data-icon="plus">Add Deals</a> 
    </div> 

<div data-role="footer"> 

</div> 
</div> 

<!--Add Deal Page--> 

    <div data-role="page" id="add"> 
    <script src="js/custom4.js"></script> 
    <div data-role="header"> 
     <h2>Find A Deal</h2> 
    </div> 

    <div data-role="content"> 

      <?php 
    if(!isset($_SESSION)){ 
    session_start(); 
     } 

    if(isset($_SESSION['username'])){ 
     echo "It's working!"; 
     } ?> 

    <label for="name">Deal Name:</label> 
     <input type="text" value="" name="name" id="name"/> 
     <label for="desc">Description</label> 
     <input type="text" value="" name="desc" id="desc"/> 
     <a data-role="button" id="submit-button" data-theme="b">Submit</a> 
    </div> 





</div> 
</body> 
</html> 

所以才解釋說 - 第一頁是一個登錄頁面,它帶給你的旁邊指數這僅僅是一個菜單頁面我已經成立了,然後從該菜單可以選擇2頁中的1頁 - 查看交易並添加交易。我現在正在與增加交易一分鐘。

添加交易時,用戶將交易名稱和說明輸入到相關文本框中,以便將其添加到數據庫中。 我使用這個js函數:

//Adding a new deal 

$(document).on('pagebeforeshow', '#add', function(){ 
$('#submit-button').on('click', function(){ 
    if($('#name').val().length > 0 && $('#desc').val().length > 0){ 
     userObject.name = $('#name').val(); // Put username into the object 
     userObject.desc = $('#desc').val(); // Put password into the object 
     // Convert an userObject to a JSON string representation 
     var outputJSON = JSON.stringify(userObject); 
     // Send data to server through ajax call 
     // action is functionality we want to call and outputJSON is our data 
     ajax.sendRequest({action : 'add', outputJSON : outputJSON}); 
    } else { 
     alert('Please fill all nececery fields'); 
    } 
});  
}); 

$(document).on('pagebeforeshow', '#index', function(){ 
if(userObject.name.length == 0){ // If username is not set (lets say after force page refresh) get us back to the login page 
    $.mobile.changePage("#add", { transition: "slide"}); // In case result is true change page to Index 
} 
$(this).find('[data-role="content"] h3').append('Deal Added:' + userObject.name); // Change header with added message 
//$("#index").trigger('pagecreate'); 
}); 

// This will be an ajax function set 
var ajax = { 
sendRequest:function(save_data){ 
    $.ajax({url: 'http://localhost/findadeal/login/json3.php', 
     data: save_data, 
     async: true, 
     beforeSend: function() { 
      // This callback function will trigger before data is sent 
      $.mobile.showPageLoadingMsg(true); // This will show ajax spinner 
     }, 
     complete: function() { 
      // This callback function will trigger on data sent/received complete 
      $.mobile.hidePageLoadingMsg(); // This will hide ajax spinner 
     }, 
     success: function (result) { 
      if(result == "true") { 
       $.mobile.changePage("#index", { transition: "slide"}); // In case result is true change page to Index 
      } else { 
       alert('Deal Addition has been unsuccessful, please try again!'); // In case result is false throw an error 
      } 
      // This callback function will trigger on successful action 
     }, 
     error: function (request,error) { 
      // This callback function will trigger on unsuccessful action     
      alert('Error has occurred, please try again!'); 
     } 
    }); 
} 
} 

// We will use this object to store username and password before we serialize it and send to server. This part can be done in numerous ways but I like this approach because it is simple 
var userObject = { 
name : "", 
desc : "" 
} 

這將隨後被輸送到一個PHP文件,準備將輸入寫入到數據庫這樣的:

<?php 

$var1 = $_REQUEST['action']; // We dont need action for this tutorial, but in a complex code you need a way to determine ajax action nature 
$jsonObject = json_decode($_REQUEST['utputJSON']); // Decode JSON object into readable PHP object 

$name = $jsonObject->{'name'}; // Get name from object 
$desc = $jsonObject->{'desc'}; // Get desc from object 

mysql_connect("localhost","root",""); // Conect to mysql, first parameter is location, second is mysql username and a third one is a mysql password 
@mysql_select_db("findadeal") or die("Unable to select database"); // Connect to database called test 

$query = "INSERT INTO deal (dname, description) VALUES ('$name' ,'$desc')"; 
$result=mysql_query($query); 
$num = mysql_numrows($result); 

if($num != 0) { 

    echo "true"; 

} else { 

    echo "false"; 

} 
?> 

這一切工作正常,但是,數據未被插入到數據庫的原因是因爲它需要用戶名中的用戶名存儲在會話變量中的ID。

我想幫什麼用是:

有人能告訴我你是怎麼從會話變量獲取數據,並把它帶過來給PHP文件。 2.此外,會話變量正在存儲用戶名 - 有沒有一種方法可以自行檢查其相關的userid標記,還是必須通過PHP文件中的SQL語句來完成。

我希望我沒有造成任何困惑,我已經明確了自己有什麼問題。我是一名學生,所以在學習過程中,所有的幫助將受到讚賞!我覺得應該把會話數據通過JavaScript函數像其他數據一樣去思考,或者是否應該能夠直接讀取寫入PHP文件或什麼? =/

謝謝你的時間!

+0

如果您已經有HTML輸出,則無法正確處理會話。請確保您在撰寫HTML – 2013-02-16 12:19:11

+0

Hi @ axel.michel的任何一行之前啓動會話(在每個頁面上),謝謝您的評論。我沒有正確處理會話嗎?我有一個session_start()變量上的PHP登錄正在閱讀,然後我有會話if語句工作沿所有其他頁面呈現的變量舉行? 到目前爲止,它似乎一直在爲我工作?如果有其他事情我應該尋找? – user2025934 2013-02-16 12:22:34

+0

你爲什麼不嘗試cookies? – rohitarora 2013-02-16 12:30:47

回答

0

如果我理解的很好,那麼您現在更感興趣的是現在學習的東西,而不是創建應用程序。我建議你一次嘗試學習一件事,在單獨的測試文件中學習,當你掌握了必要的知識後,再將所有的知識結合到一個應用程序中,讓你學到的所有東西都應用到真實的人生測試中。

我正在做一名教練,並且培養了很多學生,並幫助他們認識了一些他們可以引以爲傲的產品,所以如果您有興趣逐一學習,我想我可以幫助您,如果你喜歡。

+0

這將是非常好的你,謝謝! 做一件件一件事是我迄今爲止的結構我的學習! (這也是爲什麼我不去打破可能需要我年紀才能工作的東西:P) 我剛剛結束了把所有的東西放在一起後,我得到一塊工作,看到練習的整體流程,這是階段我在。我已經完成了用戶註冊,並且我將它用作幾乎相同的概念(將數據寫入數據庫),但我試圖找出的是我如何將usersid寫入該表中,並且它也存儲在會話變量 – user2025934 2013-02-16 12:38:26

+0

很多我想做的事情,然後轉移到學習的下一步,圍繞着看到哪個用戶登錄並呈現特定於他們的ID等數據的想法存在很多 - 這就是爲什麼學習如何在這個變量中工作鍛鍊將幫助我在稍後的階段將其操縱給其他人! – user2025934 2013-02-16 12:39:59

0

如果我得到你的邏輯是正確的,你必須做這樣的事情:

上的登錄HTML/PHP頁面開始:

<?php 
    if(!isset($_SESSION)){ session_start(); } 
?> 
THE REST OF YOUR CODE FOLLOWS HERE 

在你登錄行動PHP腳本,再次:

<?php 
    if(!isset($_SESSION)){ session_start(); } 
    // now you look up your user - how ever you do this... 
    // might be something like this... 
    // this is not a real function it should just demonstrate 
    // the possible logic. 
    if(!isset($_SESSION['userid'])) { 
     // you just have to check in case no session userid is set: 
     function getUser($username, $password) { 
      $db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS); 
      $sql = 'SELECT id FROM users WHERE username=:username AND pwd=:pwd'; 
      $statement = $db->prepare($sql); 
      $statement->bindParam(':username', $username, PDO::PARAM_STR); 
      $statement->bindParam(':pwd', $password, PDO::PARAM_STR); 
      $statement->execute(); 
      $result = $statement->fetch(PDO::FETCH_ASSOC); 
      if(!empty($result)) { 
       return $result['id']; 
      } 
      return false; 
     } 
     // call your login logic (here getUser) and 
     // if you have a result, set the session... 
     $userExists = getUser($_POST['user'], $_POST['pwd']); 
     if($userExists) { 
      $_SESSION['userid'] = $userExists; 
     } 
    } 
?> 

在這筆交易中的行動,再次:

<?php 
    if(!isset($_SESSION)){ session_start(); } 
    // you check if the username session exists 
    if(isset($_SESSION['userid'])) { 
     // in case you have... 
     // proceed with your deal logic 
     // and use $_SESSION['userid'] to fill it to the DB 
    } 
?> 
+0

Hi @ axel.michel - 感謝您的迴應。 有一個你的答案的元素,我想我可以使用。但是,我可以問你嗎,我的用戶將他們的用戶名和密碼輸入登錄表單並點擊登錄。在您給我的登錄操作PHP腳本中,是否只需要將「THE_USER_ID」提交到數據庫中並將其保存到會話中?就像它會讀取它並保存它一樣,而不需要用戶在第一個地方輸入確切的字段? – user2025934 2013-02-16 12:45:31

+0

@ user2025934我不確定是否正確地得到您的問題。儘管我已經更新了我的答案。我發佈的內容不是一個工作腳本,它是一個基本的HowTo。假設您有一個登錄邏輯,用於測試用戶是否存在,並在成功時返回用戶標識。這是您保存在會話中的內容,然後您可以使用它,您可以在所有其他PHP文件中讀取此值(只要您開始會話)即可。不需要用戶再進行交互。 – 2013-02-16 13:06:08