php mysql内连接查询仅在同一查询的phpmyadmin返回四行时返回一排

发布于 2025-01-19 22:31:52 字数 4924 浏览 2 评论 0原文

我有两个表“最喜欢的”和“图像”:

  1. “最喜欢的”-包含列:
    • 用户名 (varchar) 用户的唯一标识符
    • viewkey (varchar) 图像的唯一标识符
    • 操作 (tinyint) 1 = 图片已被收藏
    • 创建(日期时间)时间用户喜爱的图像
  2. “图像”的时间 - 包含列:
    • 用户名 (varchar) 上传图像的用户的唯一标识符
    • viewkey (varchar) 上传图片的唯一标识符
    • 标题(文本)图像标题
    • 标签(文本)描述图像的 csv 格式标签
    • 文件名(文本)服务器上图像文件的路径
    • 上传(日期时间)用户上传时间

我想输出一个数组,其中包含当前登录用户收藏的所有图像,以便他们可以查看收藏的相册。

我这样做是使用自定义数据库类,该类具有改编自<的查询构建函数一个href="https://www.codexworld.com/like-dislike- rating-system-jquery-ajax-php/" rel="nofollow noreferrer">CodexWorld。我是连接表的新手,但我编写了函数 getJoin() 来在两个表之间构建 INNER JOIN 查询,该查询生成以下 MySQL 查询:

SELECT image.* 
FROM image 
INNER JOIN favorite ON image.viewkey=favorite.viewkey 
WHERE favorite.username = 'Caddy7676' 
GROUP BY image.title, image.tags, image.filename, image.uploaded, image.modified, image.username, image.viewkey

令人惊奇的是,当我在 phpMyAdmin 中运行此查询时,返回了 4 个正确的图像行,但是在我的 php 程序中,仅返回 1 个正确的行。没有其他人。它还生成一个数组,其中所有列都是字符串。我做错了什么?

  1. 函数 getJoin() - 构建并执行查询,返回数组
class DB {
    private $hostname = DB_HOST;
    private $username = DB_USER; 
    private $password = DB_PASS; 
    private $dbname = DB_NAME; 

    public function __construct() {
        if (!isset($this->db)) {
            // Connect to database
            $conn = new mysqli($this->hostname, $this->username, $this->password, $this->dbname);

            if ($conn->connect_error) {
                die ("Failed to connect with MySQL: " . $conn->connect_error);
            } else {
                $this->db = $conn;
            }
        }
    }

public function getJoin($table1, $table2, $conditions = array()) {
    if (array_key_exists("select", $conditions)) {
        $sql = " SELECT "; 
        $i = 0;
        foreach ($conditions['select'] as $tbl => $value) {
            $pre = ($i > 0)?' , ':'';
            $sql .= $pre . $tbl . "." . $value;
            $i++;
        }
        $sql .= ' FROM ' . $table1; 
    }

    if (array_key_exists("inner_join", $conditions)) {
        $sql .= " INNER JOIN " . $table2 . " ON " . $table1 . "." . $conditions['inner_join'] . "=" . $table2 . "." . $conditions['inner_join'];
        
    }

    if (array_key_exists("where", $conditions)) {
        $sql .= ' WHERE ';
        $i = 0;
        foreach($conditions['where'] as $key => $value) {
            $pre = ($i > 0)?" AND ":'';
            $sql .= $pre.$table2 . "." . $key ." = " . "'$value'" ;
            $i++;
        }
    } 

    if (array_key_exists("group_by", $conditions)) {
        $sql .= ' GROUP BY ';
        $i = 0;
        foreach($conditions['group_by'] as $key => $value) {
            $pre = ($i > 0)?", ":'';
            $sql .= $pre . $table1 . "." . $key;
            $i++;
        }
    }

    if (array_key_exists("order_by", $conditions)) {
        $sql .= ' ORDER BY ' . $conditions['order_by'] . ' DESC ';
    } 

    $result = $this->db->query($sql);

    if (array_key_exists("return_type", $conditions) && $conditions['return_type'] != 'all') {
        switch ($conditions['return_type']) {
            case 'count':
                $data = $result->num_rows;
                break;
            case 'single':
                $data = $result->fetch_assoc();
                break;
            default:
                $data = '';
        }
    } else {
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $data[] = $row;
            }
        }
    }
    echo $sql;
    return !empty($data)?$data:false;
}
  1. view_favorites.php 将所有参数传递给 getJoin() 并充实查询
$viewFavoritesDB = new DB();
$images = array ();

// Get all favorited images based on logged in username and favorite action
$conditions['select'] = array (
    'image' => '*'
);
$conditions['inner_join'] = 'viewkey';
$conditions['where'] = array (
    'username' => $_SESSION['username'],
);
$conditions['group_by'] = array (
    'title' => '',
    'tags' => '',
    'filename' => '',
    'uploaded' => '',
    'modified' => '',
    'username' => '',
    'viewkey' => '',
);
$images = $viewFavoritesDB->getJoin('image', 'favorite', $conditions);
  1. var_dump($images)
array (size=8)
  'id' => string '53' (length=2)
  'title' => string 'Green Triangle' (length=14)
  'tags' => string 'green,triangle,2-d' (length=18)
  'filename' => string '33238_1648833408.png' (length=20)
  'uploaded' => string '2022-04-01 13:16:21.790642' (length=26)
  'modified' => string '2022-04-07 01:25:11.000000' (length=26)
  'username' => string 'AgBRAT' (length=6)
  'viewkey' => string '62473379c82ec' (length=13)

I have two tables 'favorite' and 'image':

  1. 'favorite' - contains columns:
    • username (varchar) unique identifier for user
    • viewkey (varchar) unique identifier for image
    • action (tinyint) 1 = image was favorited
    • created (datetime) time user favorited image
  2. 'image' - contains columns:
    • username (varchar) unique identifier for user that uploaded image
    • viewkey (varchar) unique identifier for image uploaded
    • title (text) title of image
    • tags (text) csv formatted tags describing image
    • filename (text) path to image file on server
    • uploaded (datetime) time user uploaded

I want to output an array with all images favorited by the currently logged in user so they can view a favorited album.

I am doing so using a custom database class with query building functions adapted from CodexWorld. I am new to joining tables but I wrote the function getJoin() to build an INNER JOIN query between the two tables which produced the following MySQL query:

SELECT image.* 
FROM image 
INNER JOIN favorite ON image.viewkey=favorite.viewkey 
WHERE favorite.username = 'Caddy7676' 
GROUP BY image.title, image.tags, image.filename, image.uploaded, image.modified, image.username, image.viewkey

The kicker is when I run this query in phpMyAdmin, 4 correct rows of images are returned but within my php program, only 1 correct row is returned. No others. It also produces an array where all the columns are strings. What am I doing wrong?

  1. function getJoin() - builds and executes query returning an array
class DB {
    private $hostname = DB_HOST;
    private $username = DB_USER; 
    private $password = DB_PASS; 
    private $dbname = DB_NAME; 

    public function __construct() {
        if (!isset($this->db)) {
            // Connect to database
            $conn = new mysqli($this->hostname, $this->username, $this->password, $this->dbname);

            if ($conn->connect_error) {
                die ("Failed to connect with MySQL: " . $conn->connect_error);
            } else {
                $this->db = $conn;
            }
        }
    }

public function getJoin($table1, $table2, $conditions = array()) {
    if (array_key_exists("select", $conditions)) {
        $sql = " SELECT "; 
        $i = 0;
        foreach ($conditions['select'] as $tbl => $value) {
            $pre = ($i > 0)?' , ':'';
            $sql .= $pre . $tbl . "." . $value;
            $i++;
        }
        $sql .= ' FROM ' . $table1; 
    }

    if (array_key_exists("inner_join", $conditions)) {
        $sql .= " INNER JOIN " . $table2 . " ON " . $table1 . "." . $conditions['inner_join'] . "=" . $table2 . "." . $conditions['inner_join'];
        
    }

    if (array_key_exists("where", $conditions)) {
        $sql .= ' WHERE ';
        $i = 0;
        foreach($conditions['where'] as $key => $value) {
            $pre = ($i > 0)?" AND ":'';
            $sql .= $pre.$table2 . "." . $key ." = " . "'$value'" ;
            $i++;
        }
    } 

    if (array_key_exists("group_by", $conditions)) {
        $sql .= ' GROUP BY ';
        $i = 0;
        foreach($conditions['group_by'] as $key => $value) {
            $pre = ($i > 0)?", ":'';
            $sql .= $pre . $table1 . "." . $key;
            $i++;
        }
    }

    if (array_key_exists("order_by", $conditions)) {
        $sql .= ' ORDER BY ' . $conditions['order_by'] . ' DESC ';
    } 

    $result = $this->db->query($sql);

    if (array_key_exists("return_type", $conditions) && $conditions['return_type'] != 'all') {
        switch ($conditions['return_type']) {
            case 'count':
                $data = $result->num_rows;
                break;
            case 'single':
                $data = $result->fetch_assoc();
                break;
            default:
                $data = '';
        }
    } else {
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $data[] = $row;
            }
        }
    }
    echo $sql;
    return !empty($data)?$data:false;
}
  1. view_favorites.php passes all parameters to getJoin() and fleshes out the query
$viewFavoritesDB = new DB();
$images = array ();

// Get all favorited images based on logged in username and favorite action
$conditions['select'] = array (
    'image' => '*'
);
$conditions['inner_join'] = 'viewkey';
$conditions['where'] = array (
    'username' => $_SESSION['username'],
);
$conditions['group_by'] = array (
    'title' => '',
    'tags' => '',
    'filename' => '',
    'uploaded' => '',
    'modified' => '',
    'username' => '',
    'viewkey' => '',
);
$images = $viewFavoritesDB->getJoin('image', 'favorite', $conditions);
  1. var_dump($images)
array (size=8)
  'id' => string '53' (length=2)
  'title' => string 'Green Triangle' (length=14)
  'tags' => string 'green,triangle,2-d' (length=18)
  'filename' => string '33238_1648833408.png' (length=20)
  'uploaded' => string '2022-04-01 13:16:21.790642' (length=26)
  'modified' => string '2022-04-07 01:25:11.000000' (length=26)
  'username' => string 'AgBRAT' (length=6)
  'viewkey' => string '62473379c82ec' (length=13)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

就像说晚安 2025-01-26 22:31:52

已回答

我之前使用过变量 $conditions,它有一个“单”行参数剩余。使用 $conditions = array (); 重新初始化 $conditions 清除了所有内容。谢谢您的评论。

Answered

I had previously used the variable $conditions which had a 'single' row paramater leftover. Reinitializing $conditions with $conditions = array (); cleared everything up. Thank you for the comments.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文