我遇到此错误:
注意:未定义变量:pdo in C:\ xampp \ htdocs \ islahPos \ pos \ posDash.php在第86行
致命错误:未捕获错误:调用成员函数prepare() C:\ xampp \ htdocs \ islahPos \ pos \ posDash.php:86中的null堆栈跟踪:#0 {main}在第86行的C:\ xampp \ htdocs \ islahPos \ pos \ posDash.php中抛出
请帮助我,我正在学习PHP
<div class="card-body p-0">
<table class="table">
<thead>
<tr>
<th style="width: 10px">#</th>
<th>Name</th>
<th>Password</th>
<th>Phone No: </th>
</tr>
</thead>
<tbody>
<?php
$select = $pdo->prepare("select * from users order by id desc");
$select->execute();
while($row=$select->fetch(PDO::FETCH_OBJ)) {
echo '
<tr>
<td>'.$row->id.' </td>
<td> '.$row->email.' </td>
<td> '.$row->phone.'</td>
<td>'.$row->join_date.'</td>
<td> </td>
</tr>
';
}
?>
</tbody>
</table>
</div>
Here is my database connection code
<?php
//initialize variables to hold connection parameters
$username = 'root';
$dsn = 'mysql:host=localhost; dbname=register';
$password = '';
try{
//create an instance of the PDO class with the required parameters
$db = new PDO($dsn, $username, $password);
//set pdo error mode to exception
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//display success message
//echo "Connected to the register database";
}catch (PDOException $ex){
//display error message
echo "Connection failed ".$ex->getMessage();
}
答案 0 :(得分:1)
我只是在您的代码上方添加了pdo连接,并且工作正常,我在您的代码之前添加了以下几行:
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$pdo = new PDO("mysql:host=$servername;dbname=stack", $username, $password);
// set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
所以只需检查您的连接即可。