PHP:查询多个表的问题

时间:2016-02-12 02:41:15

标签: php multidimensional-array

我的搜索功能在查询单个表时效果很好。但是当我在同一个数据库中查询多个表时(使用' UNION'),我遇到了两个问题:

1 即可。 $query(特别是行if ( ! $query->num_rows ))给出     错误:Notice: Trying to get property of non-object in function.php line 18

我认为这与现在如何访问数组有关 它包含多个表中的行?

2. 一旦获得这些值,我不确定如何从不同的表中提取字段信息。只要有一个表,这个foreach循环就可以了:

foreach($_SESSION['search_output']['results'] as $value){ 
echo $value->title; 
echo"<br>";
}

但是,当有多个表时,如何访问不同命名的字段。我在考虑切换案例,但是如何使用程序方法获取表名?

非常感谢您在理解如何处理此问题时提供任何帮助。

以下是文件
function.php

<?php    
function search($conn, $search_term) {
    $sanitized =  $conn->real_escape_string($search_term);

    $query = $conn->query("(SELECT * FROM news WHERE title LIKE '%{$sanitized}%' OR body LIKE '%{$sanitized}%' OR sources LIKE '%{$sanitized}%' 
      OR date LIKE '%{$sanitized}%')
      UNION
      (SELECT * FROM events WHERE eventname LIKE '%{$sanitized}%' OR eventsumm LIKE '%{$sanitized}%' OR eventdate LIKE '%{$sanitized}%')
      UNION
      (SELECT * FROM recipes WHERE rectitle LIKE '%{$sanitized}%' OR recsummary LIKE '%{$sanitized}%')
      UNION
      (SELECT * FROM reviews WHERE bookname LIKE '%{$sanitized}%' OR revbody LIKE '%{$sanitized}%' OR revsource LIKE '%{$sanitized}%')
      UNION
      (SELECT * FROM foodiq WHERE iqitem LIKE '%{$sanitized}%' OR iqbody LIKE '%{$sanitized}%')");


    if ( ! $query->num_rows ) {
      return false;
    }

 $rows = array(); // ADD THIS
    while( $row = $query->fetch_object() ) {
      $rows[] = $row;
    }

    $search_results = array(
      'count' => $query->num_rows,
      'results' => $rows
    );

    return $search_results;
  }
  ?>

的index.php

<?php require_once  ('setup.php');
require_once  ('function.php');
    if (session_id() === "") { session_start(); }
?>

<!DOCTYPE html>
<html>
<body>


<?php
if ( isset( $_GET['s'] ) ) {
  $search_results='';
  $search_term = htmlspecialchars($_GET['s'], ENT_QUOTES);
  $search_results = search($conn, $search_term);  
  }
?>

<form role="search" method="get" class="search-form" action="">
                <label>
                <input type="search" class="search-field" placeholder="Search" value="searchitem" name="s">
                </label>
                <input type="submit" class="search-submit" value="Search">              
</form>

  <?php if (isset($search_results)) : 
  print_r($search_results); exit;
        $_SESSION['search_output'] = $search_results; 
        header("Location: final.php");
        exit;
   endif; ?>

<body>
</html>

final.php

<?php 
session_start(); 
?> 

<!DOCTYPE html> 
<html> 
<body> 



<?php 
if(isset($_SESSION['search_output']) && is_array($_SESSION['search_output'])) 
{ 
echo $_SESSION['search_output']['count']. " result(s) found <br>";
foreach($_SESSION['search_output']['results'] as $value){ 
echo $value->title; 
echo"<br>";
}

} 
else
echo "Sorry, no results found"; 


?> 

<body> 
</html>

setup.php

    <?php
    $hn = 'localhost';
    $db = 'kkh';
    $un = 'water';
    $pw = 'water'; 



    #DB Connection:
     $conn = new mysqli($hn, $un, $pw, $db);
     if ($conn->connect_error) die($conn->connect_error);
    ?>

1 个答案:

答案 0 :(得分:1)

  1. 你应该检查->query之后是否有任何连接错误:

    /* check error */
    if ($conn->error) {
        printf("Query failed: %s\n", $conn->error);
        exit();
    }
    

    请注意,它与$conn->connect_error不一样。

  2. 您可以使用union语句中第一个表的字段名来访问您的字段。

    我们假设表格news包含以下字段:idtitleauthordate_created。然后只需使用$row->id$row->title

    要知道哪个表与相关行有关,您可能需要使用以下内容:

    SELECT *, 'news' AS source FROM news .... 
        UNION 
    SELECT *, 'events' AS source FROM events ...
    

    然后$row->source将包含您的表格。

  3. 请注意,当您使用UNION语句时,每个SELECT 中的所有字段必须具有相同的列数! Read more