gpt4 book ai didi

php - 无法通过 php 向我的数据库发送多个 mysql 查询

转载 作者:太空宇宙 更新时间:2023-11-03 12:05:33 25 4
gpt4 key购买 nike

我不知道这里发生了什么,但我无法通过 mysql_query 获得两个 mysql 语句来将内容添加到我的数据库中。这是我的代码:

function sendDataToDB() {

// first send the user to the users table
$audio_survey = new dbclass();
$audio_survey -> connectToDB();

$sql = $_SESSION['user']['sql'];

$audio_survey -> queryTable($sql);

// get the current users' ID number from the table
$sql = "SELECT user_id FROM users WHERE name=\"" . $_SESSION['user']['name'] . "\"";

$result = $audio_survey -> queryTable($sql);
$output = $audio_survey -> getDataFromDB($result);

$user_id = $output['user_id'];

$songs = $_SESSION['songs'];

foreach ($songs as $song) {

$sql .= "INSERT INTO survey (user_id, song, genre, emotion, time_date) VALUES ($user_id, \"" . $song['song'] . "\", \"" . $song['genre'] . "\", \"" . $song['emotion'] . "\", \"" . $song['time_date'] . "\");<br />";
}
$audio_survey -> queryTable($sql);
$audio_survey -> closeDBconnection();
}

一切正常,因为用户被添加到我的“用户”表中,但是当变量 $sql 被传递到 mysql_query 时,我得到这个错误:

错误:您的 SQL 语法有误;检查与您的 MySQL 服务器版本对应的手册,了解在“INSERT INTO survey (user_id, song, genre, emotion, time_date)”附近使用的正确语法 VALUES (3, "one mo' at line 1

我已经尝试将使用 $sql 变量连接的语句直接粘贴到 phpMyAdmin 中的 sql 查询框中,并且成功了!这是 foreach 循环产生的在 phpMyAdmin 中工作的结果,但不是 mysql_query 函数!我已确保为字符等分配了足够的空间。

INSERT INTO survey (user_id, song, genre, emotion, time_date) VALUES (3, "one more time", "dance", "happy", "15:32:21 07-11-14");
INSERT INTO survey (user_id, song, genre, emotion, time_date) VALUES (3, "dance dance dance", "disco", "relaxed", "15:32:28 07-11-14");

最佳答案

http://php.net/manual/en/function.mysql-query.php

mysql_query() sends a unique query (multiple queries are NOT supported)

文档引用服务 (tm)

您需要使用 Nisse 的方法,同时在循环内调用 mysql_query() - 或者使用其他方法,允许在一个语句中执行多个查询而不是弃用的 mysql_query 方法。

另一种选择是重写您的串联逻辑,因此它会为多个插入生成一个查询:

INSERT INTO survey 
(user_id, song, genre, emotion, time_date)
VALUES
(3, "one more time", "dance", "happy", "15:32:21 07-11-14"),
(3, "dance dance dance", "disco", "relaxed", "15:32:28 07-11-14"),
...

有点像

$sql = "INSERT INTO survey (user_id, song, genre, emotion, time_date) VALUES ";
$atLeastoneInsert = false;
foreach ($songs as $song) {
$atLeastoneInsert = true;
$sql .= "($user_id, \"" . $song['song'] . "\", \"" . $song['genre'] . "\", \"" . $song['emotion'] . "\", \"" . $song['time_date'] . "\"),";
}
$sql = trim($sql,",");

if ($atLeastoneInsert){
$audio_survey -> queryTable($sql);
}

关于php - 无法通过 php 向我的数据库发送多个 mysql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26811061/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com