php - 格式化数据库查询的结果

标签 php html mysql

到目前为止,我有以下 php,它允许用户在数据库的特定列中搜索并显示所有结果。

<?php
require("header.php");
if(isset($_REQUEST['searching'])){ //check if form has been submitted
echo"<h2>Results</H2><p>";
connect('final');//connect to DB
//set the values from search form
$field = $_POST['field'];
$query = $_POST['query']; 

    $query = htmlspecialchars($query); // stop HTML characters
    $query = mysql_real_escape_string($query); //stop SQL injection

     $data = mysql_query("SELECT *
     FROM customer 
     INNER JOIN address ON customer.ID = address.customer_ID
     LEFT OUTER JOIN sites ON address.ID = sites.address_ID 
     WHERE customer.ID IN (SELECT customer.ID 
     FROM customer
     INNER JOIN address ON customer.ID = address.customer_ID 
     LEFT OUTER JOIN sites ON address.ID = sites.address_ID
     WHERE upper(customer.$field) LIKE'%$query%')") ;//query the DB with search field in colleumn selected//

     //$data = mysql_query("SELECT * FROM customer INNER JOIN address ON customer.ID = address.Customer_ID LEFT OUTER JOIN sites ON address.ID = sites.address_ID WHERE upper(customer.$field) LIKE'%$query%'") ;

    if($data === FALSE) {
    $error = 'Query error:'.mysql_error();
    echo $error;
    }
    else
    {
    while($results = mysql_fetch_array($data)){// puts data from database into array, loops until no more
            echo "<br>"; 
            echo $results['First_Name']; 
            echo " "; 
            echo $results['Surname']; 
            echo " "; 
            echo $results['Company_Name']; 
            echo " "; 
            echo $results['Telephone']; 
            echo " "; 
            echo $results['Alt_Telephone']; 
            echo " "; 
            echo $results['line_1']; 
            echo " "; 
            echo $results['line2']; 
            echo " "; 
            echo $results['town']; 
            echo " "; 
            echo $results['postcode'];
            echo " "; 
            echo $results['site_name'];


            //posts results from db query
        }
    }


        $anymatches=mysql_num_rows($data); //checks if the querys returned any results
            if ($anymatches == 0) 
                    { 
                        echo "Sorry, but we can not find an entry to match your query<br><br>"; 
                    } 

    } 

但是,当我使用 echo 输出时,它只会在页面的最顶部显示所有结果,并将所有 html 内容推到其下方。

如何设置它的格式以便它出现在我的 html 内容中?例如,在搜索按钮下方。

最佳答案

解决方案是不要回显将在顶部显示的内容,因为 PHP 首先处理代码然后加载 html,因此它将回显页面顶部的数据。

解决方案是将结果分配到 while 循环中的数组中,然后使用该数组在 html 中显示它。

关于php - 格式化数据库查询的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16208898/

相关文章:

php - Laravel Eloquent - 日期属性未作为 Carbon 对象检索

php - Zend_Search_Lucene 尝试分配 3503812093817007931 字节

关联数组上的php array_sum

mysql - 查询无法执行,或者等待时间太长

mysql - Windows MySQL 区分大小写

javascript - Ajax 没有将数据完全发布到 php 文件

javascript - 如何复制部分文本并使用 Jquery 填充输入

javascript - 使用平板电脑大小的屏幕时尝试删除额外的空间

javascript - jQuery 选择调用 AJAX 的元素

php - ä ö 字符编码,在 PHP 中,Zend MySQL- 应用程序