简体   繁体   English

PHP中的多个MySQL数据库查询

[英]Multiple mysql database queries in php

I have a PHP document which contains mostly html, but also some MySql queries which look like this: 我有一个PHP文档,其中大部分包含html,但也包含一些MySql查询,如下所示:

<?php
require_once('connectdata.php');

$db = mysqli_connect(DB_HOST, DB_BENUTZER, DB_PASSWORT, DB_NAME);

$myquery = "SELECT name FROM Entries WHERE typ = 'Communication' ORDER BY name";

$result = mysqli_query($db, $myquery);

while($row = mysqli_fetch_object($result))
 {
 echo "$row->name";

 }

mysqli_close($db);

I am using this exact code several times in my document to echo the data I want to display. 我在文档中多次使用此精确代码来回显我要显示的数据。 Is this a good practice or is there a way to just connect once get all the data and echo them later in the document? 这是一个好习惯还是有一种方法,可以在获取所有数据后立即进行连接并在文档中稍后回显它们?

Is it bad if I leave it like that? 如果我那样离开就不好了吗?

You already have your connection. 您已经有连接。 When you have to make a query just use the syntax: 当您必须进行查询时,请使用以下语法:

$myquery = "SELECT name FROM Entries WHERE typ = 'Communication' ORDER BY name";

You can include : 您可以包括:

$db = mysqli_connect(DB_HOST, DB_BENUTZER, DB_PASSWORT, DB_NAME);

in your connectdata.php file, which you only include ONCE per file(where is needed). connectdata.php文件中,每个文件仅包含一次(需要)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM