2012-10-23 3 views
1

내 지식을 업그레이드 할 수있는 질문이 있습니다.Ajax로 ID를 즉시 얻는 방법

인라인 편집 페이지를 만들려고하는데 데이터가 데이터베이스에 저장됩니다. "content"표에서 "id"및 "text"필드를 테스트 목적으로 2 개의 필드를 만듭니다.

"id = 25"또는 id = X로 필드를 수정하려면 수동으로 수행하는 방법을 알고 MySQL 쿼리에서 "WHERE id = 25"를 지정하지만 목록이있는 경우 1000 개의 항목 중, 즉석에서 ID를 얻기 위해 쿼리를 수정할 수 있습니까?

의 index.php 파일을 여기

<style> 
body {  
    font-family: Helvetica,Arial,sans-serif; 
    color:#333333; 
    font-size:13px; 
} 

h1{ 
    font-family: Georgia, Times, serif; 
    font-size: 28px;   
} 

a{ 
    color: #0071D8; 
    text-decoration:none; 
} 

a:hover{ 
    text-decoration:underline; 
} 

:focus { 
    outline: 0; 
} 

#wrap{ 
    width: 500px; 
    margin:0 auto;    
    overflow:auto;  
} 

#content{ 
    background: #f7f7f7; 
    border-radius: 10px; 
} 

#editable {  
    padding: 10px;  
} 

#status{ 
    display:none; 
    margin-bottom:15px; 
    padding:5px 10px; 
    border-radius:5px; 
} 

.success{ 
    background: #B6D96C; 
} 

.error{ 
    background: #ffc5cf; 
} 

#footer{ 
    margin-top:15px; 
    text-align: center; 
} 

#save{ 
    display: none; 
    margin: 5px 10px 10px;  
    outline: none; 
    cursor: pointer;  
    text-align: center; 
    text-decoration: none; 
    font: 12px/100% Arial, Helvetica, sans-serif; 
    font-weight:700;  
    padding: 5px 10px; 
    -webkit-border-radius: 5px; 
    -moz-border-radius: 5px; 
    border-radius: 5px; 
    color: #606060; 
    border: solid 1px #b7b7b7; 
    background: #fff; 
    background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#ededed)); 
    background: -moz-linear-gradient(top, #fff, #ededed); 
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#ededed'); 
} 

#save:hover 
{ 
    background: #ededed; 
    background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#dcdcdc)); 
    background: -moz-linear-gradient(top, #fff, #dcdcdc); 
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#dcdcdc'); 
} 

</style> 

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script> 
<script> 
$(document).ready(function() { 

$("#save").click(function (e) {   
    var content = $('#editable').html();  

    $.ajax({ 
     url: 'save.php', 
     type: 'POST', 
     data: { 
     content: content 
     },    
     success:function (data) { 

      if (data == '1') 
      { 
       $("#status") 
       .addClass("success") 
       .html("Data saved successfully") 
       .fadeIn('fast') 
       .delay(3000) 
       .fadeOut('slow'); 
      } 
      else 
      { 
       $("#status") 
       .addClass("error") 
       .html("An error occured, the data could not be saved") 
       .fadeIn('fast') 
       .delay(3000) 
       .fadeOut('slow'); 
      } 
     } 
    }); 

}); 

$("#editable").click(function (e) { 
    $("#save").show(); 
    e.stopPropagation(); 
}); 

$(document).click(function() { 
    $("#save").hide(); 
}); 

}); 
</script> 

</head> 
<body> 
<div id="wrap"> 

    <div id="status"></div> 

    <div id="content"> 

    <div id="editable" contentEditable="true"> 
    <?php 
     //get data from database. 
     include("db.php"); 
     $sql = mysql_query("select * from content"); 
     $row = mysql_fetch_array($sql);  
     echo $row['id']; 
     echo "<br />"; 
     echo $row['text']; 
    ?>  
    </div> 

    <button id="save">Save</button> 
    </div> 

</div> 
    </body> 

그리고이 save.php 파일입니다 :

include("db.php"); 


$content = $_POST['content']; //get posted data 
$content = mysql_real_escape_string($content); //escape string 

$sql = "UPDATE content SET text = '$content' WHERE id = '$id' "; 

if (mysql_query($sql)) 
{ 
    echo 1; 
} 

내가 여기

내가 연주하고, 코드입니다 이것이 어리석은 질문 일 수 있다는 것을 아십시오. 그러나 나는 초보자입니다.

도움을 위해 미리 감사드립니다.

는 UPDATE : 루이스 고맙습니다 나는 나의 오래된 문제를 해결하지만 난 한 동안 모든 코드를 넣어 경우에만이 작동하고 좋은 나머지를 첫 번째 항목의 버튼을하지 "저장"내가 왜 몰라 , 어떤 힌트? 현재 "description_text"만 테스트 중입니다.

<?php 

    /////////// Now let us print the table headers //////////////// 

    $query =" SELECT * FROM gallery ORDER BY id DESC "; 

    $result = mysql_query($query) or die(mysql_error()); 

    echo "<div style='width: 100%; text-align: center;'>";     
    echo "<table style='margin: auto auto;'>"; 
    echo "<tr><th>ID</th><th>Image</th><th>Category</th><th>Description</th><th>Added on</th></tr>"; 

    while($ordinate = mysql_fetch_array($result)) 
    { 

    $id  = $ordinate['id']; 
    $img_name = $ordinate['img_name']; 
    $category  = $ordinate['category']; 
    $description_text = $ordinate['description_text']; 
    $insert_datetime = $ordinate['insert_datetime']; 

    echo "<tr><td style='width: 20px;'>".$id."</td><td style='width: 210px;'><img src='../../upload/content/uploaded_images/". $img_name ."' width='200px'></td><td style='width: 100px;'>".$category."</td><td style='width: 100px;'><div id='status'></div><div id='content'><div id='editable' contentEditable='true'>".$description_text."</div><button id='save'>Save</button></div></td><td style='width: 100px;'>".$insert_datetime."</td></tr>";   

    } 
    echo "</table><br /><br /></div>"; 
?> 
+0

는 '내가 어떻게 fly' 위치에 ID를 얻기 위해 쿼리를 수정할 수 있습니다 이드를 데려 가고 싶니? –

답변

3

스크립트의 나머지 부분에서 동일한 바르 사용할 수 있도록 index.php에, 처음으로 코드의이 부분을 이동에 :

는 여기에 "동안"코드입니다. 이후 아약스 호출

<?php 
    //get data from database. 
    include("db.php"); 
    $sql = mysql_query("select * from content"); 
    $row = mysql_fetch_array($sql);  
    // echo $row['id']; but keep this ones in its original place inside their <%php %> tags 
    // echo "<br />"; 
    // echo $row['text']; 
?>  

이 PHP 라인을 삽입 :

data: { 
    content: content 
    <?php 
    echo ", id: ".$row['id']; 
    echo ", token: '".md5('my SALT text'.(int)$row['id'])."'"; // strongly!!! recomended, not mandatory 
    ?> 
    },  

및 save.php

$id = (int)$_POST['id'];     // (int) sanitizes id 
    $token = $_POST['token']; 
    if(md5('my SALT text'.$id)!=$token) die(); // or whatever but do not execute update 
               // perhaps echo 0; die(); 

    // ... rest of your code .... 
    $sql = "UPDATE content SET text = '$content' WHERE id = $id" 

토큰에를, 누군가가 당신의 save.php를 사용하는 위험을 방지 테이블에있는 모든 게시물에 무엇이든 삽입하는 방법입니다.

최소한 조언 : mysql_query 대신에 mysqli_query (i를주의하십시오)를 사용하십시오. 마지막으로 사용되지 않습니다. 또한 차이가 있지만 PDO를 사용할 수 있습니다.

+0

빠른 답변 주셔서 감사합니다. 이 작업을 수행하면 "저장"버튼이 더 이상 나타나지 않고 저장할 수 없습니다. ( – Mark

+0

예.이 답변이 올바르지 않으므로 ... '행 ['id ']'는 (는) 아약스 매개 변수로 사용되는 점에서 정의되지 않았습니다. 두번째로''id = '$ id' ''','save.php'의 세번째'$ id'는 처음으로 초기화되어야합니다'$ id = $ _POST ['id ']'... – Reflective

+0

@Reflective 당신은 맞습니다. 나는 절반의 질문을 읽은 상태로 감시하고 있었는데, 지금 바로 고치고 있습니다. 아약스 호출의 부적절한 사용으로 인한 피해를 막기 위해 토큰을 추가 할 것입니다. 그러나 잠시 시간이 걸립니다. –

0

ON DUPLICATE KEY UPDATE과 함께 INSERT 문을 사용할 수 있습니다. 하지만 데이터베이스에 id 열 UNIQUE를 만들어야합니다.

사용 INSERT INTO `table` (id, text) VALUES (id1, text1), (id2, text2), ...; 구문은

VALUES 후 부분은 $_POST를 사용하여주기에 생성합니다.이 jQuery를 액세스 할 수 있으며, 게시 할 수 있도록하는 대신 단순히 $ 행 [ 'ID를'] 메아리의

INSERT statement MySql doc page

0

은 특정 ID로 HTML 요소 내부를 에코.

<span id="idfield"><?php echo $row['id']; ?></span> 
<button id="save">Save</button> 
</div>  

그런 다음, 자바 스크립트 내부 :

$("#save").click(function (e) {   
    var content = $('#editable').html();  
    var id = $('#idfield').html(); 

는 POST에서 매개 변수로 사용

$.ajax({ 
     url: 'save.php', 
     type: 'POST', 
     data: { 
     content: content, 
     id: id 
     },