mysql query – how to escape apostrophe?

webhappy asked
query mysql wpdb
via

I’ve got this query:

$tenantsInfo = $wpdb->get_results("SELECT * FROM exp_ten WHERE tenant_number = " . (int) $user->ID);

I use some echo to show data on frontend:

if ($tenantsInfo) {
        foreach ($tenantsInfo as $tenant) { 
           echo "<h2>Welcome," . " " .$tenant->tenant_name. "</h2>";

When data, like tenant’s name contains apostrophe, no data is displayed on frontend.

Could somebody please help me change mysql statement so apostrophe could be escaped? Or maybe there is different solution?

Thanks in advance!


Answer
via

Use esc_html() when outputting a string value inside tags. Use esc_attr() when you’re outputting a string value inside an attribute="". If you’re outputting a URL, use esc_url() instead of those two.

if ($tenantsInfo) {
        foreach ($tenantsInfo as $tenant) { 
           echo "<h2>Welcome, " . esc_html( $tenant->tenant_name ) . "</h2>";
        }
}
Share This
Posted in: