繁体   English   中英

使用mysql将数据库信息提取到PHP脚本中的html表中

[英]Using mysql to pull database information into html tables inside PHP script

首先,我真的希望我不要因为这个问题而被打败,但是我愿意冒风险,以便指出正确的方向,这样我才能学习。

我有一个.php脚本,在我的PHP脚本中,我编写了连接MySQL数据库的代码。

这是问题:

我有一张桌子,可用于非常简单地展示食品。 目前我有:

<table width="1024" border="0" cellpadding="10" cellspacing="5" align="center">
    <tr>
    <td colspan="2"><font>Item Name</font></td>
    <td colspan="2"><font>Item Name</font></td>
    <td colspan="2"><font>Item Name</font></td>
    </tr>

它继续与其他表行元素...

它在哪里说“项目名称”,我如何输入代码来提取数据库信息。 我拥有的数据库名称是“TEST”,我希望每个项目名称列出“ITEM”表中的不同项目。

任何帮助都会受到赞赏。

你真的需要对此进行更多的研究。 这是一个Php代码示例,它从w3学校提供的数据库中提取数据。 请参见http://www.w3schools.com/php/php_mysql_select.asp

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM Persons");

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";

 while($row = mysqli_fetch_array($result))
 {
 echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "</tr>";
 }
echo "</table>";

mysqli_close($con);
?> 

您必须迭代数据库中的结果,否则您将只能访问第一行(或数组指针所在的位置)。

您的问题是编程的基础知识,网络上有关于此主题的数百万资源。 我只会给你一个小样本代码,从这里开始调试和修改你的口味。

//Connect to MySQL Database
$connection = mysql_connect('host', 'user', 'password') or die("Connection error. Details: ".mysql_error());
//Select the database
$db_select = mysql_select_db('dbname', $connection);

//Create the query
$query = mysql_query("SELECT * FROM `foods`") or die("Error in query. Details: ".mysql_error());

//Check if the query has results, and iterate over it
if (mysql_num_rows($query) > 0)
{
    //Creates the table
    echo '<table>';

    //Iterate over the MySQL results and print the data
    while ($result = mysql_fetch_assoc($query))
    {
        echo '
        <tr>
            <td>'.$result['item_name'].'</td>
        </tr>
        ';
    }
    echo '</table>';
}
else
{
    echo "Your query hasn't returned results";
}

试试这个,不要忘记更改mysql主机名,用户名,密码,数据库名称和表名。

问候。

尝试这个:

 $conn = mysql_connect('host', 'user', 'password') or die("Connection error. Details:".mysql_error()); 

$db_select = mysql_select_db('<your_db_name', $conn);
$sql = mysql_query("SELECT * FROM `foods`") 

if($sql)
{

echo '<table>';


while ($result = mysql_fetch_assoc($query))
{
    echo '<tr><td>'.$result['<field_name1>'].'</td>';
    echo '<td>'.$result['<field_name2>'].'</td>';
      .....
      .....
    echo '</tr>'; 
 }
 echo '</table>';
 }
else
{
 echo "no results is there";
}

注意:您应该知道您的表列名称,在field_names中提供相同的名称,您可以打印表中存在的任意数量的列。 谢谢

暂无
暂无

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

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