如何在OO PHP中编写代码?
如何在OO PHP中做到这一点:如何在OO PHP中编写代码?,php,mysql,database,oop,forms,Php,Mysql,Database,Oop,Forms,如何在OO PHP中做到这一点: 表单('in newstudent.php')要求用户输入他的姓名、课程和年份 选择“提交”按钮后,页面将转到“records.php” records.php-包含一个显示所有记录的表(列:名称、课程、年份) 当用户选择“提交”时,新记录将添加到数据库中,该数据库有一个名为STUDENTS的表 SQL代码 CREATE TABLE STUDENTS( NAME VARCHAR(25) NOT NULL, COURSE VARCHAR(25) NOT
CREATE TABLE STUDENTS(
NAME VARCHAR(25) NOT NULL,
COURSE VARCHAR(25) NOT NULL,
YEAR INT NOT NULL,
CONSTRAINT STUDENTS_PK PRIMARY KEY(NAME));
*请不要介意主键,因为我知道使用名称作为主键是不准确的。这只是举个例子
还有…我如何使用OO PHP操作数据库中的数据?
谢谢也许你会谈论ORM-对象关系映射模式?有许多不同的方法可以将SQL数据对象映射到PHP类:推进、条令(两者都可以与Symfony框架一起使用)、ActiveRecord 当然,您可以尝试实现自己的ORM系统。您需要为此ORM编写数据访问层,这些类描述SQL表和许多其他内容。这很有趣(出于教育目的)
好吧,如果你想切换到一个OO方法来表示数据库中的学生,那么一个类似于下面定义的“学生”类如何(尽管这是非常基本的,并且在任何方面都不是一个完整的ORM)。它会让你走到风格方法的一半 请注意,我假设您将使用整数id列,不这样做会使整个类变得烦人
class Student {
var $id = -1;
var $name;
var $course;
var $year;
public static function newFromID ($id)
{
//fetch a row ($row) from the students table matching the given id
//perhaps returning false if the student doesn't exist?
return self::newFromRow($row);
}
// this method should return a new student object given a specific db row
// and should be called from newFromID. This function means that if the table
// changes, modifications only have to be made in one place
public static function newFromRow($row)
{
$obj = new Student();
//fill in the fields of the object based on the content of the row
return $obj;
}
public static function getAllStudents()
{
//perhaps return an array of student objects, by doing a broad select,
//and passing each row to newFromRow?
}
//this should save the object to the database, either inserting or updating as appropriate
public function save()
{
if($this->id == -1)
{
//insert, store the auto_increment id in $this->id
} else {
//update
}
}
}
因此,要创建新学员并将其保存到数据库中,请执行以下操作:
$student = new Student();
$student->name = "John Smith";
$student->course = "French";
$student->year = 2;
$student->save();
实际上,使用现有的ORM系统通常更明智,但是如果这不是一个选项,你可以考虑写自己的。p> 如何在函数save()中添加insert的sql代码?仍然是这样:$result=mysql_query(“插入到学生(姓名、课程、年份)值(“$$u POST[NAME]”、“$$u POST[COURSE]”、“$$u POST[YEAR]”)或die(mysql_error());?首先,停止。现在谷歌“SQL注入”,阅读您找到的内容,然后转到mysql_real_escape_string函数上的php文档。永远不要以刚才粘贴的方式执行查询。一旦您修改了该查询,使其安全,您可以或多或少地执行mysql_查询(_safe_查询);然后需要使用mysql_insert_id函数来获取最后一个插入列的id。