0

I have a ref query string which matches rows in my wp_invites table.

In my wp_invites table, I have the following columns:

  • lead_name
  • reference

Let's assume here is one of the rows:

  • Lead name: Freddy
  • Reference: 4FxtfVFszCHd

When the user accesses their invite, their URL will be something like: test.test/?ref=4FxtfVFszCHd

I am then getting this ref from the URL and trying to extract from the table row, if it exists. To do so, I have the following:

<?php

function get_reference(){
  $get_reference = $_GET['ref'];
  $get_reference = strval($get_reference);
  return $get_reference;
}

global $wpdb;

$get_reference = get_reference();

$result = $wpdb->get_results( "SELECT * FROM 'wp_invites' WHERE 'reference' = '{$get_reference}' " );

foreach ($result as $post){
  $lead_name = $post->lead_name;
  echo '<p>'. $lead_name . '</p>';
}

?>

However, this yields a [You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''wp_invites' WHERE 'reference' = '4FxtfVFszCHd'' at line 1] error.

I had a feeling it may have been to do with a the get_reference() function call I was doing inside the query string. So I then changed it into a PHP var, but still seeing the same issue?

Freddy
  • 683
  • 4
  • 35
  • 114

1 Answers1

0

I would set up query_vars in your functions.php to better handle your url parameter:

function add_query_vars_filter( $vars ){
    $vars[] = "ref";
    return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );

then in your function to parse the info

$reference = sanitize_text_field( get_query_var('ref') );

global $wpdb;

$table_name = $wpdb->prefix . 'invites';


$results = $wpdb->get_results( 
    $wpdb->prepare( "SELECT * FROM $table_name WHERE reference=%s", $reference), ARRAY_A
);


if( $results ){
    foreach ($results as $result){
        echo '<p>'. $result['lead_name'] . '</p>';
    }
}
Moishy
  • 3,560
  • 3
  • 23
  • 42
  • Hi Moishy - Thanks for showcasing this approach. It's much more secure and reusable than my previous method. One query however, `$vars` for me prints `Welcome to WordPress. This is your first post. Edit or delete it, then start writing!`. The `lead_name` `echo` doesn't print the name from the DB (Even through the `ref` matches what's in the DB. Any ideas what may be happening? I did a `var_dump($vars);` and `ref` returned empty? – Freddy Dec 02 '22 at 22:45
  • the `get_query_var('ref')` will only show up when the its being queried (i.e. as a url parameter) so attach to the url and do a `var_dump()`. also check the table name is spelled correctly. I just copied from your initial code – Moishy Dec 04 '22 at 02:33