0

This code should check if a user is in a table and if not create a table for the user. Right now it just names the table $MyServer. How do I make it so the name is the variable $MyServer.

<?php
    require "conn.php";
    echo "debug 1";
    $stmt = $conn->prepare("SELECT * FROM UserData WHERE username = ?");
    $stmt->bind_param('s',$username);
    $username = $_POST["username"];
    $stmt->execute();
    $stmt->store_result();

    echo "debug 2";
    if ($stmt->num_rows == 0){ // username not taken
        echo "debug 3";
        $stmt2 = $conn->prepare("INSERT INTO UserData (username, password) VALUES (?, ?)");
        $password =($_POST["password"]);
        $username =($_POST["username"]);
        $stmt2->bind_param('ss', $username, $password);
        $stmt2->execute();
        $MyServer =($_POST["username"]);
        $sql = ('CREATE TABLE $MyServer (
            id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
            username VARCHAR(30) NOT NULL
            )');
        if($conn->query($sql) === TRUE){
            echo "Table created successfully";
        } else {
            echo "Table is not created successfully ";
        }

        if ($stmt2->affected_rows == 1){
            echo 'Insert was successful.';

        }else{ echo 'Insert failed.';
            var_dump($stmt2);
        }
    }else{ echo 'That username exists already.';}

    ?>
4
  • 1
    If you're creating a table for each user, you need to evaluate your data structure, that's generally a monumentally bad idea. Commented Aug 5, 2017 at 9:52
  • Also note you're wide open to SQL injection attacks, Commented Aug 5, 2017 at 10:19
  • how would i protect myself from it Commented Aug 5, 2017 at 13:18
  • How would i do this with prepared statements Commented Aug 5, 2017 at 13:43

2 Answers 2

1

creating table for each user is not good idea. You need to create single table in which you can store all users records

But if you really want to do this. You need to change ' to " do your variable can take value

$sql = "CREATE TABLE $MyServer (
            id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
            username VARCHAR(30) NOT NULL
            )";

See the difference:

http://docs.php.net/manual/en/language.types.string.php

Sign up to request clarification or add additional context in comments.

Comments

0

Despite my comment above, here is what you're looking for: Notice that now, "$MyServer" is no longer seen as a string, but an actual variable.

$sql = ('CREATE TABLE ' . $MyServer . '(
        id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
        username VARCHAR(30) NOT NULL
        )');

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.