php - 如何在 while 循环中保留 mysqli_fetch_array() 值?

标签 php mysql mysqli

不知道题主问的够不够清楚

我正在从表 A 中获取一些 ID,查询返回多行。我还从其他表 B 中获取一些其他 ID。我的问题是我想检查表 A 的 ID 是否与表 B 中的 ID 相同,如果是,我必须打印一个值,否则其他值应该是打印。我该如何实现?

我曾尝试使用两个 while 循环(一个在另一个循环中),但内部 while 循环只执行一次并且值变为 null。所以它无法检查条件。

<?php
include('includes/template.php');
$user=$_SESSION['login_user'];

if(isset($_POST['action'])){
if($_POST['action']=="searchb"){
  $query=secure_input($_POST['searchbox']);
                  if(!empty($query)){
                    $sql="select id,username, name, email from mysql.registration_zany where name like '%".$query."' and privacy=0";
                          $res=mysqli_query($con,$sql);
                 $resmsg="<div class='alert alert-success' role='alert'>SEARCH RESULTS FOR :<b>".$query."</b></div>";
             }
      }
}
$sql2="select id from mysql.friends where id2='".$id."' and Request_Status=1 and id !=".$id;
$res2=mysqli_query($con,$sql2);
$i=1;
while($row=mysqli_fetch_array($res,MYSQLI_NUM)){
$flag=0;
  while($fr[i]=mysqli_fetch_array($res2,MYSQLI_NUM)){
    #echo $row[0];
if($fr[i][0]==$row[0]){
  $flag=1;
 }
  }
$i++;
if($flag){
$table="<div class='row'>
<div class='col-xs-6 col-md-4'>
  <div class='thumbnail'>
UserName:".$row[1]."<br>Profile:".$row[2]."<br>E-mail:".$row[3]."
<p><span class='label label-info'>Friend</span></p></div></div>";
echo $table;
}
else{
$table="<div class='row'>
<div class='col-xs-6 col-md-4'>
<div class='thumbnail'>
 UserName:".$row[1]."<br>Profile:".$row[2]."<br>E-mail:".$row[3]."
 <p><form action='request.php' method='post'>
 <input name='action' type='hidden' value='".$row[0]."' >
  <input type='submit' class='btn btn-primary' name='req' value='Send Request'>
  </form></p></div></div>";
 echo $table;
 }
  }
 ?>

谢谢。

最佳答案

如果我没理解错的话 您要检查第一个表中的每个 ID 与第二个表中的每个值吗?

为简单起见,我假设这些表存在于不同的服务器上并且无法连接。

如果将所有 ID 存储到数组 $table1[] = $row['id'];

在浏览表 2 时,您将能够使用 PHP 的 in_array 函数进行搜索。

in_array($row['id'], $table1)(如果值存在则为真)

如果您只想知道两个表中存在的内容,您可以在 SQL 中执行此操作。不知道你的数据库结构我会松散地做这件事

$sql="SELECT
 q1.id,
 count(SELECT q2.id from mysql.friends q2 WHERE q2.id2=q1.id and Request_Status=1 and q2.id !=q1.id) as 'hasmatch',
 q1.username,
 q1.name,
 q1.email FROM mysql.registration_zany q1 WHERE q1.name LIKE '%".$query."' AND q1.privacy=0";

我会玩这个,我有点生疏,它可能会丢弃没有匹配的值。我希望计数能消除这个问题。

关于php - 如何在 while 循环中保留 mysqli_fetch_array() 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37118878/

相关文章:

php - CodeIgniter 分页结果问题

php - Flutter未处理的异常: FormatException: Unexpected character (at character 4)

php - 将图标添加到自定义 WooCommerce 支付网关

涉及反引号的 MySQL 错误

php - mysqli数组到子查询中的mysql?

php - 如何将用户信息和项目获取到数据库中的同一个表中

php - 克隆依赖项的副本(依赖注入(inject))是否有意义?

mysql - 在表中递归查找内容的最有效方法?

mysql - Spring使用Windows用户而不是给定的用户名 'root'来访问mysql

php - 在 mysql 中编写查询时