Sunday, November 3, 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

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...