2

Hey guys i want to use an php variable as a part of a name of a mysql table which i create with a query. I used two types of quotes like a example i saw on the internet. It should create an individual table name. $cn is not an array it is an single value. I have php error reporting enabled and it doesn't show any errors. Here is what i tried:

$sql2 = "CREATE TABLE lm_Warenkorb_`".$cn."`
     (
     Index TEXT,
     )";

Why isn't this working? Is this possible or not? Hope it is clear what i want to do.

1
  • 1
    Just a shot in the dark here... but does your database user have the create privilege? Commented Nov 29, 2012 at 11:43

3 Answers 3

3
$sql2 = "CREATE TABLE `lm_Warenkorb_".$cn."`
     (
     Index TEXT,
     )";
Sign up to request clarification or add additional context in comments.

7 Comments

If $cn is from user input, you should also make sure that $cn doesn't contain any backtick or other illegal characters, otherwise a SQL injection attack may be possible.
doesn't work for me it runs through but no table is appearing
@SDC answer was given according to Pgr456 code, assuming all check has already done
@Pgr456 did you select DB first?
triclosan can't you imagina what could be also wrong i selected database before
|
2

I think you'll need to wrap the entire table name in backticks...

$sql2 = "CREATE TABLE `lm_Warenkorb_{$cn}`
     (
     Index TEXT,
     )";

Also you can use curly brackets to insert variables into strings encapsulated with double quotes.

3 Comments

If $cn is from user input, you should also make sure that $cn doesn't contain any backtick or other illegal characters, otherwise a SQL injection attack may be possible.
@SDC - most certainly. In any case, one should take care to sanitize any user submitted data that is destined to be saved/used at a later stage.
yep. I guess my point is that it needs to be sanitised differently from most other strings that are inserted into a SQL statement. The standard sanitation methods aren't useful when you have dynamic tablenames and fieldnames, but doing the sanitation is just as important.
2

Your code will produce string:

CREATE TABLE lm_Warenkorb_`some_string`(Index TEXT,)

I think it must be 2 variants:

CREATE TABLE `lm_Warenkorb_`.`some_string`(Index TEXT,)

Or

CREATE TABLE `lm_Warenkorb_some_string`(Index TEXT,)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.