Sunday 3 November 2019

php - mysql prepared statement "truncate table ?" returns null



in a function to truncate a table I can use



$stmt = $mysqli->prepare("truncate table packed_items");


and $stmt is set to a mysqli_stmt Object, but
if I try




$stmt = $mysqli->prepare("truncate table ?");


then $stmt is set to null and the statment:



$stmt->bind_param("s", $mytable)


will crash with error
Call to a member function bind_param() on a non-object in




I am using parameterized prepared statements to select,insert and update with no problem.


Answer



you cannot bind any SQL literal but data one. no keyword, no operator, no identifier.



if you really need to truncate your tables dynamically, knowing no name already (as truncating tables at random is obviously a sign of very bad design), check the table name against white list, format it correctly, and then interpolate in a query string.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...