【问题标题】:Retrieve data from a table with a condition where and check the record in another table in one SELECT query从具有条件 where 的表中检索数据并在一个 SELECT 查询中检查另一个表中的记录
【发布时间】:2017-05-12 12:49:51
【问题描述】:

需要在一个查询中从一个表中检索数据,条件为“where”,同时检查另一个表是否存在ip user,然后在显示信息的同时显示结果,同时显示信息是否存在ip

表格:

Ips (
   Id int (10) not null auto_increment,
   User_id int (10) not null default '0',
   Ip varchar (40) not null
)

Users (
   Id int (11) not null auto_increment,
   Username varchar (35) not null,
   Email varchar (200) not null,
   Salt varchar (40) not null,
   Password varchar (40) not null,
   Country varchar (40) not null
)

我想得到什么:

  1. 从用户表中获取条件为“where country = 'paris' LIMIT 0.10”的数据

  2. 每次使用 $_SERVER ['REMOTE_ADDR'] 检查 ips 表是否存在用户 ID 和 ip 地址时

  3. 如果表中有记录ips在while中显示信息

我目前的问题代码:

<?php

include "connect.php";

$db = mysqli_query($connect, "SELECT * FROM users JOIN ips ON ips.user_id=users.id ON ips.ip='".$_SERVER['REMOTE_ADDR']."' WHERE users.country='paris' LIMIT 0,10");

if (mysqli_num_rows($db)>0){
    while ($data = mysqli_fetch_assoc($db)){
        print_r($data);
        if (filter_var($data['ip'], FILTER_VALIDATE_IP)){ //check var is ip adress
            echo '<br>isset ip';
        }
    }
}else{
    echo 'not records';
}

?>

Ps:我在提案中找不到答案

【问题讨论】:

  • 你能把你做的初始代码贴出来
  • 请阅读What topics can I ask aboutHow to ask a good questionthe perfect question 以及如何创建Minimal, Complete and Verifiable example SO 不是 免费的编码或代码转换或调试或教程或图书馆查找服务我们尝试修复您的代码,我们不编写您的代码
  • 它叫做JOIN!在the manual 中查找或查找a tutorial
  • 来自您的代码:... JOIN ips ON ips.user_id=users.id ON ips.ip= ... 仅限 1! ON 应该连接表,过滤条件进入WHERE 子句。 FROM `Users` `u` INNER JOIN `Ips` `i` ON `u`.`id` = `i`.`User_id` WHERE ... AND ... ORDER BY `u`.`Id`; 连接表是最好的方法,因为连接比子查询有更好的性能。顺便说一句:不要将任何客户端数据插入您的 SQL 字符串。改为使用带有绑定参数的准备好的语句。

标签: php mysql


【解决方案1】:

试试这个查询:

SELECT * FROM Users WHERE Country ='paris' AND Id IN (SELECT User_id  FROM Ips  WHERE Ip = 'ip_adddress')

【讨论】:

  • 如果给出了名称和 IP,您的示例将有效。我编写了代码:SELECT * FROM users WHERE username LIKE '% NAME%' AND ID IN (SELECT user_id FROM Ips WHERE Ip = 'IP ADRESS') 需要像在常规查询中一样搜索用户:SELECT * FROM users WHERE username LIKE '%NAME%' 另外,检查 ips 表以查看是否有记录包含指定的 Ip 地址以及该行的用户 id。如果有这样的记录,将显示消息并正常返回结果。图片里的东西我都写了:iv.pl/images/11692056913053727462.png
猜你喜欢
  • 1970-01-01
  • 2018-01-21
  • 1970-01-01
  • 2020-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多