【发布时间】:2014-01-27 19:26:05
【问题描述】:
我有一个简单但令人困惑的问题,特别适合像我这样自学成才的程序员...
我已经阅读了 PHP.NET 和 MYSQL.COM 中的不同文档,它们都解释了如何打开和关闭它,但对于这个问题并没有真正帮助,至少对我来说是这样。
我学到的方法如下
我需要一个文件来连接我的连接,例如 dbconnection.php 或 db.php,名称不重要,但内容不重要,所以这就是我一直在做的...
<?php
// con.php
$host = 'localhost';
$us = 'root'; // or whatever name for the user
$ps = 'abcd'; // your password
$db = 'abc'; // The name of your DB
$con = mysqli_connect ($host, $us, $ps, $db);
if (mysqli_connect_errno()) {
echo "DB server offline: ". $mysqli->connect_error;
exit();
}
所以我的 DB 有了我的连接,现在让我们去取一些西瓜
<?php
include ('con.php');
// Lets get our varibales $_GET or $_POST
// Lets clean our variables
// Lets make sure that the data is what we expect, numbers and letters
// because thats how I roll!
$query_one = "SELECT * FROM table 1 WHERE id = 1";
$r_one = mysqli_query($con, $query_one);
$rows = mysqli_fetch_assoc($r_one);
// now lets echo the results, or print_r() or json()...
mysqli_close($con); // this is pretty straight forward i think...
现在这是我的困惑...
<?php
include ('con.php');
// Lets get our varibales $_GET or $_POST
// Lets clean our variables
// Lets make sure that the data is what we expect, numbers and letters
// because thats how I roll!
$query_one = "SELECT * FROM table_1 WHERE id = '$ids'";
$r_one = mysqli_query($con, $query_one);
$rows = mysqli_fetch_assoc($r_one);
// If I closed here the second query doesn't get executed...
if ($rows['publish'] == 1) {
$query_two = "SELECT * FROM table_2 WHERE id_user = '$ids' AND items = '$items'";
// lets do some foreach or while
// If I closed here the first query still open...
}
// If I close here
mysqli_close($con); // Am I closing both queries?
// Let get some more data
// Should I close my third query
mysqli_close($con);
// hasn't this been close already? which mean that the third query never got
the change to execute... correct?
如你所见,在MYSQL.com它告诉你如何关闭它,和PHP.net几乎一样,但它没有告诉你什么时候关闭它..
如果 a = 1 进行查询然后关闭它...
否则,如果 a = 5 执行另一个查询然后关闭它,我认为这很简单,但是如果我的一个查询中继来自另一个查询的信息怎么办...
如果 a = 1 进行查询
然后做一些事情和更多事情以及大量的 IF
如果第二个查询的结果是 B,请执行另一个查询...等等...
可能是我想多了,那么还有另一种方式打开或者关闭MySQLi
$con_one = conectTodb();
// queries
$con_one ->close();
如果你有3个查询,con_one、con_two、con_three,那么你必须一个一个地关闭,比如con_one->close()、con_two->close()、con_three->close()...等等开……对吗?
我问这个是因为几个小时。以前我有一个错误告诉我与数据库的连接太多,因此无法处理信息......
结果是服务器配置错误,让我开始思考,如果这是真实情况,我该怎么办!???如果用户购买了东西然后 POW 怎么办! !!太多的连接,数据丢失......尽管这样会带来一些噩梦
我不知道...我的大脑现在正在冒热气...有人可以请!向我解释一下,如果没有太多要求,请提供一些例子......
非常感谢!
pd。在本地主机上,最大连接数为 10(IIS、WAMP、XAMP)...在共享主机上我认为是 25...
【问题讨论】:
-
请求结束时连接自动关闭;这就是为什么您需要在每个请求开始时进行连接;)。