首页 > 解决方案 > 检查第 n 行 mysql 是否已经存在,如果存在则显示不同的回显

问题描述

我正在尝试开发一个电子商务网站,我将在其中放置一些产品。客户可以将产品放入他们喜欢的“愿望清单”中,同时按钮应尽快从“收集”更改为“收集” . 到目前为止我的代码:

在 dbconnect.php

function if_already_collected($collector_id){
    $db_conn=getConnection();
    mysqli_set_charset($db_conn,'utf8');

    if(!$db_conn)return false;


    $sql="SELECT collected_id from collection where collector_id=$collector_id";


    $result=$db_conn->query($sql);
    $db_conn->close();
    return $result->num_rows > 0;
}

在 member_profile.php 中

<?php 
 include_once("dbconnection.php");
  if(!isset($_SESSION['logged_in'])){
    header("Location: login.php");
    die();
   }
 /*USER INFO : GETTING ID*/
$uname = $_SESSION['username'];      
$pword = $_SESSION['password'];
$members = display_member_info($uname, $pword);   
 while($member = $members->fetch_assoc()) :
    $collector_id=$member['id'];
endwhile ; 
?>

<div class="member_card">


    <div class="member">    
        <?php $mems= 
     serach_members($query_name,$query_elaka,$query_division,$query_district,$query_thana); ?>

            <?php while ($mem= $mems->fetch_assoc()) : ?>

     <?php if (if_already_collected($collector_id)) { ?>
                       <table>
                         <tr>
                        <td><a href="member_collect.php?get_id_cll=<?php echo $mem['id']; ?> && 
                        get_name_cll=<?php echo $mem['full_name']; ?>">Collect</a></td>
                    </tr>
                    <?php }else{  ?>

                       <tr>
                         <td>Collected</td>
                      </tr>
                   </table>
                    <?php } ?>
                 <?php endwhile; ?>

             </div>

即使我单击“收集”(也存储在数据库中),这些代码也会为所有产品产生“收集”,并且即使我在替换条件语句时没有单击任何产品,也会为所有产品产生“收集”:

<?php if (!if_already_collected($collector_id)) { ?>

标签: phpmysqlfunctionsession

解决方案


该函数需要检查是否$mem['id']在用户的集合中。目前它只检查用户的收藏中是否有任何东西,而不是那个特定的项目。

function if_already_collected($collector_id, $collected_id){
    $db_conn=getConnection();
    mysqli_set_charset($db_conn,'utf8');

    if(!$db_conn)return false;

    $sql="SELECT 1 from collection where collector_id = ? and collected_id = ?";
    $stmt = $db_conn->prepare($sql);
    $stmt->bind_param("ii", $collector_id, $collected_id);
    $stmt->execute();
    $stmt->bind_result($ignore);
    $row = $stmt->fetch();

    $db_conn->close();
    return $row;
}

然后你会这样称呼它:

     <?php if (if_already_collected($collector_id, $mem['id'])) { ?>

我还展示了如何将代码转换为使用准备好的语句而不是替换变量,以防止 SQL 注入。


推荐阅读