Are these pdo commands ok?

I made a little webpage to help me make new MySQL tables. At first, I did not use a prepare statement, now I have changed it. The table name and column names are collected with a form.

Especially these 2 lines: Is this the correct way to do this?

$stmt = $pdo->prepare($sql);
$stmt->execute();

Is this OK? It works, I do not get any php errors and I get the table I want. Is it sql-injection safe? (Actually, only I will ever use this. Most of the time it is locked in a folder with 0700 permissions.)

<?php

include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/studentdb.inc.php';

try
{
	$pre = 'CREATE TABLE IF NOT EXISTS ';
	$tablename = $arrayoutput[0]; 
	$id = ' (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, ';
	$end = ' DEFAULT CHARACTER SET utf8 ENGINE=InnoDB;';
	// put them all together
	$sql = $pre . $tablename . $id . $allcols . $end;
	echo '$sql is ' . $sql;
	$stmt = $pdo->prepare($sql);
	$stmt->execute();
	//$pdo->exec($stmt);
	$output = 'The table "' . $tablename . '" was successfully created.';
	include 'output.html.php';
	exit();
}
catch (PDOException $e)
{
$output = 'Error creating ' . $tablename . 'table: ' . $e->getMessage();
include 'output.html.php';
exit();
}
?>

The main point of a prepared query is that they separate the sql data values from the sql syntax, making it impossible for sql special characters in the data to break the sql syntax, which is how sql injection is accomplished. A secondary point is that they provide a minor (about 5%) performance gain if you execute the same query more than once within an instance of your script.

Since only sql data values (numbers, strings, …) can be supplied via place-holders in a prepared query, there’s no good reason to use the extra statements, with the added processing needed, with a query that does not have any data values being supplied to it, such as a CREATE table query. You should just use the ->query() method for such a query.

Sponsor our Newsletter | Privacy Policy | Terms of Service