Inserting data into the database through PHP OO [duplicate]

0

I have a class that does some functions to insert and search information inside the database, I made the connection, but I do not know how to handle this form, pass the class in the form's 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 "
  //
  // }
}

Here is 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 bd, but I do not know where to get 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');
    
asked by anonymous 29.10.2018 / 17:23

2 answers

0

I'll give you a basis for what can be done.

Create an intermediate bucket, 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
    
29.10.2018 / 17:37
0

For the form, give a name and an 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 ' name = ' unless you want to use JS. Forget the id at the moment. To make it difficult, I'll make the explanation well chewed. for you 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 processing of the form. assuming you already know the language of the bank ... I will do summarized.

  

FileInserir.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 submit with Jquery, you can choose the field by id, or send the form all at once. SEND A SHOUT AI. brand that solved.

    
29.10.2018 / 18:44