首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP XML解析问题

问PHP XML解析问题
EN

Stack Overflow用户
提问于 2011-08-23 04:11:33
回答 2查看 114关注 0票数 2

我希望能够用PHP解析SQL数据库以输出XML,但是我不能让它显示表名和所有内容。我需要一些帮助,下面是我的代码,没有登录信息:我已经定义了db服务器,mdb user和pass,以及db名称;还需要定义其他什么吗?

代码语言:javascript
复制
<?php
// connection to the database
$dbhandle = mysql_connect(DB_SERVER, DB_USER, DB_PASS)
   or die("Unable to connect to MySQL");

// select a database to work with
$selected = mysql_select_db(DB_NAME, $dbhandle)
   or die("Could not select data");

// return all available tables 
$result_tbl = mysql_query( "SHOW TABLES FROM "DB_NAME, $dbhandle );

$tables = array();
while ($row = mysql_fetch_row($result_tbl)) {
   $tables[] = $row[0];
}

$output = "<?xml version=\"1.0\" ?>\n";
$output .= "<schema>";

// iterate over each table and return the fields for each table
foreach ( $tables as $table ) {
   $output .= "<table name=\"$table\">";
   $result_fld = mysql_query( "SHOW FIELDS FROM "$table, $dbhandle );

   while( $row1 = mysql_fetch_row($result_fld) ) {
      $output .= "<field name=\"$row1[0]\" type=\"$row1[1]\"";
      $output .= ($row1[3] == "PRI") ? " primary_key=\"yes\" />" : " />";
   }

   $output .= "</table>";
}

$output .= "</schema>"; 

// tell the browser what kind of file is come in
header("Content-type: text/xml");
// print out XML that describes the schema
echo $output;

// close the connection
mysql_close($dbhandle);
?> 
EN

回答 2

Stack Overflow用户

发布于 2011-08-23 04:20:40

我认为在这个问题上最好使用标准的php类XmlWriter。看看http://www.php.net/manual/en/book.xmlwriter.php

票数 2
EN

Stack Overflow用户

发布于 2011-08-23 04:53:47

代码语言:javascript
复制
$result_tbl = mysql_query( "SHOW TABLES FROM "DB_NAME, $dbhandle );
                                             ^^^---typo

$result_fld = mysql_query( "SHOW FIELDS FROM "$table, $dbhandle );
                                             ^^^---typo

您的查询中至少有两个拼写错误。你最有可能想要的是:

代码语言:javascript
复制
$result_tbl = mysql_query("SHOW TABLES FROM " . DB_NAME, $dbhandle) or die(mysql_error());
and
$result_fld = mysql_query("SHOW FIELDS FROM $table", $dbhandle) or die(mysql_error());

注意第一个上的连接运算符(.)和添加的or die(...)。永远不要假设查询成功。即使查询字符串本身在语法上是正确的,也有太多其他原因不能检查错误条件。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7153032

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档