dongmi1663 2015-09-30 02:18
浏览 43
已采纳

大学任务的小型社交网络

I am doing my university assignment, making a small social networking website. I am stuck on student search page.

if you don't search , it shows default 20 students. if you want to search by name, it does that fine.

however if you want to add someone as friend, this is where it create the problem. i have a while loop that is outing add to friend button, when you add a friend, then it should output request sent or added for that particular student but it does that for all the student, i tried many different i know but that didn't workout.

This is how it works, really bad

        <?php
        try{
          include('includes/connect.php');

          $user_id = $_SESSION['id'];
          $found = 'false';

          $sql = "SELECT * FROM requests WHERE user_id = $user_id";
          $stmt_request_status = $connection->prepare($sql);
          $stmt_request_status->execute();
          if($stmt_request_status->rowCount()) {
            $request_result = array();
            while($request_row = $stmt_request_status->fetchObject()){
              $request_result[] =  $request_row->status;
            }
          }

          if(isset($_POST['addfriend'])) {
            $request_id = $_POST['request_id'];
            $sql = "INSERT INTO requests (user_id, request_id, status) VALUES ('$user_id', :request_id, '0')";
            $stmt = $connection->prepare($sql);
            $stmt->bindParam(':request_id', $request_id);
            $stmt->execute();
          }


          $sql = "SELECT * FROM users ORDER BY id DESC LIMIT 20";
          $result = $connection->query($sql);

          $count = "SELECT count(*) FROM users";
          $count_result = $connection->query($count);
          $total_records = $count_result->fetchColumn();

          if(isset($_GET['submit'])) {

            $keyword = '%%%' . $_GET['keyword'] . '%%%';
            $sql = "SELECT * FROM users WHERE first_name like :keyword OR last_name like :keyword";

            $stmt = $connection->prepare($sql);
            $stmt->bindParam(':keyword', $keyword);
            $stmt->execute();

            if($stmt->rowCount()) {
              $found = 'true';
            } else {
              $msg = 'No results found';
            }
          }

        }


        catch(PDOException $e) {
          echo "Connection failed: " . $e->getMessage();
        }
        ?>



        <div class="row">
          <div class="medium-12 columns">
            <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">
              <div class="row">
                <div class="large-12 columns">
                  <div class="row collapse">
                    <div class="small-10 columns">
                      <input type="text" name="keyword" placeholder="Whats new in your class?">
                    </div>
                    <div class="small-2 columns">
                      <input type="submit" name="submit" class="button postfix" value="Go!">
                    </div>
                  </div>
                </div>
              </div>
            </form>


          </div>
        </div>

        <div class="row">
          <div class="large-12 columns">
            <?php echo isset($msg) ? '<span class="error">' . $msg . '</span>' : '';
            ?>



            <?php
            if($found !== 'true') {
              echo "<h4>Recent Students</h4>";
              while($row = $result->fetchObject()){ ?>
              <?php echo $row->first_name; ?>

              <form action="" method="post" accept-charset="utf-8">
                <input type="hidden" name="request_id" value="<?php echo $row->id; ?>">
                <?php
                if(isset($request_result)){
                  foreach ($request_result as  $status) {
                    if($status == 1) {
                      echo '<p class="button secondary tiny">Already Friends</p>';
                    }
                    else if ($status == 0) {
                      echo '<p class="button secondary tiny">Request Already Sent</p>';
                    }
                  }
                }
                ?>
                <input type="submit" name="addfriend" value="Add Friend" class="button tiny success">


              </form>
              <hr>
        <?php   } // while loop
        } // end if
        ?>


        <?php

        if($found == 'true') {
          echo "<h4>Student Found</h4>";
          while($row = $stmt->fetchObject()){ ?>
          <?php echo $row->first_name; ?>
        <?php  }  // while loop
        } // end if
        ?>

      </div>
    </div>

    <hr>
    <div class="row">
      <div class="large-12 columns">
        <p><strong>Total Students so far : <?php echo $total_records; ?> </strong></p>
      </div>
    </div>

    <?php include('includes/footer.php'); ?>


    But i believe this is where it is messing around, the result is so unwanting

    <?php
            if($found !== 'true') {
              echo "<h4>Recent Students</h4>";
              while($row = $result->fetchObject()){ ?>
              <?php echo $row->first_name; ?>

              <form action="" method="post" accept-charset="utf-8">
                <input type="hidden" name="request_id" value="<?php echo $row->id; ?>">
                <?php
                if(isset($request_result)){
                  foreach ($request_result as  $status) {
                    if($status == 1) {
                      echo '<p class="button secondary tiny">Already Friends</p>';
                    }
                    else if ($status == 0) {
                      echo '<p class="button secondary tiny">Request Already Sent</p>';
                    }
                  }
                }
                ?>
                <input type="submit" name="addfriend" value="Add Friend" class="button tiny success">


              </form>
              <hr>
        <?php   } // while loop
        } // end if
        ?>
  • 写回答

1条回答 默认 最新

  • dpdp42233 2015-09-30 22:19
    关注

    See if you are able to work with this. I think separation of task is important so you can focus on each part as a piece. Best way to do this is make functions or classes and include them on page compiling. It will help your page be organized and limit how much script is being displayed all at one time. Some of these elements I can not test because I don't have a requests table in my database and I am guessing your database connection will work as I have it (I also do not do my connection this way but in theory it should work). Bottom line, it will help you to separate out tasks by isolating with functions/classes:

    <?php
    // Create a "global" database
    class DBConnection
        {
            private static  $con;
            private function __construct()
                {
                }
    
            public  static  function Initialize()
                {
                    // Include your connection once here
                    // I don't know where your connect.php is in relation
                    // to this page, so I am assuming it's in the
                    // same directory (root)
                    include_once(__DIR__.'/includes/connect.php');
                    // Assign the static connection here
                    if(!isset(self::$con)) {
                            self::$con  =   $connection;
                        }
                    // Return either the new or current connection
                    return self::$con;
                }
        }
    // Wrap the connection in a function for quick access
    function connection()
        {   
            return DBConnection::Initialize();
        }
    // Fetch and set to data array
    function fetch($sql = false,$bind = false)
        {
            if(empty($sql))
                return 0;
            try {
                    $con    =   connection();
                    $query  =   $con->prepare($sql);
    
                    if(!empty($bind) && is_array($bind)) {
                            foreach($bind as $key => $value) {
                                    $array[":{$key}"]   =   $value;
                                }
                            $query->execute($array);
                        }
                    else
                        $query->execute();
    
    
                    while($row = $query->fetch(PDO::FETCH_ASSOC)) {
                            $result[]   =   $row;
                        }
    
                    return (!empty($result))? $result : 0;
                }
            catch (PDOException $e) {
                    return 0;
                }
        }
    // Quick write function
    function write($sql = false,$bind = false)
        {
            if(empty($sql))
                return 0;
            try {
                    $con    =   connection();
                    $query  =   $con->prepare($sql);
    
                    if(!empty($bind) && is_array($bind)) {
                            foreach($bind as $key => $value) {
                                    $array[":{$key}"]   =   $value;
                                }
                            $query->execute($array);
                        }
                    else
                        $query->execute();
    
                    return true;
                }
            catch (PDOException $e) {
                    return false;
                }
        }
    // Quick way to run this query
    function get_requests($id = false,$obj = false)
        {
            $result =   fetch("SELECT * FROM `requests` WHERE `user_id` = :0",array($id));
    
            if($result == 0)
                return 0;
            // Return an object if desired
            return ($obj)? json_decode(json_encode($result)) : $result;
        }
    // Quick way to write to a friend
    function add_friend($request = false)
        {
            if(empty($request) || empty($_SESSION['id']))
                return 0;
    
            return write("INSERT INTO `requests` (`user_id`, `request_id`, `status`) VALUES (:0, :1, '0')",array($_SESSION['id'],$request));
        }
    // Quick way to select users
    function get_users($limit = 20)
        {
            return fetch("SELECT * FROM `users` ORDER BY `id` DESC LIMIT {$limit}");
        }
    // Easy count function
    function count_users()
        {
            $count  =   fetch("SELECT COUNT(*) as count FROM `users`");
            return $count[0]['count'];
        }
    // Quick search function
    function find_users($search = false)
        {
            $search =   '%%%'.$search.'%%%';
            return  fetch("SELECT * FROM `users` WHERE `first_name` like :0 OR `last_name` like :1",array($search,$search));
        }
    
    session_start();
    $_SESSION['id'] =   29;
    // If add-a-friend request
    if(isset($_POST['addfriend']))
        add_friend($_POST['request_id']);
    // If submitting a search
    $search     =   (isset($_GET['search']))? find_users($_GET['keyword']) : false;
    // Get the user id
    $requests   =   (!empty($_SESSION['id']))? get_requests($_SESSION['id']) : false;
    // Count total users
    $count  =   count_users();
    // If not logged in, just show footer
    if(empty($_SESSION['id'])) {
            include('includes/footer.php');
            exit;
        }
    ?>
    <div class="row">
        <div class="medium-12 columns">
            <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">
                <div class="row">
                    <div class="large-12 columns">
                        <div class="row collapse">
                            <div class="small-10 columns">
                                <input type="text" name="keyword" placeholder="Whats new in your class?">
                            </div>
                            <div class="small-2 columns">
                                <input type="submit" name="search" class="button postfix" value="Go!">
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
    <div class="row">
        <div class="large-12 columns">
    <?php
    if(!isset($_GET['search'])) { 
    ?>      <h4>Recent Students</h4>
    <?php   foreach(get_users() as $row) {
    ?>
            <?php echo $row['first_name']; ?>
            <form action="" method="post" accept-charset="utf-8">
                <input type="hidden" name="request_id" value="<?php echo $row['id']; ?>">
    <?php           if(isset($request_result)) {
                            foreach($request_result as  $status) {
                                    if($status == 1) {
    ?>          <p class="button secondary tiny">Already Friends</p>
    <?php                               }
                                    elseif($status == 0) {
    ?>          <p class="button secondary tiny">Request Already Sent</p>
    <?php                               }
                                }
                        }
    ?>          <input type="submit" name="addfriend" value="Add Friend" class="button tiny success">
            </form>
            <hr>
    <?php       }
        }
    // If searching
    if(isset($_GET['search'])) {
            // If not found
            if($search == 0) {
    ?>      <span class="error">Friend not found!</span>
    <?php       }
            // If found
            else {
    ?>      <h4><?php echo $setCount = count($search);?> Student<?php echo ($setCount > 1)? "s":"";?> Found</h4>
    <?php           foreach($search as $row) {
    ?>      <?php echo $row['first_name']; ?>
    <?php               }
                } 
        }
    ?>  </div>
    </div>
    <hr>
    <div class="row">
        <div class="large-12 columns">
            <p><strong>Total Students so far : <?php echo $count; ?> </strong></p>
        </div>
    </div>
    <?php include('includes/footer.php');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效