【问题标题】:Why is it that my mysql content in xampp cannot be displayed using php script?为什么我的xampp中的mysql内容无法使用php脚本显示?
【发布时间】:2012-09-22 01:01:31
【问题描述】:

我在 xampp 中创建了一个数据库,制作了一个非常简单的 php 脚本来访问/连接到 xampp 中的 mysql(将其保存到 xampp/htdocs)。连接没问题,但是当我在浏览器上运行它时,只出现了我在php中创建的表,而mysql中的数据没有出现。可能是什么问题?

这里是php代码:

<?php

// Make a MySQL Connection

mysql_connect("localhost", "root", "password") or die(mysql_error());

mysql_select_db("test") or die(mysql_error());

// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM example") 
or die(mysql_error()); 

echo "<table border='1'>";
echo "<tr> <th>Name</th> <th>Age</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>"; 
echo $row['name'];
echo "</td><td>"; 
echo $row['age'];
echo "</td></tr>"; 
} 

echo "</table>";
?>

【问题讨论】:

  • 示例表中有数据吗?
  • 开始学习如何调试 PHP 脚本。您的错误报告配置是什么?浏览器中的 HTML 源代码是怎么说的(不是标准视图,而是视图源代码)?

标签: php mysql


【解决方案1】:

如果您刚开始使用 PHP 和 MySQL,为什么不开始学习 PDO,因为 mysql_* 函数已被弃用。

确保example 表中有数据,与 PHPMyAdmin 核实并关注this nice guide

你的代码应该是:

<?php
    $db = new PDO('mysql:host=localhost;dbname=test;charset=UTF-8', 'username', 'password', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

    echo "<table border='1'>";
    echo "<tr> <th>Name</th> <th>Age</th> </tr>";

    $stmt = $db->query("SELECT * FROM example");
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        echo "<tr><td>"; 
        echo $row['name'];
        echo "</td><td>"; 
        echo $row['age'];
        echo "</td></tr>"; 
    }

    echo "</table>";
?>

【讨论】:

  • php新手觉得难,可以改用mysqli
猜你喜欢
  • 2018-12-16
  • 2011-06-18
  • 2022-01-11
  • 2021-11-10
  • 2019-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-28
相关资源
最近更新 更多