0
// Not working
$stmt = $connection->prepare( "INSERT INTO numbers (homePhone, mobilePhone, officePhone)".
    " VALUES ($phone_1,$phone_2,$phone_3)");
$stmt->execute();

// Works
$stmt = $connection->prepare( "INSERT INTO numbers (homePhone, mobilePhone, officePhone)".
    " VALUES (?,?,?)");
$stmt->execute([$phone_1, $phone_2, $phone_3]);

When the first one is executed, it prints the error:

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 1 no such column: blablabla in C:\Users\zahha\IdeaProjects\icd0007\index.php:78 Stack trace: #0 C:\Users\zahha\IdeaProjects\icd0007\index.php(78): PDO->prepare('INSERT INTO peo...') #1 {main} thrown in C:\Users\zahha\IdeaProjects\icd0007\index.php on line 78

The second one works perfectly. What is the problem? Just wondering.

2 Answers2

1

You need quotes around the variables in the first one, to indicate that the values are string literals in SQL.

$stmt = $connection->prepare( "INSERT INTO numbers (homePhone, mobilePhone, officePhone)".
    " VALUES ('$phone_1','$phone_2','$phone_3')");
Barmar
  • 741,623
  • 53
  • 500
  • 612
-1

To make the first one work, you should put the variables between '. For example:

$stmt = $connection->prepare( "INSERT INTO numbers (homePhone, mobilePhone, officePhone)".
    " VALUES ('$phone_1','$phone_2','$phone_3')");
$stmt->execute();

Or taking them out of the string, like:

$stmt = $connection->prepare( "INSERT INTO numbers (homePhone, mobilePhone, officePhone)".
    " VALUES ('".$phone_1."','".$phone_2."','".$phone_3."')");
$stmt->execute();
David Dutra
  • 391
  • 7
  • 21