0

use php variable in name of mysql create table

I want to use a PHP variable ( $userAltId ) as the name of the SQL table I am creating. However, despite looking at several examples, I have been unable to successfully create a table with this PHP variable. Using echo I have shown that the variable ( $userAltId ) does contain the predicted value, and if I plug in that value instead of the variable I can successfully create the table.

My latest attempt at the code is below, notice I use $useAltId three times, from creating, inserting, and selecting. Thanks for the help!

<?php

$con=mysqli_connect('localhost', 'alexpnqo_johnny', '?KlI+TtfNEIO', 'alexpnqo_johnny');
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
session_start();
$userAltId = $_SESSION['userAltId'];//I am passing $userAltId from another php file


// escape variables for security
$FBname = mysqli_real_escape_string($con, $_POST['FBname']);

echo $userAltId;//echos desired value

$sqlFriendList="INSERT INTO '$userAltId' (FacebookFriend)
VALUES ('$FBname')";

if (mysqli_query($con,$sql)) {
  echo "Table created successfully";
} else {
  echo "Error creating table: " . mysqli_error($con);";
}

echo "You have added ";
echo $FBname;
echo " to your friend's list!";
echo "<br>";
echo "Below is your friends list";
echo "<br>";
echo "<br>";


$result = mysqli_query($con, "SELECT FacebookFriend FROM '$userAltId'");

echo "<table border='1'>
 <tr>
<th>Friends List</th>
</tr>";

while($row = mysqli_fetch_array($result)) {
    echo "<tr>";
    echo "<td>" . $row['FacebookFriend'] . "</td>";
    echo "</tr>";
}

echo "</table>";

mysqli_close($con);
?> 
2
  • 1
    mysqli_error($con);"; extra quote " and ; semicolon? Commented Aug 20, 2014 at 3:16
  • My bad, that was just a copy and paste error of mine when entering the code into this post Commented Aug 20, 2014 at 13:06

1 Answer 1

2

Use backticks $userAltId to all your queries (table name) so that it'll read your variable even spaces.

$sqlFriendList="INSERT INTO `$userAltId` (FacebookFriend) VALUES ('$FBname')";
Sign up to request clarification or add additional context in comments.

1 Comment

Hey John. I tried that, but unfortunately it did not work. Have any other ideas?

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.