大学任务的小型社交网络

时间:2015-09-30 02:18:23

标签: php mysql

我正在完成大学任务,建立一个小型社交网站。 我被困在学生搜索页面上。

如果您不进行搜索,则会显示默认的20名学生。 如果你想按名字搜索,它就可以了。

但是,如果您想将某人添加为朋友,则可以在此处创建问题。我有一个正在郊游的循环添加到朋友按钮,当你添加一个朋友,然后它应该输出为该特定学生发送或添加的请求,但它为所有学生做了,我尝试了许多不同我知道,但没有&# 39;锻炼。

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 个答案:

答案 0 :(得分:0)

看看你是否能够使用它。我认为任务的分离很重要,所以你可以把每个部分都集中在一块上。最好的方法是创建函数或类,并将它们包含在页面编译中。它将帮助您整理页面并限制一次显示多少脚本。我无法测试这些元素中的一些,因为我的数据库中没有requests表,我猜你的数据库连接会像我一样工作(我也不是这样做的,但在理论上它应该工作)。最重要的是,它将通过隔离函数/类来帮助您分离任务:

<?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');