我试图使用OOPS概念的CRUD操作,但在调用函数时遇到错误

时间:2015-10-02 13:22:05

标签: php oop mysqli

我正在尝试使用OOPS Concept的CRUD操作,但在调用函数时出错。我确实从这个文件创建了一个add.php文件我试图从DB.class.php调用函数,但它的值不适合插入数据库。我收到“通知:未定义的变量:D:\ wamp \ www \ oops \ DB.class.php中的连接”这个错误。

DB.class.php

<?php 
class DB 
{
protected $db_name='user';
protected $db_user='root';
protected $db_pass='';
protected $db_localhost='localhost';
public function __construct()
{
$this->connection=mysqli_connect($this->db_localhost,$this->db_user,$this->db_pass,$this->db_name);
return true;
}
public function connect()
{
$this->connection=mysqli_connect($this->db_localhost,$this->db_user,$this->db_pass,$this->db_name);
return true;
}
public function Insert($table,$data,$debug="")
{
$columns = "";
$values = "";
foreach( $data as $column=>$value )
{
$field[] = $column;
if($value !="now()")
$values[] = "'$value'";
else
$values[] = "$value";
}
$columns = trim( implode(", ", $field) );
$values = trim( implode(", ", $values) );
$sql = "insert into $table ($columns) values ($values)";
if($debug==1)
{
echo $sql;
exit();
}
mysqli_query($connection,$sql) or die(mysqli_error());

return mysqli_insert_id();
}
}
?>

add.php

<?php 
include('DB.class.php');
$db = new DB();
$db->connect();

if(isset($_POST['save']))
{
$data['firstname']=$_POST['firstname'];
$data['lastname']=$_POST['lastname'];
$data['username']=$_POST['username'];
$data['password']=$_POST['password'];

$db->Insert('users',$data,'');
}
?>
<html>
<head>
<title>MySQLi Create Record</title>
</head>
<body>
<form action='#' method='post' border='0'>
<table>
<tr>
<td>Firstname</td>
<td><input type='text' name='firstname' /></td>
</tr>
<tr>
<td>Lastname</td>
<td><input type='text' name='lastname' /></td>
</tr>
<tr>
<td>Username</td>
<td><input type='text' name='username' /></td>
</tr>
<tr>
<td>Password</td>
<td><input type='password' name='password' /></td>
<tr>
<td></td>
<td>
<input type='hidden' name='action' value='create' />
<input type='submit' value='Save' name='save'/>
</td>
</tr>
</table>
</form>
</body>
</html>

1 个答案:

答案 0 :(得分:-1)

使用此问题解决了我的问题,并且感谢了@Andrew  公共功能连接()     {     $这 - &GT;连接= mysqli_connect($这 - &GT; db_localhost,$这 - &GT; DB_USER,$这 - &GT; DB_PASS,$这 - &GT; DB_NAME);     返回true;     }