简体   繁体   中英

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.

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.

将字符串值放在引号内:

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

字符串应用引号引起来

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

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

用这个

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM