Jump to content

Recommended Posts

I'm working with a client and setting up this form for them. I'm trying to have the user be able to add a new name and email record into the account table. Once they submit it should display the 10 newest records below the form. Appreciate any help.

 

 

class account{

function account(){

$this->id = ' ';

$this->name = '';

$this->email = '';

}

function find_account($id){

$sql="select `id` from `account` where `id`='".$id."'";

$result = mysql_query($sql);

while ($row = mysql_fetch_assoc($result)){

$row['id']; //int pk auto incerment

$row['name']; //varchar(50)

$row['email']; //varchar(50)

$row['timestamp']; //varchar(15)

}

}

}

<html>

<body>

<div>

<form action='#'>

name: <input type='text' name='account_name'>

email:<input type='text' id='account_email'>

<input type="button" value="submit">

</form>

</div>

<div style="border:solid 1px #F60;">

Last 10 entry:

</div>

<div style="border:solid 1px #000;">

<?php echo "id: ".$account->id;?>

<?php echo "name: ".$account->name;?>

<?php echo "email: ".$account->email;?>

</div>

</body>

</html>

Link to comment
https://forums.phpfreaks.com/topic/273590-custom-php-code-im-stuck/
Share on other sites

To insert, you could do like this:

  1. Add a new function to your class which will insert data into the database
  2. Either pass data to this function with parameters or use class fields (variables) and access these from within the function
  3. Write insert code within the function

To get the latest 10 entries, you could do like this:

  1. Add a new function to your class which will fetch X entries (X could be a parameter)
  2. Write the SQL query to fetch the latest X entries; for instance using ORDER BY and LIMIT
  3. Either create a wrapper class for an entry and return an array of objects or return an array of key-value pairs, such as 'entry_id' => 123
  4. Call this function where you want to show the entries
  5. Loop through the returned array (perhaps with foreach) and generate the HTML markup to show them - e.g. in a table

Here is a bit of code to get you started:

 


class Account {
protected $id;
protected $name;
protected $email;

public function __construct($id, $name, $email) {
$this->id = $id;
$this->name = $name;
$this->email = $email;
}

public static function getLatestEntries($number_to_fetch) {
$number_to_fetch = (int) $number_to_fetch; // Ensure it's a number

$query = "SELECT * FROM Account ORDER BY date DESC LIMIT 0, " . $number_to_fetch;
$result = mysql_query($query); // You should really use mysqli or PDO here! The mysql extension is deprecated

$entries = array();

// Fill rows into $entries here

return $entries;
}

public function insert() {
// Prevent against SQL injection
$id = mysql_real_escape_string($this->id);
$name = mysql_real_escape_string($this->name);
$email = mysql_real_escape_string($this->email);

$query = "INSERT INTO Account VALUES ($id, $name, $email)";
$result = mysql_query($query);

return (mysql_affected_rows($result) > 0); // True if successful and false otherwise
}

public function getId() {
return $this->id;
}

public function setId($id) {
$this->id = $id;
}

public function getName() {
return $this->name;
}

public function setName($name) {
$this->name = $name;
}

public function getEmail() {
return $this->email;
}

public function setEmail($email) {
$this->email = $email;
}
}

?>

<p>This is your HTML markup</p>

<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$account = new Account(-1, $_POST['account_name'], $_POST['account_email']);
$result = $account->insert();

if ($result === true) {
// Show latest entries
$entries = Account::getLatestEntries(10);

foreach ($entries as $entry) {
// Show entries here
}
}
}

?>

Hey,

 

My name is Chris, and I would be more than glad to assist you!

  1. First lets create the class in a separate file and include it later.
    <?php
    //this is your class file save it and name it as class.account.php
    class account
    {
    var $ten = array();
    var $clean_inputs = array();
    var $errors = array();
    
    function __construct()
    {
      global $_POST;
      if (isset($_POST['name']) || isset($_POST['email']))
      {
       if ($_POST['name'] == "" || $_POST['email'] == "")
       {
        echo "Please fill out both the name and email!";
        $this->account_form();
       }
       else
       {
        $this->add_account($_POST);
       }
      }
    }
    
    function get_ten(){
      $sql="select * from `account` WHERE ORDER BY id DESC LIMIT 0, 9";
      $result = mysql_query($sql);
      $i = 1;
      while ($row = mysql_fetch_assoc($result)){
       foreach ($row as $z => $x)
       {
        $this->ten[$i][$z] = $x;
       }
       $i++;
      }
    }
    function list_ten()
    {
      $this->get_ten();
      echo "<div style=\"border:solid 1px #F60;\">";
      echo "Last 10 entry:";
      echo "</div>";
      foreach ($this->ten as $z => $x)
      {
       echo "<div style=\"border:solid 1px #000;\">";
       echo "id: {$x['id']}";
       echo "name: {$x['name']}";
       echo "email: {$x['email']}";
       echo "</div>";
      }
    
    }
    function add_account($inputs)
    {
      //first lets clean the inputs
      foreach ($inputs as $z => $x) { $this->clean_inputs[$z] = mysql_real_escape_string($x); }
      $date = date_create(); //get the date
      $timestamp = date_format($date, 'U = Y-m-d H:i:s'); //set the timestamp seeing how I do not know what you guys are doing for this
      $sql = "INSERT INTO account (`name`,`email`,`timestamp`) VALUES ('{$this->clean_inputs['name']}','{$this->clean_inputs['email']}','{$timestamp}')";
      if (mysql_query($sql) or die(mysql_error()))
      {
       $this->account_form();
       $this->list_ten();
      }
      else
      {
       echo "Error creating account, try again!"
       $this->account_form();
      }
    }
    function account_form()
    {
      echo "<div>
      <form action='#' method='POST'>
      name: <input type='text' name='account_name'>
      email:<input type='text' id='account_email'>
      <input type=\"button\" value=\submit\">
      </form>
      </div>";
    }
    
    }
    ?>
    


  2. Include the class file into the main index or .php file
    <?php
    session_start();
    //include ur config script for ur database
    //include class file include("class.account.php");
    include("class.account.php");
    ?>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <html>
    <head>
    <title></title>
    <meta name="" content="">
    </head>
    <body>
    <?php $Account = new account(); ?>
    </body>
    </html>
    


 

WARNING I HAVE NOT TRIED THIS CODE BUT IT SHOULD WORK IF IT DOES NOT WORK NO WORRIES, IT WAS A QUICK AND EASY 5 MINUTE THING

Perhaps you should have spent six minutes on it.

 

A quick glance at the "get_ten()" function showed it only getting nine records. A closer look showed a syntax error in the query "WHERE ORDER BY"

 

Try

function get_ten(){
 $sql="SELECT * FROM `account` ORDER BY timestamp DESC LIMIT 10";
 $result = mysql_query($sql);
 while ($row = mysql_fetch_assoc($result)) {
    $this->ten[] = $row;
 }
}

Not to mention the outdated PHP4 OOP syntax, or the completely unnecessary use of the global keyword on the $_POST superglobal. Then there's the fact that while you're using a class, chris, that is sadly not object oriented programming.

 

Look at Andy's example for how to do it. The only comment I have on his example, is that the actual fetching from the DB should have been in a class of its own. Relatively minor, and easy to refactor out.

Look at Andy's example for how to do it. The only comment I have on his example, is that the actual fetching from the DB should have been in a class of its own. Relatively minor, and easy to refactor out.

 

That, and no one should use the mysql_* functions any longer. Use MySQLi or PDO.

Look at Andy's example for how to do it. The only comment I have on his example, is that the actual fetching from the DB should have been in a class of its own. Relatively minor, and easy to refactor out.

 

I was thinking of this, but the code that was posted in the initial post was quite far away from working code, which led me to believe that I was dealing with someone relatively new to PHP and/or programming. I figured that bringing design patterns, DAL, DAO, etc. into this would confuse more than it would do good, so I decided to keep things simple. But thanks for the heads up. :)

 

That, and no one should use the mysql_* functions any longer. Use MySQLi or PDO.

 

Definitely. I left a comment in the code about this to encourage Idzik to look up either of those. :)

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.