PHP数据库从数据库查询外键数据

时间:2018-09-27 18:52:25

标签: php mysql sql database

我尝试构建一个简单的博客系统。数据库表如下。

帖子

    $(function() {

  var form = $('#ajax-contact');


  var formMessages = $('#form-messages');


    $(form).submit(function(event) {

        event.preventDefault();


        var formData = $(form).serialize();


        $.ajax({
          type: 'POST',
          url: $(form).attr('action'),
          data: formData,
          dataType: 'json'
          }).done(function(response) {

          $(formMessages).removeClass('error');
          $(formMessages).addClass('success');


          $(formMessages).text(response);


          $('#name').val('');
          $('#email').val('');
          $('#message').val('');
          })

          .fail(function(data) {
          $(formMessages).removeClass('success');
          $(formMessages).addClass('error');

          if (data.responseText !== '') {
            $(formMessages).text(data.responseText);
          } else {
            $(formMessages).text('Oops! An error occured and your message could not be sent.');
          };
      });
   });
});

类别

   <?php


    if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $name = strip_tags(trim($_POST["name"]));
    $name = str_replace(array("\r","\n"),array(" "," "),$name);
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $message = trim($_POST["message"]);


    if (empty($name) OR empty($message) OR !filter_var($email, 
    FILTER_VALIDATE_EMAIL)) {

        http_response_code(400);
        echo "Oops! There was a problem with your submission. Please 
    complete the form and try again.";
        exit;
    }

    $recipient = "name@example.com";


    $subject = "New contact from $name";


    $email_content = "Name: $name\n";
    $email_content .= "Email: $email\n\n";
    $email_content .= "Message:\n$message\n";


    $email_headers = "From: $name <$email>";


    if (mail($recipient, $subject, $email_content, $email_headers)) {

        http_response_code(200);
        echo "Thank You! Your message has been sent.";
    } else {

        http_response_code(500);
        echo "Oops! Something went wrong and we couldn't send your 
    message.";
    }

    } else {

    http_response_code(403);
    echo "There was a problem with your submission, please try again.";
    }

    ?>

帖子类别

+----+----------+-------------+
|id  | title    | content     |
+----+----------+-------------+
|1   | Tile     | Content     |
+----+----------+-------------+
|2   | Tile 2   | Content 2   |
+----+----------+-------------+

我使用此代码

+--------+-------------+
|id      | category    |
+--------+-------------+
|1       | Category1   |
+--------+-------------+
|2       | Category2   |
+--------+-------------+
|3       | Category3   |
+--------+-------------+

我知道这不是获取类别的好方法。

甚至一次又一次地查询同一类别。

任何人都可以给我一些指南/资源/教程来学习PHP逻辑,OOP和最佳实践。 我如何使用OOP PHP处理此问题。

并且还请提供用于获取类别的答案。

我不想将+--------+-------------+ |postID | categoryID | +--------+-------------+ |1 | 1 | +--------+-------------+ |1 | 2 | +--------+-------------+ |1 | 3 | +--------+-------------+ |2 | 2 | +--------+-------------+ |2 | 3 | +--------+-------------+ <?php $posts = DB::get("SELECT * FROM `posts` LIMIT 5"); foreach ($posts as $post) { echo $post["title"]; $category_ids = DB::get("SELECT categoryID FROM `post_categories` WHERE postID = " . $post["id"]); $ids = join(", ", $category_ids); $categorys = DB::get("SELECT * FROM `categories` WHERE id IN (" . $ids . ")"); foreach ($categorys as $category) { echo '<a href="...">' . $category["category"] . '</a>'; } echo $post["content"]; } ?> 表联接到获取数据,因为那里的列很少。

在一个帖子中也可能有多个类别。

2 个答案:

答案 0 :(得分:1)

为什么不希望加入..与单个加入的查询相比,您的代码更加复杂且耗时

span

答案 1 :(得分:0)

您的答案有点宽泛 关于您的具体实现,我将合并类别查询,生成一个输出,然后回显一次

<?php
    $posts = DB::get("SELECT * FROM `posts` LIMIT 5");
$output = '';
    foreach ($posts as $post) {
     $categories = DB::get("SELECT c.* FROM `post_categories` pc INNER JOIN categories c ON c.id = pc.category_id WHERE id = " . $post["id"]);

        $output .= $post["title"];

        foreach ($categories as $category) {
            $output .=  '<a href="...">' . $category["category"] . '</a>';
        }

        $output .=  $post["content"];
    }

echo $output;
?>

如果您想要更多订单,我建议您使用framework,这将帮助您将订单整理好 并可能会读到有关MVC

的信息