简体   繁体   English

首次尝试使用PHP / MySQL进行OOP

[英]First attempt at OOP with PHP/MySQL

I'm trying to get a feel for OOP with PHP/MySQL, so I attempted to write a program that will take a text input called "name" and store it in a database, then display the names that are stored. 我试图通过PHP / MySQL来体验OOP,所以我尝试编写一个程序,该程序将使用名为“ name”的文本输入并将其存储在数据库中,然后显示存储的名称。 This is my first attempt at OOP so I'm not sure if I'm doing it right. 这是我第一次尝试OOP,所以不确定执行是否正确。

Any suggestions? 有什么建议么? Am I inserting the value properly? 我是否正确插入值? The table is called "names" and the column is "name." 该表称为“名称”,而列称为“名称”。

Here are my two different files.This one is called template.php 这是我的两个不同文件,这个文件叫做template.php

<html>
<head>
</head>
<body>
<form action="template.php" method="post"> 
Person: <input name="person" type="text" /> 
<input type="submit" />
</form>
<table>
 <?php 

$insert_name = new MyController();
$insert_name-> getname($_POST['person']);


foreach ($names as $name); ?>
 <tr>
  <td><?php echo htmlspecialchars($name); ?></td>
<tr>
<?php endforeach; ?>
</table>
</body>
</html>

Now for my other file, index2.php 现在,对于我的其他文件,index2.php

<?php

$connection = mysql_query("localhost","root","password") or die(mysql_error());
mysql_select_db("test",$connection) or die(mysql_error));

require_once("template.php");


class MyController
{
var $name;

function getname($new_name) { 
          $this->name = $new_name;      
    }


function insert(){
  mysql_query("INSERT INTO names(name) 
 VALUE ( "$this->name" )");       
}


function run()
{
$result = mysql_query("select * from names");
$names = array();
while ($row = mysql_fetch_array($result))
{
  $names[] = $row['name'];
}

include("template.php");
 }
 }

  $controller = new MyController();
  $controller->run();

?>

You are generating your HTML all wrong. 您正在错误地生成HTML。 You should not be mixing complex PHP code (eg: mysql queries) with your HTML. 您不应将复杂的PHP代码(例如mysql查询)与HTML混合使用。 Those two things should be in completely separate files, and most of the PHP part should be in it's own class. 这两件事应该放在完全独立的文件中,而大多数PHP部分应该在它自己的类中。 For example: 例如:

index2.php index2.php

<?php

require_once("dbinsert.php");

class MyController
{
  function run()
  {
    $insert_name = new datainsert();

    $insert_name->setname($_POST['person']);

    $result = mysql_query("select * from names");
    $names = array();
    while ($row = mysql_fetch_array($result))
    {
      $names[] = $row['name'];
    }

    include("my-template.php");
  }
}

$controller = new MyController();
$controller->run();

my-template.php 我-的template.php

<html>
<head>
</head>
<body>

<form action="index2.php" method="post"> 
Person: <input name="person" type="text" /> 
<input type="submit" />
</form>
<table>
  <?php foreach ($names as $name); ?>
    <tr>
      <td><?php echo htmlspecialchars($name); ?></td>
    <tr>
  <?php endforeach; ?>
</table>

</body>
</html>

Alternatively, look into a proper templating language such as Smarty. 或者,研究适当的模板语言,例如Smarty。 I prefer it myself. 我自己喜欢。

on the second part of code snippet, opening tag is <?php not <? 在代码段的第二部分,开始标记是<?php not <? . Another thing would be to wrap your connection db query within try..catch block, so that it is easier to know when there's error. 另一件事是将连接数据库查询包装在try..catch块中,以便更容易知道何时出现错误。 Better practice would be to use PDO for doing connection to the DB. 更好的做法是使用PDO与数据库建立连接。 Why? 为什么? well, there's aa lot of articles about it already. 好吧,已经有很多关于它的文章。 One of them is here, I'd share with you http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/ 其中一个在这里,我会与您分享http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/

And also, the best practice is to sanitize input before inserting to the database. 而且,最佳实践是在插入数据库之前清理输入。 Sanitizing should be done on the method member that handles the data posted to avoid SQL injection; 应该对处理已发布数据的方法成员执行清理操作,以避免SQL注入。 So i suggest you do: 所以我建议你这样做:

function setname($sent_name){
            $sent_name = mysql_real_escape_string($sent_name);
            $this-> insert_name = $sent_name ;
}

When creating class that is invoked as a new object (if not working with just plainly static variable), you probably want to create a constructor function where the initial state of the private variables are created. 创建作为新对象调用的类时(如果不能仅使用纯静态变量),则可能要创建一个构造函数,在该函数中创建私有变量的初始状态。 The regular convention is also to use Uppercase for the class name. 常规约定也将大写字母用作类名。 So, in your class, you may want to do this instead: 因此,在您的课堂上,您可能需要这样做:

class DataInsert{

var $insert_name;

function __construct(){
//initialize
}

function setname($sent_name){
            $sent_name = mysql_real_escape_string($sent_name);
            $this-> insert_name = $sent_name ;
}

function dbinsert(){
    mysql_query("INSERT INTO names(name) 
    VALUE ( "$this->insert_name" )");       
    }
}

Hope that helps. 希望能有所帮助。 In the end, have fun with PHP. 最后,玩转PHP。 The next thing is to learn the MVC part then (if you havent been exposed to such design pattern) where there are a few frameworks available for PHP; 接下来的事情是学习MVC部分(如果您尚未接触过这种设计模式),那里有一些适用于PHP的框架。 ie .cake, zend. 即.cake,zend。

I myself have not done much PHP for a while now since I'm now mainly focusing on ruby on rails and node.js. 自从我现在主要专注于Rails和Node.js上的ruby以来,我自己已经有一段时间没有做太多PHP了。 I think rails in particular is much more fun tow work with. 我认为与Rails一起工作尤其有趣。 So, another suggestion for you is to take a look at them in the future (again, if you haven't known them yet). 因此,对您的另一建议是将来查看它们(同样,如果您还不了解它们的话)。 thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM