Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error using $wpdb->prepare()

I'm trying to use $wpdb->prepare() function but it is returning an error. What is wrong with the SQL syntax?

WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''wp_spreadsheets' WHERE id = 6' at line 1]

SELECT table_name, table_code FROM 'wp_spreadsheets' WHERE id = 6

The code I'm using is as followed.

<?php

// Variables
$mysqltable_name = 'wp_spreadsheets';
$table_id = 6;

// Query
$query = $wpdb->prepare( 'SELECT table_name, table_code FROM %s WHERE id = %d', $mysqltable_name, $table_id );
$results = $wpdb->get_results( $query, ARRAY_A );

// Results
if( !empty( $results ) ) {
    print_r( $results );
} else {
    $wpdb->print_error();
}

?>
like image 772
Cory Nickerson Avatar asked Mar 07 '26 04:03

Cory Nickerson


1 Answers

%s means that you intend to use a varchar input, which is nice on your PHP end where you pass the $mysqltable_name text, but on MySQL level the query to be executed will contain apostrophes around $mysqltable_name since it is a varchar. You need to use string concatenation or hard-coded table name to avoid it in your PHP code. If your table name is dynamic, then you need to make sure it will not contain harmful code.

like image 179
Lajos Arpad Avatar answered Mar 08 '26 18:03

Lajos Arpad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!