简体   繁体   中英

Strange difference between what PHP tells me is a error and my code Insert into Mysql Table?

Hello I am doing some simple inserting into a table from my <php> and it doesn't work let me start off with the code:

<?php
include_once "connect.php";
$db_host="localhost";
$user_name="root";
$pass="";
$db_name="knight orders";
$con = mysql_connect("$db_host","$user_name","$pass") or die("There is a problem with the connection");
mysql_select_db("$db_name",$con) or die("There is a problem with the database");
$name="Default";
$rank=3;
//$name=$_POST['name'];
//$rank=$_POST['rank'];
$table_name="ordertemp";
$query="INSERT INTO '$table_name' ('Code','Name')VALUES ('$rank','$name')";
mysql_query($query,$con) or die("Problems!" . mysql_error());
mysql_close($con);
?>

I'm working with some default values now but I will be reading from a form later, the strange thing is when I check out the mysql_error() result in Firefox it tells me:

Problems!You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''ordertemp' ('Code','Name')VALUES ('3','Default')' at line 1

It's changing some of the semicolons, could this be what causes my error, or if you've seen other faults please point them out.

'$table_name' should not be in quotes: it's a table name, not a string column value,

use backticks if you have to, but they aren't necessary

In MySQL quotes ( ' ) are used to denote a string literal.

Backticks ( ` ) are used to denote MySQL 'objects' such as database names, table names and column names.

Don't use quotation marks for table and column names. You can use backticks "`" instead or just leave the quotes out:

$query = "INSERT INTO `{$table_name}` (`Code`, `Name`) VALUES ('{$rank}', '{$name}')";

PS: Never ever insert an unsafe string variable like $name=$_POST['name']; directly into your SQL statements. This makes your application vulnerable against SQL injections. See here for more information: How can I prevent SQL injection in PHP?

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