我正在尝试使用包含相应用户名的XML文件列出与数据库中的用户名关联的ID。
我认为这可能与$ conn不是全局变量有关 是吗?
我使用以下代码:
<?php //idlister.php
require 'connectDB.php';
$xml=simplexml_load_file("names.xml") or die("Error:
Cannot create object");
foreach($xml->book as $book)
{
$username = (string)$book->username;
$sql = "SELECT `id`
FROM `directory`
WHERE `UserName` = '$username'
LIMIT 0 , 30";
if ($result = $conn->query($sql)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row["id"]."<br />";
}
/* free result set */
$result->free();
}
}
$conn->close();
?>
当我运行上面的代码时,浏览器会继续工作,直到遇到502 Gateway错误。
我测试了上面相同的代码,替换了#username; $ username&#39;与比尔&#39; (数据库中的名称),并获得相同的502网关错误。
但是当我从for循环中取出$ result = $ conn-&gt;查询($ sql)行时,我得到了我想要的结果:
<?php //idlister.php
require 'connectDB.php';
$xml=simplexml_load_file("names.xml") or die("Error:
Cannot create object");
$username = (string)$book->username;
$sql = "SELECT `id`
FROM `directory`
WHERE `UserName` = 'Bill'
LIMIT 0 , 30";
if ($result = $conn->query($sql)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row["id"]."<br />";
}
/* free result set */
$result->free();
}
$conn->close();
?>
// Printed&#34; 20&#34;,这是Bill的id
如何从foreach循环中获取结果,或者如何从XML文件中获取名称以在foreach循环之外搜索数据库?
XML示例:
<response>
<book>
<username>Sarah</username>
<gender>f</gender>
<age>23</age>
</book>
<book>
<username>Jonathan</username>
<gender>m</gender>
<age>33</age>
</book>
<book>
<username>Demonte</username>
<gender>m</gender>
<age>18</age>
</book>
</response>
连接文件:
<?php //connectDB.php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "Directory";
// Create connection to Directory
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection to the Directory failed: " . $conn->connect_error);
}
echo "<h2>Directory Connection Successful</h2>";
?>