gpt4 book ai didi

php - 如何使用 PHP 从 url 访问 mysql 表中的字段

转载 作者:行者123 更新时间:2023-11-29 00:13:36 26 4
gpt4 key购买 nike

您好,我正在尝试访问 mysql 表中的字段,结果来自 url,例如 localhost/test.php=id=2

顺便说一句,我是 xml 和 php 的菜鸟,所以请原谅我..

任何建议或教程将不胜感激..

这是我正在处理的代码

<?php
header("Content-Type: text/xml");
$xmlBody = '<?xml version="1.0" encoding="ISO-8859-1"?>';
$xmlBody .= "<XML>";

$dbhost = 'localhost:3036';
$dbuser = 'nas';
$dbpass = 'root';
mysql_select_db('db_home') or die("no database");

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die (mysql_error());

$sql = mysql_query("SELECT * FROM table_gas ORDER BY datetime DESC LIMIT 0, 20");

while($row = mysql_fetch_array($sql)){

$id = $row["gas_id"];
$timestamp = $row["timestamp"];
$value = $row["value"];
$datetime = strftime("%b %d, %Y", strtotime($row["datetime"]));
$xmlBody .= '
<Data>
<DataID>' . $id . '</DataID>
<DataTime>' . $timestamp . '</DataTime>
<DataValue>' . $value . '</DataValue>
<DataTime>' . $datetime . '</DataTime>
</Data>';
}
mysql_close();
$xmlBody .= "</XML>";
echo $xmlBody;
?>

当我将它放入地址栏 local/xmltest.php?DataID=2 时,我得到一个空白屏幕..

最佳答案

首先,你不应该再使用mysql_了。我个人喜欢 PDO,所以这是我的答案

如下所述,url 应为 localhost/xmltest.php?DataID=2

header("Content-Type: text/xml");
$xmlBody = '<?xml version="1.0" encoding="ISO-8859-1"?>';
$xmlBody .= "<XML>";

$dbhost = 'localhost'; //No need to set the port if default is 3306
$dbuser = 'nas';
$dbpass = 'root';
$dbname = 'db_home';

// Check if ?id= is set or not
if ( isset($_GET['DataID']) ) {
// Initiate the connect to the MySQL DB using PDO extention. You'll need to activate PDO if it's not done then restart Apache
$db = new PDO('mysql:host='. $dbhost .';dbname='. $dbname, $dbuser, $dbpass);

$query = $db->prepare("SELECT * FROM table_gas WHERE id = :id ORDER BY datetime DESC LIMIT 0, 20");
$query->bindParam(':id', $_GET['DataID']); // Grab the value inside ?id= and pass it in the query
$query->execute(); // Execute the query with the parameters
$result = $query->fetchAll(); //Fetch everything and store it in a variable

foreach ($result as $row) { // I like using foreach but while loop works too
$xmlBody .= '
<Data>
<DataID>' . $row["gas_id"] . '</DataID>
<DataTime>' . $row["timestamp"] . '</DataTime>
<DataValue>' . $row["value"] . '</DataValue>
<DataTime>' . strftime("%b %d, %Y", strtotime($row["datetime"])) . '</DataTime>
</Data>';
}
$xmlBody .= "</XML>";
echo $xmlBody;
} else {
echo "Invalid ID."; //Output error message if test.php?id= is not set
}

关于php - 如何使用 PHP 从 url 访问 mysql 表中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23770891/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com