-2

你好朋友我写了以下代码在 MySQL 中插入评论(如 Facebook),但我没有成功。请帮我。

这是html页面

    <html>
<head><title>ABC</title>
    </head>
    <body>
        <form method="GET" action="try1.php">
    <input type="text" name="like">
    <input type="submit" name="Comment" value="dislike">    
</form>
</body>

现在这是php代码

    <html>
<head><title> </title>
    </head>
    <body>


    <?

//connecting to database

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';

$conn = mysql_connect($dbhost, $dbuser, $dbpass);

if(!$conn )
{
  die('Could not connect: ' . mysql_error());
}
  mysql_select_db("try", $conn);
    $a= array('comments' =>'$_GET["like"]');

  mysql_query("INSERT INTO try1 (Comments) VALUES ('$a')",$conn);
  echo "Record Inserted in table";
mysql_close($conn);
?>
</body>

MySQL 只是显示“数组”。它只是将“数组”存储在 MySQL 字段中请帮助我!

4

3 回答 3

2

你的问题

您正在尝试将数组插入查询!

您需要从数组中提取值。您可以循环遍历数组(这将允许多个值),也可以提取单个值。

以下示例循环遍历您的数组并构建查询:

foreach($array as $column => $value){
    // Append the columns string with the column name
    $columns .= "`$column`,";
    // Escape and append the values string
    $values .= "'".mysql_real_escape_string($value)."',";
}

// Remove the trailing commas
rtrim($columns, ",");
rtrim($values, ",");

$SQL = "INSERT INTO try1 ($columns) VALUES ($values)";

mysql_query($SQL,$conn);

或者,您可以像这样提取和转义数组值

mysql_query("INSERT INTO try1 (count) VALUES ('".mysql_real_escape_string($a['comments'])."')",$conn);

一些忠告

请不要使用mysql_*它们现在已弃用的功能!见这里。您应该使用 PDO 或 Mysqli。

请参阅这些参考资料:

  1. mysqli
  2. PDO
于 2013-06-12T10:58:14.583 回答
0

代替

$a= array('comments' =>'$_GET["like"]');
mysql_query("INSERT INTO try1 (count) VALUES ('$a')",$conn);

有了这个:

$a= array('comments' =>$_GET["like"]);
mysql_query("INSERT INTO try1 (count) VALUES ('".mysql_real_escape_string($a['comments'])."')",$conn);
于 2013-06-12T11:00:40.167 回答
0

你不能这样做:

 $a= array('comments' =>'$_GET["like"]');

  mysql_query("INSERT INTO try1 (Comments) VALUES ('$a')",$conn); 

as$a不是字符串,因此当您将其包含在字符串参数中时,它会简单地输出为“数组”,因此您会在数据库中看到数组。

这会起作用

mysql_query("INSERT INTO try1 (Comments) VALUES ('{$a['comments']}')",$conn);

但是,我强烈建议在问题的评论中听取建议。虽然对学习练习很有用,但您可能需要考虑使用 php web 框架,如 codeigniter 或 cakephp

于 2013-06-12T10:57:23.853 回答