Getting SQL error when submitting form in wordpress

Viewed 34

I have a table in the database which contains 2 columns one for PLZ (zip code) and the other for Link and I have a form that contains an input and a button. the work required is when I type the PLZ in the form and I click on the button we will give the link corresponding to this PLZ

<?php
 require('../../../wp-blog-header.php');
 require('../../../wp-config.php');

if(isset($_POST['submit']))
{
    // WP Globals
    global $table_prefix, $wpdb;

    // Customer Table
    $customerTable = $table_prefix . 'customer';
    $PLZ = $_POST['PLZ'];
    // search in all table columns
    $query = "SELECT Link 
    FROM $customerTable
    WHERE  PLZ = '$PLZ'
    ";
    $search_result = submit($query);
    
}
 else {
   echo 'error';
}
// function to connect and execute the query
function submit($query)
{
    global  $wpdb ;
    $search_result = $wpdb->get_results($query);
    foreach($search_result as $row){
        header('Location: '.$row['Link']);
    }

}
?>

and this is the form

<?php
function oped_postcode_form_function() { 
   
       <form  method="get" action="<?php echo plugins_url('action.php', __FILE__ ); ?>">
   <label>Postleitzahl</label><input type="text" pattern="[0-9]{5}" title="Five digit zip code" />
   <button name="submit">submit</button>
   </form>
   <?php
       } 
       // register shortcode
       add_shortcode('oped_postcode_form', 'oped_postcode_form_function'); 

?>

the result always gives error

1 Answers

Your form send GET request to server, so you need to use $_GET array in PHP code:

<?php
 require('../../../wp-blog-header.php');
 require('../../../wp-config.php');

if(isset($_GET['submit']))
{
    // WP Globals
    global $table_prefix, $wpdb;

    // Customer Table
    $customerTable = $table_prefix . 'customer';
    $PLZ = $_GET['PLZ'];
    // search in all table columns
    $query = $wpdb->prepare("SELECT Link FROM $customerTable WHERE  PLZ = %s", $PLZ);
    $search_result = submit($query);
    
}
else {
   echo 'error';
}
// function to connect and execute the query
function submit($query)
{
    global  $wpdb ;
    $search_result = $wpdb->get_results($query);
    foreach($search_result as $row){
        header('Location: '.$row['Link']);
    }

}
?>

Also you should to use prepared statements to prevent SQL Injection

Related