0

Can't get this to work! Why?? Have searched all over the Internet including here on Stackoverflow, but I just can't figure this out!

$myvar = "thisdb";
$file_name = "myfilename";
mysql_query("INSERT INTO mydb_".$myvar." (myplace) VALUES ('$file_name')");

Have tried with:

mysql_query("INSERT INTO mydb_".$myvar." myplace VALUES '$file_name'");

and:

mysql_query("INSERT INTO mydb_".$myvar." (myplace) VALUES ($file_name)");

...but still won't add this to my database!

Thanks in advance!

The Simon
  • 105
  • 2
  • 2
  • 9

2 Answers2

0

You don't need the . . for the $myvar in that SQL query. Unless you start working with session variables where you store data to take over to other pages you can just call it up like that if you've defined it prior to the query.

Example of connect script:

 // Server Details //
 $host = "---";
 $username = "---";
 $password = "---";
 $database_name = "mydb";
 $myvar = "thisdb";

 // Connect Command //
 mysql_connect($host, $username, $password) OR die("Can't connect");
 mysql_select_db($database_name) OR die("Can't connect to Database");

After that you can just do:

mysql_query("INSERT INTO $myvar (myplace)
VALUES ('$file_name')") or die(mysql_error());
Sean Limpens
  • 79
  • 1
  • 1
  • 12
  • Have tried that, doesn't make any difference... Have even tried removing the variable and just go mydb_thisdb, but still nothing. – The Simon Oct 16 '13 at 14:08
  • Are you successfully running a connect to DB script? If so, you shouldn't even need the db name in your query - just the tablename (which can be defined as $myvar) (see edited answer) – Sean Limpens Oct 16 '13 at 14:11
-1

First you need to use mysql_connect to connect to the database and select it. Then you need to pass that as the second parameter of mysql_query.

mysql_query("INSERT INTO $tablename columns VALUES '$vaue1'", $connection);

Judging by your variable name you are putting Database name instead of the table name.

Also I would suggest using mysqli instead as mysql is deprecated.

/* make your connection */
$sql = new mysqli('localhost','username','password','localhost');

$query = "INSERT INTO `$tableName` (`id`,`name`,`age`) VALUES ('$value');";

if ( $sql->query($query) ) {
    echo "A new entry has been added with the `id` of {$sql->insert_id}.";
} else {
     echo "There was a problem:<br />$query<br />{$sql->error}";
}

/* close our connection */
$sql->close();
Antony D'Andrea
  • 991
  • 1
  • 16
  • 35
  • 2
    The second param is optional. I don't think OP is advanced enough to be working with multiple databases. w3fools.com – Mike B Oct 16 '13 at 14:21
  • Ok, but it still looks like he is putting the database name instead of the table name and the link shows him exactly what he needs to do. – Antony D'Andrea Oct 16 '13 at 14:23
  • Please, [do not link to or use w3schools.com](http://w3fools.com/). It does way more damage than good. – tadman Oct 16 '13 at 14:25