Home Backend Development PHP Tutorial Detailed explanation of the abuse of echo statement in PHP

Detailed explanation of the abuse of echo statement in PHP

Mar 13, 2018 am 10:17 AM
echo php Detailed explanation

First of all, let me briefly introduce the structure of my program and the functions to be implemented: In short, the main function of this program is to display a certain point with a known address, longitude and latitude on the map. The program is mainly divided into There are three modules: front-end (html+css+js), back-end (php), and database (mysql). The three modules implement the following functions respectively.
Database: stores the latitude and longitude information of a certain location (because the project requires the display of the location of a certain hardware device of the company, so I call it - device address);
Backend: implemented by this backend The main function is to query the address information (latitude and longitude) of the equipment that meets the conditions in the database through SQL statements, and then output the address information in json format so that the front-end page can be obtained through ajax;

//后台代码:<?phpsession_start ();//查找数据库header ( "Content-type:text/html;charset=utf-8" );include "conn.php";
mysql_query("set names utf8");//读取旧信息$startTime = date("Y-m-d H:i:s", strtotime(&#39;-300 minutes&#39;, time()));$UserName = $_SESSION[&#39;UserName&#39;];//echo $UserName ;//$UserName = &#39;wld&#39;;$sql = "select * from user_device where UserName=&#39;".$UserName."&#39; and UseFlag=1";$result_set = mysql_query($sql);$snstr=0;$longstr=0;$lastr=0;$statusstr=0;    while($row=mysql_fetch_array($result_set)){            $sql = "select * from device where  SN=&#39;".$row[&#39;SN&#39;]."&#39;";            $res = mysql_query($sql);            $result=mysql_fetch_assoc($res);        /////////////////////////在线监测/////////////////////  
        $sql_queryt="SELECT * FROM device_online_list WHERE SN=&#39;".$SN."&#39;  order by Time desc limit 1";        $result_sett=mysql_query($sql_queryt);        $resultt=mysql_fetch_assoc($result_sett);        if($result_sett)
        {   
            if(strtotime($startTime)<strtotime($resultt[&#39;Time&#39;]))
            {   
                    $runstr=1;
            }            else $runstr=0;
        }else $runstr=0;    ///////////////////////////////////////////////////////
            if($snstr){            $snstr=$snstr.&#39;_&#39;;            $snstr=$snstr.$row[&#39;SN&#39;];            $longstr=$longstr.&#39;_&#39;;            $longstr=$longstr.$result[Longtitude];            $lastr=$lastr.&#39;_&#39;;            $lastr=$lastr.$result[Latitude];            $statusstr=$statusstr.&#39;_&#39;;            $statusstr=$statusstr.$runstr;
            }else{                $snstr=$row[&#39;SN&#39;];                $longstr=$result[Longtitude];                $lastr=$result[Latitude];                $statusstr=$runstr;
            }
    }$resultJson = array("SNstr"=>$snstr, "Long"=>$longstr, "La"=>$lastr,"Status"=>$statusstr);//json格式的数组echo urldecode(json_encode($resultJson));//Json格式输出 */?>
Copy after login

Front-end: The main function of the front end is to display a map by calling the Baidu Map API, and fill in the longitude and latitude information obtained from the background through js (ajax) as location parameters into the map point function to realize the function of displaying a certain point on the map. (Of course, the information obtained from the background in my code is not only longitude and latitude, but because it is a map program, the focus is mainly on longitude and latitude, so only the longitude and latitude are mentioned in the explanation process, and other information is ignored);

//下面是前端代码:<!DOCTYPE html><html lang="en"><head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>设备地图</title>
   <style type="text/css">
        body, html{width: 100%;height: 100%;margin:0;font-family:"微软雅黑";}
        #dev_map{height:500px;width:100%;}
    </style> 
    <script type="text/javascript" src="jquery-1.12.1.js"></script> 
    <script type="text/javascript" src="http://api.map.baidu.com/api?&v=1.3"></script></head><body><p class="dev_map" id="dev_map"></p><!-- <p><button type="button" onclick="theLocation()">设备地图</button></p> --></body></html><script>var map = new BMap.Map("dev_map");    // 创建Map实例map.centerAndZoom(new BMap.Point(114.317, 30.594), 5);  // 初始化地图,设置中心点坐标和地图级别//添加地图类型控件map.addControl(new BMap.MapTypeControl({
    mapTypes:[
        BMAP_NORMAL_MAP,
        BMAP_HYBRID_MAP
    ]}));     
map.setCurrentCity("武汉");          // 设置地图显示的城市 此项是必须设置的map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放var arr_longitude = new Array();var arr_latitude = new Array();var arr_sn = new Array();var arr_status = new Array();var arr_point = new Array();var mapSpots = new Array;var url = "http://image.tupian114.com/20140419/09274112.png";var content;var myIcon = new BMap.Icon(url, new BMap.Size(40,30));var opts = {
                width : 180,     // 信息窗口宽度
                height: 180,     // 信息窗口高度
                title : "信息窗口" , // 信息窗口标题
                enableMessage:true//设置允许信息窗发送短息
               };// //获取经纬度  
  $(function()
  {
    $.ajax({
                url: "mysql.search.handle.php",
                type: "GET",
                dataType:"json",
                async:false,
                success:function(data)
                {   //alert(data.Long.split("_").length);
                    for(var i=0;i<data.Long.split("_").length;i++)
                    {
                        arr_longitude[i]=data.Long.split("_")[i];
                        arr_latitude[i] = data.La.split("_")[i];
                        arr_sn[i] = data.SNstr.split("_")[i];
                        arr_status[i] = data.Status.split("_")[i];
                        arr_point[i] = new BMap.Point(arr_longitude[i],arr_latitude[i]);                    //  marker = new BMap.Marker(arr_point[i]);
                    //  map.addOverlay(marker);
                    }
                    addSpots(data.Long.split("_").length);
                }
                });
 }); function addSpots(arr_length){
 alert("您有"+arr_length+"台设备!");     for(var i=0;i<arr_length;i++)
         {
            content = "";
            content = "<p><span>SN码:" + arr_sn[i] + "</span></br>" +                             "<span>设备状态:" + translateOnline(arr_status[i]) + "</span></br>" +                             "<p class=&#39;btn&#39;><a href=&#39;../DevAlarm/DevAla.html?SN=" + arr_sn[i] + "&#39; target=&#39;fname&#39;"
                             + "&#39;>报警配置</a></p>" +"<p class=&#39;btn&#39;><a href=&#39;../DevAlarmView/DevAlarmView.html?SN=" + arr_sn[i] + "&#39; target=&#39;fname&#39;"
                             + "&#39;>报警信息</a></p>"+"<p class=&#39;btn&#39;><a href=&#39;../DevRun/DevRun.html?SN=" + arr_sn[i] + "&#39; target=&#39;fname&#39;"
                             + "&#39;>实时数据</a></p>"+"<p class=&#39;btn&#39;><a href=&#39;../history/history.html?SN=" + arr_sn[i] + "&#39; target=&#39;fname&#39;"
                             + "&#39;>历史数据</a></p>"+"<p class=&#39;btn&#39;><a href=&#39;../DevCfg/DevCfg.html?SN=" + arr_sn[i] + "&#39; target=&#39;fname&#39;"
                             + "&#39;>数据可视与报警开关配置</a></p>";
            marker = new BMap.Marker(arr_point[i]);
            map.addOverlay(marker);            //var lable =  new BMap.Label(content,{offset:new BMap.Size(20,-10)});
            //marker.setLabel(lable);
            addClickHandler(content,marker); //添加点击处理程序(点击会出现sn码等信息)
         }
 }function addClickHandler(content,marker){
    marker.addEventListener("click",function(e){
        openInfo(content,e)}
    );
}function translateOnline(code){
    if (code == 0) {return "离线";}    else if(code == 1) {return "在线";}    else{return "error";}
}function openInfo(content,e){
    var p = e.target;    var point = new BMap.Point(p.getPosition().lng, p.getPosition().lat);    var infoWindow = new BMap.InfoWindow(content,opts);  // 创建信息窗口对象 
    map.openInfoWindow(infoWindow,point); //开启信息窗口}</script>
Copy after login

Here we only focus on the js part of the code, and re-post these key codes below for easy viewing:

var arr_longitude = new Array();var arr_latitude = new Array();var arr_sn = new Array();var arr_status = new Array();var arr_point = new Array();var mapSpots = new Array;var url = "http://image.tupian114.com/20140419/09274112.png";var content;var myIcon = new BMap.Icon(url, new BMap.Size(40,30));var opts = {
                width : 180,     // 信息窗口宽度
                height: 180,     // 信息窗口高度
                title : "信息窗口" , // 信息窗口标题
                enableMessage:true//设置允许信息窗发送短息
               };// //获取经纬度  
  $(function()
  {
    $.ajax({
                url: "mysql.search.handle.php",
                type: "GET",
                dataType:"json",
                async:false,
                success:function(data)
                {   
            //  alert(data.Status);//弹出接收到的数据,调试用
            //  alert(data.La);//弹出接收到的数据,调试用
            //  alert(data.SNstr);//弹出接收到的数据,调试用
            //  alert(data.Long.split("_").length);//split是实现从一串用特定符号来连接的字符串中一次提取有用字符的功能(如me_you_he 用‘_’连接,用split可实现对me、you、he进行提取)
                    var longstring=data.Long+&#39;&#39;;                    var lastring=data.La+&#39;&#39;;                    var SNstring=data.SNstr+&#39;&#39;;                    var Statusstring=data.Status+&#39;&#39;;                    for(var i=0;i < longstring.split("_").length;i++)
                    {
                        arr_longitude[i]=longstring.split("_")[i];
                        arr_latitude[i] = lastring.split("_")[i];
                        arr_sn[i] = SNstring.split("_")[i];
                        arr_status[i] = Statusstring.split("_")[i];                    //  alert("设备状态"+arr_status[i]);
                        arr_point[i] = new BMap.Point(arr_longitude[i],arr_latitude[i]);
                        marker = new BMap.Marker(arr_point[i]);
                        map.addOverlay(marker);
                    }
                    addSpots(longstring.split("_").length);
                } ,
                error: function(XMLHttpRequest, textStatus, errorThrown) {//这个error函数调试时非常有用,如果解析不正确,将会弹出错误框                alert(XMLHttpRequest.responseText); 
                    alert(XMLHttpRequest.status);
                    alert(XMLHttpRequest.readyState);
                    alert(textStatus); // parser error;
                }
                });
 });
Copy after login

In the initial process of writing the code, the background echoed a lot of debugging in the program due to the need to debug the program. Information, as shown in the figure:

Detailed explanation of the abuse of echo statement in PHP

, but this information is not in json format. When these non-json format information are echoed, they will be received by the front desk. However, the ajax at the front end is designated to be received in json format, so when a file in a non-json format is received, the ajax program will not enter the success to execute, but will enter the error to pop up an error message. At the same time, the browser will pop up according to the type. Errors such as:
XML error: root directory not found (Firefox), flie could not be load:... (Google chrome) and other errors.


Lessons learned: When the background outputs data in json format for the front desk to get, remember that except when echo outputs useful data, echo cannot be used to output all other useless data, otherwise This will cause an error in the foreground data reception format.


The above is my little experience in the project process. If there are any fallacies, please criticize and correct them! ,

Related recommendations:

Detailed explanation of the difference between using commas and dots for echo in php

php outputs one or more String function echo

# Do you know the difference between echo and print in php?

The above is the detailed content of Detailed explanation of the abuse of echo statement in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles