1

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.

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Put the string value inside quotes:

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

Comments

2

String should be enclosed in quotes

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

1 Comment

okay, I forgot put single quotes around name field. Thanks, its working now.
1

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"]."')";

3 Comments

Hmm... You're right. It is formatted like one in MySQL Workbench, so I guess I just assumed it was. I always surround my column names with backticks, anyway, to be safe; I spent many hours debugging a column named desc when I was first starting out...
@EdCottrell - sorry, I was using ename field and in questions I put name field.
0

use this

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

Comments

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.