2010-07-05 118 views
0

我編輯了我的原始文本,以便爲那些不理解我的問題的人解釋我的整套代碼。當我使用MyISAM的數據庫時,所有這些工作都非常完美,但是當我切換到InnoDB時,我現在必須考慮我的外鍵,否則mysql_queries將無法成功執行。我在用戶登錄時創建的會話變量中擁有user_id。我想我需要從該會話變量中繼傳遞該數字(int)並將其附加到$ _GET,以便它可以傳輸到todo.class.php處理權?通過jquery從php頁面抓取會話變量?

最終的get()或許會需要這個樣子?行動=新& USER_ID = 1(或什麼都編號用戶)&文本=用戶文本類型...

如果有更好的方式來做到這一點,我全力以赴,準備好學習! ;-)

todo.js

$(document).ready(function(){ 
    $(".todoList").sortable({ 
     axis  : 'y', 
     containment : 'window', 
     update  : function(){ 

      var arr = $(".todoList").sortable('toArray'); 

      arr = $.map(arr,function(val,key){ 
       return val.replace('todo-',''); 
      }); 

      $.get('././process/todo/todo.ajax.php',{action:'rearrange',positions:arr}); 
     }, 

     /* Opera fix: */ 

     stop: function(e,ui) { 
      ui.item.css({'top':'0','left':'0'}); 
     } 
    }); 

    var currentTODO; 

    $("#dialog-confirm").dialog({ 
     resizable: false, 
     height:130, 
     modal: true, 
     autoOpen:false, 
     buttons: { 
      'Delete item': function() { 

       $.get("././process/todo/todo.ajax.php",{"action":"delete","id":currentTODO.data('id')},function(msg){ 
        currentTODO.fadeOut('fast'); 
       }) 

       $(this).dialog('close'); 
      }, 
      Cancel: function() { 
       $(this).dialog('close'); 
      } 
     } 
    }); 

    $('.todo').live('dblclick',function(){ 
     $(this).find('a.edit').click(); 
    }); 

    $('.todo a').live('click',function(e){ 

     currentTODO = $(this).closest('.todo'); 
     currentTODO.data('id',currentTODO.attr('id').replace('todo-','')); 

     e.preventDefault(); 
    }); 

    $('.todo a.delete').live('click',function(){ 
     $("#dialog-confirm").dialog('open'); 
    }); 

    $('.todo a.edit').live('click',function(){ 

     var container = currentTODO.find('.text'); 

     if(!currentTODO.data('origText')) 
     { 
      currentTODO.data('origText',container.text()); 
     } 
     else 
     { 
      return false; 
     } 

     $('<input type="text">').val(container.text()).appendTo(container.empty()); 

     container.append(
      '<div class="editTodo">'+ 
       '<a class="saveChanges" href="#">Save</a> or <a class="discardChanges" href="#">Cancel</a>'+ 
      '</div>' 
     ); 

    }); 

    $('.todo a.discardChanges').live('click',function(){ 
     currentTODO.find('.text') 
        .text(currentTODO.data('origText')) 
        .end() 
        .removeData('origText'); 
    }); 

    $('.todo a.saveChanges').live('click',function(){ 
     var text = currentTODO.find("input[type=text]").val(); 

     $.get("././process/todo/todo.ajax.php",{'action':'edit','id':currentTODO.data('id'),'text':text}); 

     currentTODO.removeData('origText') 
        .find(".text") 
        .text(text); 
    }); 

    var timestamp=0; 
    $('#addButton-todo').click(function(e){ 

     if((new Date()).getTime() - timestamp<5000) return false; 

     $.get("././process/todo/todo.ajax.php",{'action':'new','text':'New Todo Item. Doubleclick to Edit.','rand':Math.random()},function(msg){ 

      $(msg).hide().appendTo('.todoList').fadeIn(); 
     }); 

     timestamp = (new Date()).getTime(); 

     e.preventDefault(); 
    }); 

}); 

todo.class.php

<?php 
class ToDo{ 

    private $data; 

    public function __construct($par){ 
     if(is_array($par)) 
      $this->data = $par; 
    } 

    public function __toString(){ 

     return ' 
      <li id="todo-' . $this->data['id'] . '" class="todo"> 

       <div class="text">' . $this->data['text'] . '</div> 

       <div class="actions"> 
        <a href="#" class="edit">Edit</a> 
        <a href="#" class="delete">Delete</a> 
       </div> 

      </li>'; 
    } 

    public static function edit($id, $text){ 

     $text = self::esc($text); 
     if(!$text) throw new Exception("Wrong update text!"); 

     mysql_query("UPDATE `todo` SET `text` = '".$text."' WHERE `id`=".$id ); 

     if(mysql_affected_rows($GLOBALS['link'])!=1) 
      throw new Exception("Couldn't update item!"); 
    } 

    public static function delete($id){ 

     mysql_query("DELETE FROM `todo` WHERE `id` = ".$id); 

     if(mysql_affected_rows($GLOBALS['link'])!=1) 
      throw new Exception("Couldn't delete item!"); 
    } 

    public static function rearrange($key_value){ 

     $updateVals = array(); 
     foreach($key_value as $k=>$v) 
     { 
      $strVals[] = 'WHEN '.(int)$v.' THEN '.((int)$k+1).PHP_EOL; 
     } 

     if(!$strVals) throw new Exception("No data!"); 

     mysql_query("UPDATE `todo` SET `position` = CASE `id`".join($strVals)." ELSE `position` END"); 

     if(mysql_error($GLOBALS['link'])) 
      throw new Exception("Error updating positions!"); 
    } 

    public static function createNew($uid,$text){ 

     $text = self::esc($text); 
     if(!$text) throw new Exception("Wrong input data!"); 

     $posResult = mysql_query("SELECT MAX(`position`)+1 FROM `todo`");// WHERE `user_id` = 1"); 

     if(mysql_num_rows($posResult)) 
      list($position) = mysql_fetch_array($posResult); 

     if(!$position) $position = 1; 

     mysql_query("INSERT INTO `todo` SET /*`user_id` = {$uid},*/ `text` = '".$text."', `position` = ".$position); 

     if(mysql_affected_rows($GLOBALS['link'])!=1) 
      throw new Exception("Error inserting TODO!"); 

     echo (new ToDo(array(
      'id' => mysql_insert_id($GLOBALS['link']), 
      'text' => $text 
     ))); 

     exit; 
    } 

    public static function esc($str){ 

     if(ini_get('magic_quotes_gpc')) 
      $str = stripslashes($str); 

     return mysql_real_escape_string(strip_tags($str)); 
    } 
} 
?> 

todo.ajax.php

<?php 

require "../../dbc.php"; 
require "../../resources/classes/todo.class.php"; 

$id = (int)$_GET['id']; 

try{ 

    switch($_GET['action']) 
    { 
     case 'delete': 
      ToDo::delete($id); 
      break; 

     case 'rearrange': 
      ToDo::rearrange($_GET['positions']); 
      break; 

     case 'edit': 
      ToDo::edit($id,$_GET['text']); 
      break; 

     case 'new': 
      ToDo::createNew($_GET['text']); 
      break; 
    } 

} 
catch(Exception $e){ 
    echo $e->getMessage(); 
    die("0"); 
} 

echo "1"; 
?> 
+0

注意:您的mySQL查詢容易受到SQL注入攻擊。你需要使用'mysql_real_escape_string()' – 2010-07-05 15:35:08

+0

是的,我已經在我的課上報道過了。我只是推出了一個片段記住;) – Eli 2010-07-05 21:11:25

+0

嗯....如果你這麼說?我所看到的是'$ _GET'值直接傳遞到了沒有任何過濾的'mysql_query()'中。但是,這是你的代碼:) – 2010-07-06 09:11:05

回答

2

爲什麼你需要客戶端的會話ID? jQuery正在向服務器上的PHP腳本發送GET請求。對於您的PHP腳本,它看起來像其他任何請求。 $ _SESSION數組將就位,所有與會話相關的函數都可以正常工作。

信任客戶端提供會話ID是一個非常糟糕的主意。

+0

不一定:如果PHP由於cookies關閉而回退到通過GET參數添加會話ID,可能是因爲jQuery URL不會自動重寫。在這種情況下,手動添加會話ID是唯一的選擇。 – Unicron 2010-07-05 16:29:09

+0

我想這是邊緣情況下的一個例子,你可能想要將會話ID傳遞給你的js文件,但它看起來並不像s2xi所問的那樣。 這將是一個嚴重的阻力,不得不在ajaxy web應用程序中支持無Cookie會話! – joeynelson 2010-07-05 18:36:47

+0

腳本從index.php中接受一個動作,並用javascript將它傳遞給我的ajax.php,它有我的包括todo.class.php。因此,添加/編輯/刪除操作通過$ _GET進行,所以它看起來像?action = new&text =我的測試文本和位置= 2我想要的是JS捕獲會話ID並在$ GET中將它攜帶到我的ajax.php將信息傳遞給我的class.php ...這有道理嗎? – Eli 2010-07-05 20:36:15

0

我不明白你的腳本完全,但據我所知,將當前會話ID可靠地轉換爲JavaScript空間的唯一方法是

(... head section of the HTML document ...) 

<script type="text/javascript"> 
php_session_id = "<?php echo session_id(); ?>" 

alert("The PHP session ID is "+php_session_id); 
</script> 
+0

以及文件是分開的,如果我把它們都放在一起,那麼我不會對此感到疑惑,因爲我可以使用php來回顯我在js中需要的東西。 – Eli 2010-07-05 20:34:02

+0

@ s2xi是的,但是如果你在包含腳本之前執行上述操作,'php_session_id' javascript變量將可用。 – Unicron 2010-07-05 21:59:48

+0

哈,我做了php_session_id = 和我能夠在我的腳本中使用該js變量...不,我只是不知道爲什麼它不會保存到我的數據庫,我得到一個錯誤;( – Eli 2010-07-06 00:22:10

0

@ s2xi我意識到您正在尋找一個簡單問題的答案,「我如何將PHP會話ID加入我的javascript?」而Unicron的回答是這樣做的一個萬無一失的方法。

我想我們只是想弄清楚爲什麼你需要把PHP會話ID放在你的GET請求中。您的PHP腳本將始終知道用戶的會話ID,您只需致電session_id()即可。沒有必要把它放在你的GET請求中。 (讓我們忽略餅乾殘疾邊緣的情況下,現在,我認爲這是明確的,我們有更大的魚魚苗)

其他的事情我很擔心:在數據庫中的會話

  1. 搭售數據身份證並沒有很多意義。一旦該用戶的會話過期,您將永遠無法將該數據綁定到他們。我在這裏錯過了什麼嗎?

  2. 您正在使用GET請求來執行操作和修改數據。這是一個非常糟糕的主意。

+0

他沒有在尋找會話ID,他正在尋找一個最有可能來自登錄的會話變量(一個自定義user_id)。但事實仍然存在(正如你所提到的),會話被維護,所以從AJAX調用的PHP頁面知道user_id .. – 2010-07-05 22:46:45

+0

啊,足夠公平,我抨擊了SQL語句中的$ _SESSION ['user_id']'。 雖然這並不能讓我更加困惑。如果您已經使用'$ _SESSION ['user_id']'那麼問題是什麼? – joeynelson 2010-07-05 23:15:36

+0

嗯,以及我正在使用InnoDB與外鍵到位。我的問題是,我試圖找到一種方法1)通過ajax從php頁面傳遞user_id到class.php或2)....不知道;(我試圖想爲什麼我可以在我的class.php中簡單地添加WHERE子句並使用我的會話變量並完全繞過js ...? – Eli 2010-07-05 23:35:31