通过PHP将数据插入MySQL表时出错

时间:2013-10-28 16:15:54

标签: php mysql sql mysqli

我有一个带有表" AllParties"的MySQL数据库。当我使用PHP(下面)将数据插入该表时,我没有收到错误,但是,数据没有插入到表中。我尝试从MySQL服务器获取错误报告,而且含糊不清地说它在MySQL语法中有错误。请注意我在Mac CodeRunner中运行我的代码,可能这是问题所在?此外,$ con是一个成功的连接。

<?php
$con=mysqli_connect("sql3.freemysqlhosting.net","*********","********","*********");

$name = "Will's Party";
$date = 'October 1st, 2013';
$housenum = '333 East Street';
$city = "Golden Gate";
$state = "California"; 
$time = "7:00";
$tag = "Serra";

mysqli_select_db('AllParties', $con);

$alpha = mysqli_query($con, 'INSERT INTO AllParties(Party Name, Date, House number and       street name, City, State, Time, Tag)  VALUES("$name","$date","$housenum","$city","$state","$time","$tag")');
?>

2 个答案:

答案 0 :(得分:0)

任何包含空格的列名,以及这样的命名列都是让开发人员感到非常不安的好方法,需要进行转义:

INSERT INTO AllParties (`Party Name`, ...)

反引号,而不是常规引号,用于转义数据库,表和列名称。常规引号'"用于字符串。

答案 1 :(得分:-3)

<?php
$con=mysqli_connect("sql3.freemysqlhosting.net","*********","********","*********");

$name = 'Will\'s Party';
$date = 'October 1st, 2013';
$housenum = '333 East Street';
$city = 'Golden Gate';
$state = 'California'; 
$time = '7:00';
$tag = 'Serra';

mysqli_select_db('AllParties', $con);

$alpha = mysqli_query($con, "INSERT INTO AllParties(`Party Name`, `Date`, `House   number and street name`, `City`, `State`, `Time`, `Tag`)    VALUES('{$name}','{$date}','{$housenum}','{$city}','{$state}','{$time}','{$tag}')");
?>

{$ x}将评估x字符串