我很难弄清楚这段代码出了什么问题。我尝试了许多变化,但仍然得到错误在这一行:
$query= "INSERT INTO publish (name, email, title, content)" .
"VALUES ('$row['Name']','$row['Email']',$row['title'],$row['content'])";
怎么了?
下面是剩下的代码:<?php
// connect to the database
include('config2.php');
// check if the 'id' variable is set in URL, and check that it is valid
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
// get id value
$id = $_GET['id'];
$dbc = mysqli_connect('localhost', 'x', 'x', 'x')
or die('Error');
$name = $row['Name'];
$email = $row['Email'];
$title = $row['title'];
$content = $row['content'];
$result = mysql_query("select *stories WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array( $result );
$query= "INSERT INTO publish (name, email, title, content)" .
"VALUES ('$row['Name']','$row['Email']',$row['title'],$row['content'])";
or die('Error querying database.');
mysqli_close($dbc);
}
?>
错误信息:"parse Error expected identifier (t_string) "' or variable (t_variable)' or number (t_num_string)"
您可能需要使用复杂的字符串语法来正确地插入这些变量。例如:
$query= "INSERT INTO publish (name, email, title, content)" .
"VALUES ('{$row['Name']}','{$row['Email']}',{$row['title']},{$row['content']})";
虽然这只会解决代码中的一个问题。
请注意,还有很多其他的方法来解决这个问题,比如串联而不是插值,或者字符串替换,等等。
在某些时候,关于字符串的文档也值得阅读。
您忘记了变量和字符串之间的"。"像这样:
$query= "INSERT INTO publish (name, email, title, content)" .
"VALUES (".$row['Name'].','.$row['Email'].','.$row['title'].','.$row['content'].")";
然而,看起来您在实际的SQL查询中可能会遇到一些额外的问题。
PHP的最佳实践是对字符串使用单引号'
。Cos PHP查找双引号字符串中的变量,并继续嗅探字符串中是否有一个变量(或多个变量)。
例如:"A very very long string…美元var1 . .长串…$var2 string"与'A very very long string…"。var1美元。". .长串…"。var2美元。"字符串";因为当PHP看到单引号时,它不会嗅探其中的变量,因此速度更快。
根据我的经验,在我年轻的时候,我在一个非常大的php脚本中工作,到处都使用双引号。经过专家的上述解释,我将整个脚本转换为单引号,性能好多了。
所以针对你的情况,我建议并要求使用单引号,这样也可以避免混淆。使用mysql_real_escape_string()
是避免使用SQL Injection
的好方法。
$query= 'INSERT INTO publish (name, email, title, content)
VALUES (
''' . mysql_real_escape_string ($row['Name']) . ''',
''' . mysql_real_escape_string ($row['Email']) . ''',
''' . mysql_real_escape_string ($row['title']) . ''',
''' . mysql_real_escape_string ($row['content']) . ''')';