dousa1630 2012-12-17 04:11
浏览 7
已采纳

PHP / SQL不确定如何处理

I have two tables, categories and info.

categories looks like:

id | name 

info looks like:

id | parent_id | name | url

parent_id is the id from categories.

I have a form where a user can add more than one url. There is a button that can be pressed to make more url fields appear. If there is more than one url, then url2, url3, etc are added to the database.

info will then look like:

id | parent_id | name | url | url2 | url3

Is this an appropriate approach?

If so, what if info is like this:

id | parent_id |name  |url            |url2          |url3
1  | 1         |One   |http://cnn.com |
2  | 1         |Two   |http://msn.com |http://aol.com|

When I view One or Two or w/e, how do I query to get their urls?

I know I can do:

$mysqli->query("SELECT i.url FROM info AS i LEFT JOIN categories AS c ON i.parent_id = c.id");

But this is dependent on me putting i.url, i.url2, i.url3 and I would have to create a separate query for each info. I want it so PHP determines how many and what i.url to select.

So it should be:

$mysqli->query("SELECT (PHP determines what i.url to put here depending on what info page I'm viewing) FROM info AS i LEFT JOIN categories AS c ON i.parent_id = c.id");
  • 写回答

2条回答 默认 最新

  • dongnai5905 2012-12-17 04:16
    关注

    If you go that path you will have a bunch of columns with null values and encounter issues with queries, which is pretty much what you are describing.

    I would create a different table (perhaps urls) that maps info with urls. For example:

    url_id | info_id | url 
    

    This is the Repeated Attributes design pattern which is concisely explained here: http://www.tomjewett.com/dbdesign/dbdesign.php?page=phone.php

    Here is an example on how to query:

    SELECT i.*, url
    FROM info i JOIN urls u ON i.id = u.info_id
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥15 流式socket文件传输答疑
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接