单击该值更新数据库

时间:2014-10-31 05:42:55

标签: jquery

我想管理我的图片库。有一个图像管理页面。每个图像的默认标志为“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>

1 个答案:

答案 0 :(得分: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'] - 和使用这些来更新数据库记录。