Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
add comment

5 Answers

up vote 3 down vote accepted

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.

share|improve this answer
    
thanks for solution and suggestion on SQL injection –  user2998401 Nov 16 '13 at 7:29
add comment

Put the string value inside quotes:

$query="INSERT INTO myTable (id, name) VALUES (".$_SESSION["id"].", '".$_SESSION["name"]."');";
share|improve this answer
add comment

String should be enclosed in quotes

 $query="INSERT INTO myTable (id, name) VALUES (".$_SESSION["id"].", '".$_SESSION["name"]."');";
share|improve this answer
    
okay, I forgot put single quotes around name field. Thanks, its working now. –  user2998401 Nov 16 '13 at 7:21
add comment

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"]."')";
share|improve this answer
    
I don't really think so: dev.mysql.com/doc/refman/5.5/en/reserved-words.html –  Hanky 웃 Panky Nov 16 '13 at 7:15
1  
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... –  Ed Cottrell Nov 16 '13 at 7:19
    
@EdCottrell - sorry, I was using ename field and in questions I put name field. –  user2998401 Nov 16 '13 at 7:23
add comment

use this

$query="INSERT INTO myTable (id, name) VALUES ({$_SESSION["id"]},'{$_SESSION["name"]}');";
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.