Jesper Olsen Jesper Olsen - 3 months ago 16
MySQL Question

Insert into with variables php mysql

Im having some trouble getting my SQL query to 'insert into' my database, is it allowed to use variables as table name, field name, and values?

Here my code:

$nameOfDBFromA = "vagtplanA" . $_GET["from"];

$flytnedToQ1 = $con->prepare("SELECT * FROM $nameOfDBToA WHERE ansatId='$_GET[ansatId]' ORDER BY id DESC");
$flytnedToQ1->execute();
$flytnedTo1 = $flytnedToQ1->fetch();

$nameOfFieldToA1 = "a" . $_GET["to"] . "1";
$nameOfFieldToA2 = "a" . $_GET["to"] . "2";
$nameOfFieldToA3 = "a" . $_GET["to"] . "3";
$nameOfFieldToA4 = "a" . $_GET["to"] . "4";
$nameOfFieldToA5 = "a" . $_GET["to"] . "5";
$nameOfFieldToA6 = "a" . $_GET["to"] . "6";
$nameOfFieldToA7 = "a" . $_GET["to"] . "7";

$redigeringsTidspunkt = date("j M Y");

$flytnedTA = $con->prepare(
"INSERT INTO $nameOfDBFromA
(ansatId, edit, $nameOfFieldToA1, $nameOfFieldToA2,
$nameOfFieldToA3, $nameOfFieldToA4, $nameOfFieldToA5,
$nameOfFieldToA6, $nameOfFieldToA7)
VALUES($_GET[ansatId], $redigeringsTidspunkt,
$flytnedTo1[$nameOfFieldToA1], $flytnedTo1[$nameOfFieldToA2],
$flytnedTo1[$nameOfFieldToA3], $flytnedTo1[$nameOfFieldToA4],
$flytnedTo1[$nameOfFieldToA5], $flytnedTo1[$nameOfFieldToA6],
$flytnedTo1[$nameOfFieldToA7]) ")
or die(mysql_error());
$flytnedTA->execute();


SOLVED! I just put my arrays into it own variable

$intoVarToA1 = $flytnedTo1[$nameOfFieldToA1];
$intoVarToA2 = $flytnedTo1[$nameOfFieldToA2];
$intoVarToA3 = $flytnedTo1[$nameOfFieldToA3];
$intoVarToA4 = $flytnedTo1[$nameOfFieldToA4];
$intoVarToA5 = $flytnedTo1[$nameOfFieldToA5];
$intoVarToA6 = $flytnedTo1[$nameOfFieldToA6];
$intoVarToA7 = $flytnedTo1[$nameOfFieldToA7];

Answer

One of your mistakes is When u want to access an value in an array inside of a string, you can't do

"$flytnedTo1[$nameOfFieldToA1]"

You have to do it like this:

"{$flytnedTo1[$nameOfFieldToA1]}" // use curly brackets