尝试将数据插入数据库时​​出错

时间:2015-01-17 07:00:03

标签: php

HTML代码

<form id="form1" name="addAnnouncement" method="post" action="ownerAddAnnouncement_exec.php" onsubmit="return validateForm()">
  <label style="font-size:18px">Title:
  <input type="text" name="title" />
  </label>
  <p>
  <label style="margin-left: -36px; font-size:18px;">Description:
  <textarea name="description" rows="6" cols="60"></textarea>
  </label>
  </p>
  <label style="font-size:18px">Date & Time: <br>
  From
  <input type="text" name="from" /> <br>
  To <input type="text" name="to" />
  </label>  <br>
  <label style="font-size:18px">Venue
  <input type="text" name="venue" />
  </label>        
  <p>
  <label>
  <input type="submit" name="Submit" value="Submit" />
  </label>
  </p>
  </fieldset>
  </form>

PHP代码

<?php


$title = $_POST['title'];
$description = $_POST['description'];
$from = $_POST['from'];
$to = $_POST['to'];
$venue = $_POST['venue'];


$link = mysql_connect("localhost","root","") or die();
$db = mysql_select_db("condo") or die("no database found");
$insert_sql="INSERT INTO announcement (title, description, from, to,venue, status)
             VALUES('$title', '$description', '$from', '$to','$venue', 'Pending')"; 

$sql_result=mysql_query($insert_sql) or die("Error in inserting data due to ".mysql_error());

if($sql_result)
    echo "Succesfully insert new data. Please log in back";

        else
    echo "Error in inserting new data";

&GT;

这样的错误(&#34;由于您在SQL语法中出错而导致插入数据时出错;请查看与您的MySQL服务器版本对应的手册,以便在&#39附近使用正确的语法“从,到,状态”VALUES(&#39; melvin&#39;,&#39; sdsaadsd&#39;,&#39; wew&#39;,&#39; ewrerw&#39;,&#39; we3& #39;,&#39; Pendi&#39;在第1行&#34;) 在尝试将数据插入数据库时​​显示出来。

任何人都可以帮我修复代码。我已经在这里停留了1个小时。

4 个答案:

答案 0 :(得分:3)

``中显示字段名称。

将insert语句转换为

$insert_sql="INSERT INTO announcement (`title`, `description`, `from`, `to`,`venue`, `status`)
             VALUES('$title', '$description', '$from', '$to','$venue', 'Pending')"; 

答案 1 :(得分:1)

关于当前错误,它是关于保留关键字,如来自作为字段名称,所以要避免它重命名您的数据库列或将其括在后引号中,如`from`

此外,您可能会遇到其他错误,因为您忽略了代码中的许多良好做法,例如

答案 2 :(得分:1)

您应该使用反引号来转义保留关键字。目前,您使用的是以下保留关键字 - FromTo请尝试以下操作: -

$insert_sql="INSERT INTO `announcement` (`title`, `description`, `from`, `to`,`venue`, `status`)
         VALUES('$title', '$description', '$from', '$to','$venue', 'Pending')"; 

答案 3 :(得分:1)

From是一个关键字。还有To。不建议使用它们。但是如果你无法避免它并仍想使用它们,请在插入查询中添加反引号`如下所示:

INSERT INTO公告(`title`,`description`,`from`,`to`,`status`)              VALUES('$ title','$ description','$ from','$ to','待定')

希望这会有所帮助。

相关问题