我需要使用oop和mysqli将值插入数据库
我的代码是
<?php
class dbcon
{
function __construct()
{
$link = mysqli_connect("localhost","root","","oop_testing") or die(mysqli_error());
}
function insert_table($fname,$city)
{
$res=mysqli_query($link,"INSERT INTO tbl_user(name,city) values ('$fname','$city')");
return $res;
}
}
?>
<html>
<head>
<title>OOP CRUD</title>
</head>
<body>
<form action="" method="POST" name="form1">
<table>
<tr>
<td>USERNAME:</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>CITY:</td>
<td><input type="text" name="city" /></td>
</tr>
<tr>
<td colspan="2" align="center"> <input type="submit" name="submit" value="Insert" /> </td>
</tr>
</table>
</form>
<?php
$con = new dbcon();
if(isset($_POST['submit']))
{
$fname=$_POST['username'];
$city=$_POST['city'];
$con->insert_table($fname, $city);
}
?>
</body>
</html>
但它返回
注意:未定义的变量:第11行的C:\ xampp \ htdocs \ CRUD_OOP \ index.php中的链接
警告:mysqli_query()期望参数1为mysqli,在第11行的C:\ xampp \ htdocs \ CRUD_OOP \ index.php中给出空值
有什么帮助吗? 预先感谢
答案 0 :(得分:0)
class dbcon
{
private $link; //private by design
function __construct()
{
$this->link = mysqli_connect("localhost","root","","oop_testing") or
die(mysqli_error());
}
function insert_table($fname,$city)
{
$res=mysqli_query($this->link,"INSERT INTO tbl_user(name,city) values ('$fname','$city')");
return $res;
}
}
您的$ link仅在__construct函数中可用。在对象内部使用变量