简体   繁体   中英

SQL syntax: passing variable to SQL select query

I'm trying to pass variables into the select query. Quer is below

$Email = $_POST["Email"];
$Username = $_POST["User_Name"];
$FirstName = $_POST["First_Name"];
$Password = $_POST["Password"];


$CreateTable = "CREATE TABLE IF NOT EXISTS "+$Username+" (
address_id int(11) NOT NULL 
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;" ;

But the table wasn't creating. Where I missed?

Thanks your valuable time.

As you would not be able to use prepared statements with this type of query you should perhaps attempt to remove potentially harmful characters from the supplied user input.

$email = filter_input( INPUT_POST, 'Email', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH );
$username = filter_input( INPUT_POST, 'User_Name', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH );
$firstname = filter_input( INPUT_POST, 'First_Name', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH );
$password = filter_input( INPUT_POST, 'Password', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH );


/* Strip any non alphanumeric charachters and replace space with underscore */
$username = preg_replace('@^[\da-z]$@i','', str_replace( ' ', '_', $username ) );


$sql = "CREATE TABLE IF NOT EXISTS `{$username}` (
    address_id int(11) NOT NULL 
) ENGINE=MyISAM DEFAULT CHARSET=utf8;";

$db=new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$db->query( $sql );

You are using '+' symbol to connect two string (which will not work in php).

You should use '.' to connect two strings.

See answer : How to combine two strings together in PHP?

Your SQL statement should look like this :

$CreateTable = "CREATE TABLE IF NOT EXISTS ".$Username." (
address_id int(11) NOT NULL 
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;" ;

BTW, It's not recommended to execute sensitive queries such as creating (NOR DELETING) tables within your php script.

You should check your PHP file. And try

$tableUser = "CREATE TABLE IF NOT EXISTS ".$Username."(
index int(11) NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;" ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM