Inserting data into the database via PHP OO

Asked

Viewed 351 times

0

I have a class that does some functions to insert and search for information inside the database, I already made the connection, but I do not know how to handle this form, pass the class in the form action?

Follow my class:

<?php

require_once "bcrypt.class.php";
require_once "db.class.php";
require_once "helpers.class.php";

/**
 *
 */
class DocModel
{

  protected static $Helpers;
  protected static $pdo;

  function __construct(argument)
  {
    self::$Helpers = new Helpers;
    self::$pdo = Database::connect();
  }

  public function addDoc($title, $text){
    $sql = "INSERT INTO doc_model (id, title, text) VALUES (DEFAULT, :title, :text);";
    $st = self::$pdo->prepare($sql);
    $st->bindParam(':title', $title);
    $st->bindParam(':text', $text);
    $st->execute();

    if ($st->rowCount() > 0) {
      return true;
    } else {
      return false;
    }
  }

  public function getDoc(){
    $sql = "SELECT * FROM doc_model ORDER BY id DESC;";
    $st = self::$pdo->prepare($sql);
    $st->execute();
    if ($docmodel = $st->fetchAll(PDO::FETCH_ASSOC)) {
      return $docmodel;
    } else {
      return false;
    }
  }

  // public function removeDoc($title, $text){
  //   $sql = "DELETE FROM doc_model where "
  //
  // }
}

Follow my HTML form:

<form method="post" class="form-horizontal" action="?">
                            <div class="box-body">
                                <div class="form-group">
                                    <label for="title" class="col-sm-2 control-label">Título *</label>
                                    <div class="col-sm-9">
                                        <input name="title" type="text" class="validate[required] form-control" placeholder = "Título do documento modelo" value="<?php echo ((isset($array['title']))?$array['title']:"")?>"/>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label for="message" class="col-sm-2 control-label">Texto *</label>
                                    <div class="col-sm-9">
                                        <textarea id="message" name="message" class="form-control" placeholder = "Texto da mensagem" ><?php echo ((isset($array['message']))?$array['message']:"")?></textarea>
                                    </div>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="submit" class="btn btn-primary"><i class="fa fa-floppy-o"></i> Salvar</button>
                            </div>
                            <input type="hidden" name="tab" value="tab_1">
                        </form>

I want to save the data of this form in the comic, but I don’t know where to receive the $_POST, whether it would be in the class or in an action.

Intermediate script:

<?php
if (!session_id()) {
    session_start();
}

define('__ROOT__', dirname(__FILE__));
require_once (__ROOT__.'/classes/user.class.php');
require_once (__ROOT__.'/classes/helpers.class.php');
require_once (__ROOT__.'/config.php');
require_once (__ROOT__.'/classes/docmodel.class.php');

if (!isset($_SESSION['USER']) OR !User::checkSession($_SESSION['USER'])) {
    header ('Location: sair');
    exit;
}

if(isset($_SESSION['USER']['type']) AND $_SESSION['USER']['type'] > 2) {
    header ('Location: painel');
    exit;
}

$config['page-title'] = 'Documentos Modelo';

$User = new User;
$Helpers = new Helpers;
$DocModel = new DocModel();


$title = $_POST['title'];
$text = $_POST['message'];

var_dump($title, $text);exit();

$DocModel->addDoc($title, $text);


include_once ('templates/header.tpl.php');
include_once ('templates/sidebar.tpl.php');
include_once ('templates/breadcrumb.tpl.php');
include_once ('templates/modelos.tpl.php');
include_once ('templates/footer.tpl.php');
  • Create a php file intermediario for example exemplo.php and put that same name in the action of your form

  • ai in this file you capture the content that comes from the form and store them in a variable using $_POST

  • Usually this class you created just interacts with the database, the best is to create another file that receives the data, validate and then move to the class DocModel. Take a look at the standard dao

  • I recommend using MVC. The post would be sent from view, would be received and treated on controller and only then passed to the model.

2 answers

0

I’ll give you a basis of what can be done.

Create a middle course , for example meuexemplo.php

<?php
//inclui o arquivo da sua classe
require_once "DocModel.php";

//Nesse arquivo você recebe o conteúdo vindo do formulário  
$aux = $_POST['campox'];

//para acessar a sua classe basta você criar o objeto da mesma
$model = new DocModel(); //Aqui não estou considerando que você esteja carregando as variáveis no construtor 

//a partir daqui vc pode acessar os métodos da sua classe com a variável $model 
 $model -> metodox($campox); //campox é o dado que vem do seu formulário
  • i did this, but it gave this error: Parse error: syntax error, Unexpected ')', expecting variable (T_VARIABLE) in ... on line 16

  • Did you use this example I gave you? Otherwise attach the file you mounted in the question so we can check what the problem might be.

  • Sorry, he gave was this error: Notice: Undefined index: title in

  • put this code in question , only with error not to define the problem

  • Pus la Thiago

  • Let’s debug this code then , it comes to execute the var_dump()?

Show 1 more comment

0

for the form, give a name and action
the form object will look like this:

<form method="post" name="NomeDoFORM" action="ArquivoInserir.php">    
</form>

php does not know what a 'id=' php understands the 'name=' unless you want to use JS. forget the id at the moment. Not to make it difficult I will make the explanation well chewed. to adapt. the items as they go:

<seletor name="NomeDoCampo1" />
<seletor name="NomeDoCampo2" />

now the form has a new face for php.

<form method="post" name="NomeDoFORM" action="ArquivoInserir.php"> 
    <seletor name="NomeDoCampo1" />
    <seletor name="NomeDoCampo2" />   
</form>

Now let’s do the form processing. Assuming you already know the language of the bank... I’ll make it short.

Arquivoinserir.php

<?php
//crie uma variavel para cada campo
$variavelParaCampo1=$_POST['NomeDoCampo1'];
$variavelParaCampo2=$_POST['NomeDoCampo2'];
$sql = "INSERT INTO NomeDaTabela (NomeDaColuna1,NomeDaColuna2) VALUES ('$variavelParaCampo1','$variavelParaCampo2')";
// ou então:
$sql = "INSERT INTO NomeDaTabela (NomeDaColuna1,NomeDaColuna2) VALUES ('$_POST['NomeDoCampo1']','$_POST['NomeDoCampo1']')";
?>

If you want to send with Jquery, you can choose the field by id, or send the whole form at once. SEND AN AI SHOUT. tag that solved.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.