我有简单的表单来向数据库添加记录。它看起来像这样:
<form action="" method="post">
<label>Student Name :</label>
<input type="text" name="stu_name" id="name" required="required" placeholder="Please Enter Name"/><br /><br />
<label>Student Email :</label>
<input type="email" name="stu_email" id="email" required="required" placeholder="john123@gmail.com"/><br/><br />
<label>Student City :</label>
<input type="text" name="stu_city" id="city" required="required" placeholder="Please Enter Your City"/><br/><br />
<input type="submit" value=" Submit " name="submit"/><br />
</form>
<?php
if(isset($_POST["submit"])){
$hostname='localhost';
$username='root';
$password='';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=college",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "INSERT INTO students (student_name, student_email, student_city)
VALUES ('".$_POST["stu_name"]."','".$_POST["stu_email"]."','".$_POST["stu_city"]."')";
if ($dbh->query($sql)) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
}
else{
echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
?>
此代码有效,我可以连接到数据库并添加一些记录。我的问题是,如果我想使用其他文件中的代码而不是第一个代码中的连接来连接数据库,那么我需要在该代码中进行哪些更改:
<?php
class Database {
public function getConnection() {
$result = false;
try {
$result = new PDO('mysql:host=localhost;dbname=college', 'root', '');
} catch(PDOException $e) { }
return $result;
}
}
$db = new Database();
$conn = $db->getConnection();
if (!$conn) {
die("Error connecting to the database");
}
?>
答案 0 :(得分:3)
您可以包含数据库脚本,然后使用$conn
进行所有数据库操作,而不是使用$dbh
创建新的PDO对象。
require_once('database.php');
try {
if ($conn->query($sql)) {
...
...
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
附注:您的查询容易受到SQL注入攻击。使用Prepared Statement而不是将值连接到SQL中。
答案 1 :(得分:1)
只需将数据库类与php require语句一起使用即可。
<div id="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
<div class="item">9</div>
<div class="item">10</div>
<div class="item">11</div>
<div class="item">12</div>
<div class="item">13</div>
<div class="item">14</div>
<div class="item">15</div>
<div class="item">16</div>
<div class="item">17</div>
<div class="item">18</div>
<div class="item">19</div>
<div class="item">20</div>
<div class="item">21</div>
</div>
另一个文件
<?php
// file: database.class.php
class Database {
...
}
?>