Test file for Trac 52506
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Testing for https://core.trac.wordpress.org/ticket/52506 | |
add_action( 'loop_start', 'test_trac_52506' ); | |
function test_trac_52506() { | |
global $wpdb; | |
$table = 'wp_posts'; | |
$field = 'post_name'; | |
$value = 'Trac_52506'; | |
echo "<h1>Test Trac 52506</h1>"; | |
// Test escaping table and field identifiers | |
$sql = $wpdb->prepare( | |
'SELECT * FROM %i WHERE %i LIKE %s', | |
$table, | |
$field, | |
'%' . $wpdb->esc_like( $value ) . '%' | |
); | |
echo "<h2>Basic Test</h2>"; | |
echo "<p>Table and field names should be backtick escaped:</p>"; | |
output_result( $sql ); | |
// Test %i execution time, adapted from https://wpdb.eiv.dev | |
$iterations = 10000; | |
$c1 = hrtime( true ); | |
for ( $k = 0; $k < $iterations; ++$k ) { | |
$sql1 = $wpdb->prepare( "SELECT ID FROM `%1s`", $wpdb->posts ); | |
} | |
$c2 = hrtime( true ); | |
$p1 = hrtime( true ); | |
for ( $k = 0; $k < $iterations; ++$k ) { | |
$sql2 = $wpdb->prepare( 'SELECT ID FROM %i', $wpdb->posts ); | |
} | |
$p2 = hrtime( true ); | |
// Compare output of manual escape vs placeholder | |
echo "<h2>Performance Test</h2>"; | |
echo "<p>Rough performance comparison with $iterations iterations of <code>\$wpdb->prepare()</code>:</p>"; | |
output_result( $sql2 ); | |
output_result( $sql1 === $sql2 ? 'SQL Matches ✅' : 'SQL Different ❌' ); | |
// Calculate execution time to compare manual escape vs placeholder method | |
$current_time = round( ( ( $c2 - $c1 ) / 1000000000 ), 4 ); | |
$patched_time = round( ( ( $p2 - $p1 ) / 1000000000 ), 4 ); | |
output_result( sprintf( 'Manual escape: %s', $current_time ) ); | |
output_result( sprintf( 'Using %%i placeholder: %s', $patched_time ) ); | |
output_result( | |
sprintf( | |
'Diff (manual - %%i): %s', | |
$current_time - $patched_time | |
) | |
); | |
output_result( | |
sprintf( | |
'Time to execute: %s%%', | |
round ( ( ( $patched_time - $current_time ) / $current_time ) * 100 ) | |
) | |
); | |
exit; | |
} | |
function output_result( $text ) { | |
echo "<pre>"; | |
echo $text; | |
echo "</pre>"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment