在PHP和mysqli中使用oop概念插入数据库
我需要使用oop和mysqli将值插入数据库 我的代码是在PHP和mysqli中使用oop概念插入数据库,php,mysqli,Php,Mysqli,我需要使用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
<?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>
$link仅在可用的_构造函数中。在对象内使用变量$link
在函数内声明为本地变量,不能在其他函数中使用。将$link
声明为属性,并在\uu construct()
中初始化它。然后在方法中将其调用为$this->link
。现在,这不是OOP,因为它使用的是类,我建议您也使用OOP mysqli。不客气。请投票并标记为解决方案
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;
}
}