user2998401
user2998401

Reputation: 67

INSERT Query Syntax Error in PHP and MySQL

I am not able to insert id and name in myTable MySQL table by using following PHP syntax. id is integer field and name is varchar field.

$query="INSERT INTO myTable (id, name) VALUES (".$_SESSION["id"].", ".$_SESSION["name"].");";

Is there something wrong with above syntax? As per me its right because if insert hardcoded values, those are inserted fine.

Upvotes: 1

Views: 61

Answers (5)

Damodaran
Damodaran

Reputation: 11065

String should be enclosed in quotes

 $query="INSERT INTO myTable (id, name) VALUES (".$_SESSION["id"].", '".$_SESSION["name"]."');";

Upvotes: 2

Hanky Panky
Hanky Panky

Reputation: 46900

Put the string value inside quotes:

$query="INSERT INTO myTable (id, name) VALUES (".$_SESSION["id"].", '".$_SESSION["name"]."');";

Upvotes: 2

UltraInstinct
UltraInstinct

Reputation: 44474

Yes, you need to use single quotes for name

$query="INSERT INTO myTable (id, name) VALUES (" . $_SESSION["id"] . ", '" . $_SESSION["name"]."');";

Also, please try not to contstruct the queries by hand using string concatenation/substitution. It can be dangerous if your $_SESSION (somehow) contains content that can manipulate queries completely.

Read about SQL Injection, and what PHP offers.

Upvotes: 3

elixenide
elixenide

Reputation: 44851

name is a reserved word. Put backticks around it. Also, you need quotes around your name variable (and the id, if it is not an integer).

Your query should look like this:

$query="INSERT INTO myTable (id, `name`) VALUES (".$_SESSION["id"].", '".$_SESSION["name"]."')";

Upvotes: 1

Osama Jetawe
Osama Jetawe

Reputation: 2705

use this

$query="INSERT INTO myTable (id, name) VALUES ({$_SESSION["id"]},'{$_SESSION["name"]}');";

Upvotes: 0

Related Questions