无法从PHP中的MySQL表中的行中删除内容?

时间:2015-10-28 09:07:08

标签: php html mysql

这是我的代码:

$html = $_POST['html'];
$username   = $_POST['username'];
$saving     = $_POST['saving'];
$username   = $connection->real_escape_string($username);
$html       = $connection->real_escape_string($html);
$query      = $connection->query("SELECT * from members WHERE username ='$username'");
$matches    = mysqli_num_rows($query);
if ($matches == 1) {
   $row               = mysqli_fetch_array($query);
   $all_articles      = $row['readlater'];
   if($saving == true){
      $all_articles      .= $html.'§';
      $connection->query("UPDATE members SET readlater = '$all_articles' WHERE username ='$username'");
   } else {
      $all_articles      = str_replace($html.'§','',$all_articles);
      $connection->query("UPDATE members SET readlater = '$all_articles' WHERE username ='$username'");
   }
}

这是jQuery代码:

if (localStorage.getItem(key) === null) {
    localStorage.setItem(key, 'Saved');
    $(this).css('color','#278F00');
    $(this).closest('.item').find('.fa-bookmark-o').css('font-weight','bold');
    $.ajax({
      type: "POST",
      url: '/savedarticle.php',
      data: {
        html: innerHTML,
        username: '<?php echo $_SESSION['user']; ?>',
        saving: true        
    }
  }); 
}else {
    localStorage.removeItem(key);
    $(this).css('color','#000');
    $(this).closest('.item').find('.fa-bookmark-o').css('font-weight','normal');
    $.ajax({
      type: "POST",
      url: '/savedarticle.php',
      data: {
        html: innerHTML,
        username: '<?php echo $_SESSION['user']; ?>',
        saving: false       
      }
    }); 
}

我是以§作为分隔符的行的HTML,因为这个字符不会出现在普通的HTML中。如果文章已经在行中并且用户点击了unsave按钮,我想使用str_replace删除文章,但它不会替换任何内容。

此外,只有在文章被保存两次后才点击保存按钮。我可以稍后再解决。

编辑:我想$saving变量总是传递值true。这也会导致多次保存同一篇文章。

我需要帮助删除未保存的文章,并且还想知道是否有更好的方法来执行此操作。

以下是示例HTML块:

<h2>Nexus 5X Receiving Update Today to Build MDB08I<small class="label droidlife">Droid Life</small><button type="button" class="close bkmrk-btn" style="color: rgb(0, 0, 0);"><i class="fa fa-bookmark-o" style="font-weight: normal;"></i></button></h2><p>Nexus 5X devices that are arriving at the homes of Android fans today are receiving a small 42MB update almost immediately out of the box. The build is arriving as&nbsp;MDB08I, which is a build first seen as a factory image earlier in the week.&nbsp; Tough to know what’s new in it, but it’s likely...</p><p>Read More — <a data-id="1445529719-Unv5Og" data-toggle="modal" class="modal-link store-link" href="http://www.droid-life.com/2015/10/21/nexus-5x-receiving-update-today-to-build-mdb08i/" data-target="#myModal">Nexus 5X Receiving Update Today to Build MDB08I</a></p><hr>§

1 个答案:

答案 0 :(得分:2)

你正在接近错误。不是将所有文章存储在由魔术字符分隔的单个字段中,而是应该有一个单独的表,其中包含用户名和文本字段。然后,您可以为每个用户任意添加和删除该表的多行。如果您想获得用户的所有结果,只需执行fields['ECStruct1']