我认为通过将数组中的值和字段名称连接起来然后将它们插入到SQL中我很聪明。这是为了节省我将大量的值直接放入我的函数中使用。
所以我有一个数组,我循环并连接值来创建一个字符串。
foreach ($customer_info as $key=>$value) {
$fieldInsert .= '`'.$key.'`,';
$valueInsert .= $value.',';
}
$fieldInsert = rtrim($fieldInsert, ",");
$valueInsert = rtrim($valueInsert, ",");
这正确地创建了两个字符串,例如:
`field1`,`field2`,`field3`
value1,value2,value3
然后我有了我的疑问:
$query = $mysqli->query("INSERT INTO `customers` ('$fieldInsert') VALUES ('$valueInsert')");
var_dump($query);
但它不起作用。有什么帮助吗?
尝试设置错误处理,因为我们在为别人项目工作时发言。
答案 0 :(得分:0)
我不在mySql中工作,但我确实熟悉SQL。问题是您不能在查询中使用变量作为对象名,除非您构建整个字符串并将其传递给执行命令。我将在t-SQL中向您展示一个我母语的例子。
您会注意到我创建了两个表并将数据放入其中。它们具有不同的列和表名,但从中选择的SQL语句使用变量连接成可重用的语句。构造语句后,我将其传递给EXECUTE命令。我相信mySql命令是EXECUTE IMMEDIATE,但我不确定。
IF EXISTS (SELECT * from sys.tables where name = 'People')
DROP TABLE People
GO
-- First create one table with a list of people
CREATE TABLE People(
PersonId INT NOT NULL,
FirstName VARCHAR(20) NULL,
LastName VARCHAR(20) NULL
)
GO
INSERT INTO People (PersonId, FirstName, LastName) VALUES
(1, 'George', 'Washington'),
(2, 'Thomas', 'Jefferson'),
(3, 'Teddy', 'Roosevelt'),
(4, 'Abe', 'Lincoln')
GO
IF EXISTS (SELECT * from sys.tables where name = 'RushmoreHeads')
DROP TABLE RushmoreHeads
GO
-- Then create one table with a list of the heads on Mount Rushmore
CREATE TABLE RushmoreHeads(
RushId INT NOT NULL,
Name VARCHAR(30) NULL,
PresidentNumber INT NULL
)
GO
INSERT INTO RushmoreHeads(RushId, Name, PresidentNumber ) VALUES
(1, 'George Washington', 3),
(2, 'Thomas Jefferson', 2),
(3, 'Teddy Roosevelt', 26),
(4, 'Abe Lincoln', 16)
GO
DECLARE @SQLPrefix VARCHAR(200)
DECLARE @SQLDelimiter VARCHAR(200)
DECLARE @SQLSuffix VARCHAR(200)
DECLARE @SQLWhere VARCHAR(200)
DECLARE @Table VARCHAR(20)
DECLARE @Column1 VARCHAR(20)
DECLARE @Column2 VARCHAR(20)
DECLARE @Column3 VARCHAR(20)
DECLARE @SQL2Execute VARCHAR(2000)
SET @SQLPrefix = 'SELECT '
SET @SQLSuffix = ' FROM '
SET @SQLDelimiter = ' , '
-- Object names from first table
SET @Table = 'People'
SET @Column1 = 'PersonId'
SET @Column2 = 'FirstName'
SET @Column3 = 'LastName'
-- Construct the select statement
SET @SQL2Execute = @SQLPrefix + @Column1+ @SQLDelimiter +
@Column2+ @SQLDelimiter + @Column3+ @SQLSuffix + @Table
PRINT @SQL2Execute
EXECUTE (@SQL2Execute)
-- Object names from second table
SET @Table = 'RushmoreHeads'
SET @Column1 = 'RushId'
SET @Column2 = 'Name'
SET @Column3 = 'PresidentNumber'
-- Same code as first table
SET @SQL2Execute = @SQLPrefix + @Column1+ @SQLDelimiter +
@Column2+ @SQLDelimiter + @Column3+ @SQLSuffix + @Table
EXECUTE (@SQL2Execute)
PRINT @SQL2Execute