我想从 MySql 表中检索数据。我正在使用 Xampp、phpMyAdmin 等...我一步一步地遵循了本教程:https://www.youtube.com/watch?v=IHdd02IK2Jg
但是我得到这个错误:
Notice: Undefined variable: records in C:\XAMPP\htdocs\display_prsc.php on line 29
还有一个警告:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, null given in C:\XAMPP\htdocs\display_prsc.php on line 29
它只在我运行时显示列名。
<? php
//make connection
mysql_connect('localhost','root','');
//select_db
mysql_select_db('mynewdb');
$sql="SELECT * FROM new";
$records=mysql_query($sql);
?>
<html>
<head>
<title>Program Scores Table</title>
<body>
<table width="600" border="1" cellpadding="1" cellspacing="1">
<tr>
<th>Year</th>
<th>Criteria</th>
<th>Score</th>
<tr>
<?php
while ($new=mysql_fetch_assoc($records)){
echo"<tr>";
echo"<td>".$new['py']."</td>";
echo"<td>".$new['pcrit']."</td>";
echo"<td>".$new['psco']."</td>";
echo"</tr>";
}
?>
</table>
</body>
</head>
</html>
最佳答案
您的代码中有一些错误:
1.错误的 php 开始标记
您必须删除 php 开始标记中的空格,例如
<?php
2。奇怪的 html
几乎你的整个html都是错的!我建议您阅读一本书或观看基本的 html 教程
所以你的整个代码应该是这样的:
<?php
//make connection
mysql_connect('localhost', 'root', '');
//select_db
mysql_select_db('mynewdb');
$sql = "SELECT * FROM new";
$records = mysql_query($sql);
?>
<html>
<head>
<title>Program Scores Table</title>
</head> <!-- head tag closed here -->
<body>
<table width="600" border="1" cellpadding="1" cellspacing="1">
<tr>
<th>Year</th>
<th>Criteria</th>
<th>Score</th>
</tr> <!-- forgot / to close the tag -->
<?php
while ($new = mysql_fetch_assoc($records)){
echo "<tr>";
echo "<td>" . $new['py'] . "</td>";
echo "<td>" . $new['pcrit'] . "</td>";
echo "<td>" . $new['psco'] . "</td>";
echo "</tr>";
}
?>
</table>
</body>
</html>
旁注:
1.有什么可以改进的?
- 我会做一些基本的错误检查,例如如果连接失败等等
- 使用
mysqli_*
使用准备好的语句,或PDO
使用准备好的语句,它们会更安全! (我们生活在 2015 年) - (另外,如果您教程中的人使用
mysql_*
,请更改教程!)
这样您不仅可以使用旧代码,还可以使用改进后的代码:
<?php
//Database stuff
$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "mynewdb";
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("SELECT * FROM new");
$stmt->execute();
//Close Connection
$dbh = null;
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
<html>
<head>
<title>Program Scores Table</title>
</head>
<body>
<table width="600" border="1" cellpadding="1" cellspacing="1">
<tr>
<th>Year</th>
<th>Criteria</th>
<th>Score</th>
</tr>
<?php
while ($new = $stmt->fetch(PDO::FETCH_ASSOC)){
echo "<tr>";
echo "<td>" . $new['py'] . "</td>";
echo "<td>" . $new['pcrit'] . "</td>";
echo "<td>" . $new['psco'] . "</td>";
echo "</tr>";
}
?>
</table>
</body>
</html>
2。编码旁注
添加error reporting到您的文件的顶部,这将有助于查找错误。
<?php
ini_set("display_errors", 1);
error_reporting(E_ALL);
?>
错误报告只应在试运行中进行,而绝不能在生产中进行。
关于php - undefined variable : records in C:\XAMPP\htdocs\display_prsc. php 第 29 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28692239/