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

标签 php mysql oop

我试图通过 PHP/MySQL 了解 OOP,因此我尝试编写一个程序,该程序将采用名为“name”的文本输入并将其存储在数据库中,然后显示存储的名称。这是我第一次尝试 OOP,所以我不确定我做的是否正确。

有什么建议吗?我是否正确插入了值?该表名为“names”,列为“name”。

这是我的两个不同的文件。这个叫做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>

现在我的另一个文件,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();

?>

最佳答案

您生成的 HTML 完全错误。您不应该将复杂的 PHP 代码(例如:mysql 查询)与您的 HTML 混合在一起。这两件事应该在完全独立的文件中,大部分 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

<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>

或者,研究合适的模板语言,例如 Smarty。我自己比较喜欢。

关于php - 首次尝试使用 PHP/MySQL 进行 OOP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8554398/

相关文章:

mysql - 使用前一行的 id 删除多行

mysql - 如何在支持 mysql2 的 Redhat 4.0 上安装 rails 3.0?

php - 如果没有设置参数如何给出默认值

javascript - 在 ES6、OOP Javascript 编程中转换 ES5 IIFE

php - Cake php 登录显示用户名和密码无效,即使它们是正确的

php - 更改/index.php?route=affiliate/account to/affiliate OpenCart 2.0.3.1

c++ - 包含类对象的最佳 C++ 设计是什么?

c++ - 处理 const 类数据的最佳实践

php - 在 Laravel 的 Homestead 中运行 PHPUnit

PHP不会在cmd中执行代码