开发者

Database insert in PHP returns string not defined and notice about unknown column

开发者 https://www.devze.com 2023-01-31 06:06 出处:网络
I\'m trying to insert into a database a field called Id_Obj and it\'s a VarChar but when I try to send it I get an error:

I'm trying to insert into a database a field called Id_Obj and it's a VarChar but when I try to send it I get an error:

Unknown Column 'Id_Obj4' in 'field List'

T开发者_开发技巧he insert looks like this:

while($info=mysql_fetch_Array($data))
{
  print "name :".$info['Id']." ";
  $count=$info['Id'];
}

$t = "INSERT INTO Table_Faces(Id_Obj,Num_Sides)VALUES(";
$t = $t."IdObj$count".",".$_GET["ns"];
$t = $t.")";

mysql_query($t);

The fields in the database are Id, Id_Obj, Num_Sides.


Couple of things:

  1. You really want to make sure that your values are escaped
  2. You're missing out on your last ")" in the query
  3. Your strings need to be wrapped in quotes, otherwise it thinks you're using a table name

Your SQL can be like:

$t ="INSERT INTO Table_Faces(Id_Obj,Num_Sides)VALUES('IdObj4','". $_GET["ns"]. "')";

Also, just as a side so you know the shortcut:

$t = $t . " something added"; is the same as $t .= " something added"


You need to wrap strings with single quotes in SQL.

$ns = intval($_GET('ns')); // This should sanitize $ns enough for the db.
if ($ns > 0)
{
  $t="INSERT INTO Table_Faces(Id_Obj,Num_Sides)VALUES(";
  $t = $t."'IdObj4'".",".$ns . ")";
  mysql_query($t);
}

You also forgot the closing parenthesis.

I have modified your code to be more resistant to SQL Injection in a very simple way. If you intend to make the Id_Obj a variable as well, you should consider using mysql_real_escape_string() to escape the value for use in your SQL statement.


When you are in a situation where your insert query is so small like this, why you don't use everything in a single line? It saves you from a lot of small problems.. I think @Mark solved your problem.

0

精彩评论

暂无评论...
验证码 换一张
取 消