2014-10-31 62 views
0

我想管理我的图片库。有一个图像管理页面。每个图像的默认标志都是'0'。当我在图像管理页面中点击'0'时,它变为'1'。它完美的作品。点击数值更新数据库

我想要的是我想同时更新数据库的标志值为'1'。我该怎么做。

我的代码是

<?php 

# Init the MySQL Connection 
    mysql_connect("localhost", "root", "") or die(mysql_error()) ; 
mysql_select_db("selfie") or die(mysql_error()) ; 

# Prepare the SELECT Query 
    $selectSQL = 'SELECT * FROM `image_upload` INNER JOIN user_table 
ON image_upload.user_id=user_table.user_id WHERE flag="0" ORDER BY timestamp DESC'; 
# Execute the SELECT Query 
    if(!($selectRes = mysql_query($selectSQL))){ 
    echo 'Retrieval of data from Database Failed - #'.mysql_errno().': '.mysql_error(); 
    }else{ 
     ?> 
<table border="2"> 

     <thead id="head"> 
    <tr> 
     <th id="head">User name</th> 
     <th>Category</th> 
     <th>Description</th> 
     <th>Image</th> 
     <th>Location</th> 
     <th>Status</th> 
    </tr> 
</thead> 
    <tbody> 
    <?php 
     if(mysql_num_rows($selectRes)==0){ 
     echo '<tr><td colspan="4">No Rows Returned</td></tr>'; 
     }else{ 
      while($row = mysql_fetch_assoc($selectRes)){ 
       echo "<tr> 
       <td>{$row['user_name']}</td> 
       <td>{$row['category']}</td> 
      <td>{$row['description']}</td> 
      <td ><img src='uploads/".$row['image']."'width=300px height=200px></td> 

     <td onclick='changeText(this)'>{$row['flag']}</td> 
      </tr>\n"; 

     } 
     } 
    ?> 
    </tbody> 
</table> 
    <?php 

    } 

?> 

我的剧本是

<script> 
function changeText(id) { 

id.innerHTML = "1"; 

} 
</script> 
+2

您需要从函数changeText()发送一个AJAX请求。 我不想把它放在这里,你会错过学习AJAX的乐趣。 访问http://www.w3schools.com/ajax/ – 2014-10-31 05:45:43

+0

与jQuery使用ajax来更改您在数据库中的值 – Robin 2014-10-31 05:45:51

+0

我试过了。但这不是工作。其他的事情是我也找不到错误。因为我是网络开发新手 – Lanka 2014-10-31 06:35:10

回答

0

它总是从您的标记分隔您的JS很好的做法。因此,通过改变开始:

<td onclick='changeText(this)'>{$row['flag']}</td> 

要:

<td class="change-text" data-user="{$row['user_name']}">{$row['flag']}</td> 

然后使用以下更新的代码更改标志。请注意,代码中包含Ajax调用,并且您的网页上标记一个成功的数据库更新后,才会更新:

$(function() { 
    $('.change-text').on('click', function() { 
     var text = $(this).text().trim(); 
     if(text === "0") { 
      $.post('updateText.php', {flag: 1,user_name:$(this).data('user')}) 
      .done(function(data) { 
       //depending on what is returned you may want to update the flag 
       //if only you get the desired response 
       $(this).html(1); 
      }); 
     } 
    }); 
}); 

最后,写一个新的PHP,updateText.php,接收两个参数的脚本; flaguser_name(如果可用,您可以使用id或您的主键代替user_name) - $_POST['flag']$_POST['user_name'] - 并使用它们更新数据库记录。