How to run an external script from a Wordpress form?

Asked

Viewed 794 times

2

I just installed the last version of Wordpress and created a page with a simple form.

<form class="" method="post" action="insert.php">
    <input name="name" placeholder="Name">
    <input name="email" placeholder="E-Mail">
    <input name="company" placeholder="Company">
    <button name="submit" type="submit">OK</button>
</form>

I would then like to enter the data from this form into a database table. I researched and discovered that a possible code to do this would be:

<?php
    if(isset($_POST['submit']))
    {
        global $wpdb;

        $wpdb->insert
            ('users', // Nome da tabela no banco de dados.
                array
                (
                    'name'=>$_POST['name'],
                    'email'=>$_POST['email'],
                    'company'=>$_POST['company'],
                    'registration'=>now()]
                )
            );

        echo 'Usuário inserido com sucesso!'
    }
?>

The questions would be:

I must enter this code just below the form code or save it all in an external file?

And if this is the case, where I must save the file Insert.php so that it is run by clicking on the button of Submit?

  • If you want to leave everything in the same form file, just leave the action="" empty so that when submitting the form it returns to the page itself and runs the condition if(isset($_POST['submit'])

  • @Thyagothysoft thank you for your reply, but unfortunately it didn’t work... The PHP code appears just below the form...

  • Did it not work or did not Insert? If you have an error report the error.

  • If the PHP code appears just below as text seeing in the browser, it is probably something from WP. I know that if you are going to insert PHP by the Admin panel on a certain page, if I am not mistaken, you need a plugin for this, because WP escapes the tags and variables, presenting as plain text. If so, alternative measure is to open the PHP file itself via FTP and put this script.

1 answer

1

You can leave this code in the same file or in a separate file. I advise to leave in a separate file the logic that is within the if, then you just give one include of the file within your if verifying the post. Example:

if(isset($_POST['submit'])){
    include('meuArquivo.php');
}

And within the meuArquivo.php

global $wpdb;

$wpdb->insert
  ('users', // Nome da tabela no banco de dados.
    array
    (
      'name'=>$_POST['name'],
      'email'=>$_POST['email'],
      'company'=>$_POST['company'],
      'registration'=>now()]
    )
  );
echo 'Usuário inserido com sucesso!'

Browser other questions tagged

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