2011-11-07 2 views
0

jquery와 ajax를 사용하여 데이터베이스에서 레코드 (게임)를 추가 및 삭제하려고합니다. 저는 아직 주니어 소프트웨어 엔지니어이며 웹 개발의 기본 사항을 배우고 있습니다. 그러나이 작업을 수행하고 내가 누락 된 작업이 무엇인지 확실하지 않습니다.새로 고침없이 DB에 새 레코드를 삭제하고 삽입하십시오.

나는 내 데이터베이스에서 5 개의 열을 가지고 있으며 ID는 자동 증가로 숨겨져 있습니다.

내 질문에 내가 추가하거나 게임을 삭제하고 데이터베이스에 반영하게하지 않는 코드가 무엇입니까 ???

이것은 게임을 삭제하고 추가하는 호출이있는 내 주 파일입니다.

  <script type = "text/javaScript" src ="http://code.jquery.com/jquery-    latest.js""></script> 
     <script type = "text/javascript"> 
      $(document).ready(function(){ 
      $("add games").Submit(function() 
      $("#add").load("add.php"); { 
     var id = $("#ID").val(); 
     var name = $("#name").val(); 
     var type = $("#type").val(); 
     var rating = $("#score").val(); 
     var release = $("Yreleased").val(); 
     var dataString = 'ID=' + id 'name='+ name + '&username=' + type + '&password=' + rating +       '&gender=' + release; 
     if (id =='' || name == '' || type == '' || rating == '' || release == '') 
     { 
     alert("please enter some valid data for your game entry"); 
     } 
     else 
     $.ajax({ 
     type: "POST", 
     url: "add.php", 
     data: dataString, 
     success: function(){ 
     $('.success').fadeIn(200).show(); 
     $('.error').fadeOut(200).hide(); 
     } 
     }); 
     } 
     return false; 
     }); 
     }); 



     </script> 


     <body> 
     <?php 

     include("dbconfig.php"); 
     $sql = "SELECT * FROM games"; 
     $result = mysql_query($sql); 
     while ($record = mysql_fetch_array($result)){ 

     echo "</br> Game ID: " .$record['ID']. "</br> Game Name: " .$record['Name']. 
     "<br /> Game Type: ".$record['Type']. "<br /> Rating: ".$record['Rating']."<br /> Year Released: ".$record['Release Year']."<br /> <br />" ?> 


    <a href="#" id="<?php echo $record["ID"]; ?>" class="deletebutton"><img src="trash.png" alt="delete"/></a> 






    <?php 
     } 

     ?> 

     <form name="add" id ="add" action="add.php" method="post"> 
     <input class ="gameID" type="hidden" id="ID" value = " ' .$record['ID'] . ' " /> 
     <b>Game Name: </b> <input type="text" id="name" size=70> 
     <b>Game Type:</b> <input type="text" id="type" size=40> 
     <b>Rating: </b> <input type="number" id="score" min="1.0" max="10.0" step ="0.1"/> 
     <b>Year Released: </b> <input type="number" min="1900" max="2011" id="Yreleased" value="1985" size=4> 


     <p><input type="submit" name="Submit" id = "Submit" value="Add Game" class = "add games"></p> 
     </form> 



     <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> 

     <script type="text/javascript" 
     $(document).ready(function() { 

     $("a.deletebutton").click(function(){ 

     var del_id = element.attr("id"); 
     var info = 'id=' + del_id; 
     var parent = $(this).parent(); 
     if(confirm("Sure you want to delete this game? !")) 
     { 
     $.ajax({ 
     type: "get", 
     url: "delete.php", 
     data: parent.attr('id').replace('record-',"), 
     success: function(){ 
     } 
     }); 
     $(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast") 
     .animate({ opacity: "hide" }, "slow"); 
     } 
      return false; 
      }); 
      }); 
      </script> 




      </body> 

와 나는 추가에 대한 매우 간단한 PHP 파일을 가지고, 대한 삭제하고 dbconfig

delete.php

<?php 

// This is a sample code in case you wish to check the username from a mysql db table 
include("dbconfig.php"); 
if(($_GET['id']) 
{ 
$id=$_GET['id']; 

$sql = "DELETE from games where ID='.(int)$_GET['id']; 
$result= mysql_query($sql); 






} 

?> 

에 대한

이 나의은 add.php 내 dbconfig.php입니다에 대한 마지막

<?php 
include("dbconfig.php"); 

if(isset($_POST['Submit']) 

$name=$_POST['name']; 
$type=$_POST['type']; 
$rating=$_POST['score']; 
$release=$_POST['Yreleased']; 
$sql = ("INSERT INTO games VALUES ($name, $type, $rating, $release)"); 

echo " your game has been added to the list of games. "; 
?> 

및 내 dbconfig 마지막

<?php 
$user_name = "root"; 
$password = ""; 
$database = "gamebook"; 
$server = "localhost"; 


$bd = mysql_connect($server, $user_name, $password) or die ('I cannot connect to the  database because:' . mysql_error()); 
mysql_select_db($database); 
?> 

내가 처음으로 질문을 올리고 물을 때마다, 내가 용납 할 수없는 일을했거나 달리 수행해야만한다면 팁, 도움, 링크 또는 누군가가 나를 도울 수 있다면 감사 할 것입니다. 내 문제를 해결할 수 있습니다. 데이터베이스에서 읽을 수는 있지만 동적으로 추가하거나 삭제할 수는 없습니다.

+0

질문 무엇입니까? –

+0

게임을 추가하는 것과 동일한 DB를 새로 고치거나 제거하지 않고 레코드를 동적으로 삭제할 수 없습니다. 게임을 추가 할 수 없어서 데이터베이스에 반영된 것을 확인하십시오. 모든 코드가 올바르게 수행하는 것은 데이터베이스에서 읽기 및 레코드를 표시하는 것입니다. 각 레코드 아래의 삭제 버튼이 보이지만 작동하지 않습니다. – deli10

+0

문제를 특정 구성 요소로 좁히고 올바르게 포맷하십시오. –

답변

0

delete.php

<?php 
    require('dbconfig.php'); //we cannot continue without this file, thats why using require instead of include 
    if(isset($_GET['id'])){ 
    $id=(int)$_GET['id']; 
    $sql = 'DELETE FROM `games` WHERE `ID`="'.$id.'" LIMIT 1'; 
    mysql_query($sql); 
    echo 'deleted'; 
    } 
?> 

은 add.php

<?php 
    require('dbconfig.php'); //we cannot continue without this file, thats why using require instead of include 

    if(isset($_POST['Submit'])){ 

    $name=addslashes($_POST['name']); 
    $type=addslashes($_POST['type']); 
    $rating=addslashes($_POST['score']); 
    $release=addslashes($_POST['Yreleased']); 
    $sql = 'INSERT INTO `games` (`Name`,`Type`,`Rating`,`Release Year`) VALUES ("'.$name.'", "'.$type.'", "'.$rating.'", "'.$release.'")'; 
    mysql_query($sql); 
    if(!mysql_errno()) 
     echo " your game has been added to the list of games. "; 
    } 
?> 

의 index.php 여기에서 걸릴 : http://pastebin.com/NVbheAJZ

+0

정말 고마워요. 나는 당신이 게시 한 코드를 다시 읽고 그에 맞는 코드를 고쳤습니다. 그것이 나를 위해 문제를 해결하지 못했지만 그들은 더 깔끔한 방법입니다. 4 개의 필드 u가 테이블에 r을 썼습니다. 게임을 추가하려고하면 다음과 같은 오류가 발생합니다. Parse error : 구문 오류, 예기치 않은 '{'in C : \ xampp \ htdocs \ add.php on line 8 .. 삭제를 위해 버튼을 누릅니다. 모든 레코드가 있지만 나를 데려 가지 않습니다 .. 팁 내 코드를 디버깅하는 방법과 그것을 할 수 있다면 ... 모든 힌트를 부탁드립니다. 그리고 답장을 보내 주셔서 감사합니다 0leg 너무 .. 내 index.php 지금은 문제가 어디 있는지보고 시작합니다 – deli10

+0

당신의 브라우저 (FF 또는 크롬)에 대한 플러그인을 http://getfirebug.com/ 플러그인을 사용하는 것이 좋습니다 그럼 내가 버튼을 누르면 아약스 호출을 볼 수 있습니다. 나는 그것이 도움이되기를 바랍니다. – 0leg

+0

죄송합니다. 내 잘못입니다. 내 1 답변에서 add.php를 업데이 트하십시오 그리고 그것은 작동합니다. – 0leg

관련 문제