简体   繁体   中英

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. This is my first attempt at OOP so I'm not sure if I'm doing it right.

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

<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

<?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. You should not be mixing complex PHP code (eg: mysql queries) with your HTML. Those two things should be in completely separate files, and most of the PHP part should be in it's own class. For example:

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>

Alternatively, look into a proper templating language such as Smarty. I prefer it myself.

on the second part of code snippet, opening tag is <?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. Better practice would be to use PDO for doing connection to the DB. 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/

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; 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. 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; ie .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. I think rails in particular is much more fun tow work with. So, another suggestion for you is to take a look at them in the future (again, if you haven't known them yet). thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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