【问题标题】:Save array into database将数组保存到数据库中
【发布时间】:2012-06-27 09:31:50
【问题描述】:

我在将数组插入数据库时​​出错。 错误:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 23 行的“访问学生应咨询学生应参考相关部分”附近使用正确的语法。

这是下面的数组

array
 'Choose by Subject Category or Module Code' => string '' (length=0)
 '
Back to Home page' => string '' (length=0)
 'International' => string 'visiting students should consult the' (length=36)
 'Undergraduate' => string 'students should refer to the relevant section of the UCC' (length=56)
 'Postgraduate' => string 'students should refer to the relevant section of the UCC' (length=56)
 'Credit Weighting' => string '5' (length=1)
 'Teaching Period(s)' => string 'Teaching Period 1.' (length=18)
 'No. of Students' => string 'Min 15, Max 30.' (length=15)
 'Pre-requisite(s)' => string 'None' (length=4)
 'Co-requisite(s)' => string 'None' (length=4)
 'Teaching Methods' => string '1 x 4hr(s) Lectures; Other (Distance Education Module - Up to 146hrs Self Directed Study).' (length=90)
 'Module Co-ordinator' => string 'Dr Peter Cleary, Department of Accounting, Finance and Information Systems.' (length=75)
 'Lecturer(s)' => string 'Staff, Department of Accounting, Finance and Information Systems.' (length=65)
 'Module Objective' => string 'To examine the management uses of accounting information and to enhance students ability to exert effective managerial control.' (length=127)
 'Module Content' => string 'Topics include; the accounting information needs of management, costs and pricing; estimating costs; the identification of key performance indicators; budgeting for control; capital investment appraisal and  implications for strategic planning and control.' (length=256)
 'Learning Outcomes' => string 'On successful completion of this module, students should be able to:' (length=68)
 'Assessment' => string 'Total Marks 100: Continuous Assessment 100 marks (Project/ Essay. Approximately 1500 words.).' (length=93)
 'Compulsory Elements' => string 'Continuous Assessment.' (length=22)
 'Penalties (for late submission of Course/Project Work etc.)' => string 'Where work is submitted up to and including 7 days late, 10% of the total marks available shall be deducted from the mark achieved.  Where work is submitted up to and including 14 days late, 20% of the total marks available shall be deducted from the mark achieved.  Work submitted 15 days late or more shall be assigned a mark of zero.' (length=336)
 'Pass Standard and any Special Requirements for Passing Module' => string '40%.' (length=4)
 'End of Year Written Examination Profile' => string 'No End of Year Written Examination.' (length=35)
 'Requirements for Supplemental Examination' => string 'Marks in passed element(s) of Continuous Assessment are carried forward, Failed element(s) of Continuous Assessment must be repeated (Resubmission of revised Continuous Assessment).' (length=181)

下面是查询。

//============== INSERT QUERY================//
$result = array();      
foreach($result as $snode){ 
$query = sprintf("INSERT INTO save_array 
       (ModuleCode,
        Homepage,
        International,
        ......) VALUES ('%s')",mysql_real_escape_string($snode)); 


foreach ($result as $key => $value) 
$query = $query . "$value"; 

 echo '<br /><br />'; 
mysql_query($query) or die($query."<br/><br/>".mysql_error());  
echo $snode. '<br />'; 
}
echo '<br /><br /><br />'; 

如果能解决这个问题,我们将不胜感激。

//================== New Updated Query Using Mysqli =============================

$result = array();
foreach($result as $snode){ 
$snode = mysql_real_escape_string($snode);
$query = sprintf("INSERT INTO save_array 
       (ModuleCode,Homepage,International,.......)VALUES ('%s')",implode("','",$result)); 

echo $query. '<br />'; 

foreach ($result as $key => $value) 
    $query = $query . "$value"; 
$result = mysql_query($query) or die (mysql_error());
}

我回显了查询,似乎将正确的值插入到正确的列中,但没有执行到数据库中。

错误:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 23 行的“访问学生应咨询学生应参考相关部分”附近使用正确的语法

【问题讨论】:

  • 请不要将mysql_* 函数用于新代码。它们不再维护,社区已经开始deprecation process。看到red box?相反,您应该了解prepared statements 并使用PDO 或MySQLi。如果您不能决定,this article 将帮助您选择。如果你想学习,here is good PDO tutorial.
  • 好吧,我只是在学习 PHP,所以对旧代码和新代码不太熟悉。如果我决定使用 MySQLi,这是否意味着我必须更改我编写的所有 PHP 脚本才能使用 MySQLi 或这是如何运作的??我会看看 PDO,看看我能从中得到什么。
  • 你能在你的问题中添加结果查询吗?并且在第一个问题解决之前不要使用mysqli。

标签: php mysql curl


【解决方案1】:

您正在尝试保存到多个列:

ModuleCode,
Homepage,
International,
Undergraduate,
...

具有单个值('%s')

还请注意,mysql_real_escape_string 采用 SINGLE 值,而不是数组(我假设 $snode 是一个数组)。 还可以考虑使用PDO 或mysqli。

您可以这样做(例如;不知道 $snode 结构)并检查输出:

foreach($snode as &$val) {
   $val = mysql_real_escape_string($val);
}
...VALUES ('%s'),implode("','",$snode)

更新:

我找不到问题;查询应该可以工作。 我什至在我的系统中创建了您的表结构(假设每一列的 VARCHAR(256))并且您的查询输出按预期工作(插入)..

$result = array();
foreach($result as $snode) { 

   foreach($snode as &$val) {
      $val = mysql_real_escape_string($val);
   }

   $query = sprintf("INSERT INTO save_array (
        ModuleCode,Homepage,International,Undergraduate,Postgraduate,CreditWeighting, 
        TeachingPeriod,NoofStudents,Prerequisite,Corequisite,TeachingMethods, 
        ModuleCoordinator,Lecturer,ModuleObjective,ModuleContent,LearningOutcomes, 
        Assessment,CompulsoryElements,Penalties,PassStandard, 
        EndofYearWrittenExamination,RequirementsforExamination) 
        VALUES ('%s')",implode("','",$snode)); 

   $result = mysql_query($query) or die (mysql_error());
}

按原样运行上面的 sn -p ;不要改变任何东西。

【讨论】:

  • 嘿抱歉。我使用 mysqli 更新了我的代码,似乎将正确的值放入正确的列中,但没有将其保存到数据库中。不知道做错了什么?
  • 我尝试了你的方法,得到的结果与@Jack 的方法相同。:(
  • 有错误吗?调用错误报告(E_ALL);在脚本的顶部带来'em'all(只是为了安全)。我还看到你变成了 mysqli_。那是你唯一的改变?连接器 mysqli_connect 怎么样。坚持使用 mysql_ 直到问题解决,然后升级(以尽量减少干扰实际问题的噪音)
  • 所以我有 error_reporting(E_ALL);在我的代码中。我更改为 mysqli,因为我认为它可能会对我的查询结果产生影响。但是现在我回到 mysql,直到我解决问题为止。我有上面查询的结果。请看一下。谢谢。
  • 我尝试了你在更新帖子上所做的 sn-p,但它仍然是一样的。没有任何内容保存到数据库中。现在使用挫折不是正确的词。已经重建并尝试了许多其他我做过的示例代码版本,但仍然没有得到它。非常感谢你的帮助,你真的帮了我很多。
【解决方案2】:

回显您的 $query,您会看到。 这不是有效的 SQL 语句。

用于调试动态查询的规则号 1,2 和 3:查看查询本身。

【讨论】:

  • 不,这些是第 2、3 和 4 条规则。#1 不能使用 mysql_*。
  • 我回应了我的查询,似乎将正确的值放在正确的列中,但仍未将其保存到数据库中。
【解决方案3】:

你的主要问题是引号:

('%s')

然后是你的:

mysql_real_escape_string

这会导致您的 SQL 发生冲突。使用 MySQL 转义或 '.

所以发生的事情是你双重转义你的 SQL 输入,这导致它实际上是 SQL 注入......

另外,MYSQL 真正的转义字符串不会将 $snode 作为数组插入。您将需要 foreach 数组提取值构建和数组以注入 SQL 查询。

【讨论】:

    【解决方案4】:

    假设您的数组 $node 与您显示的列的顺序相同,您可以改用 vsprintf() 来生成结果查询:

    // assuming $node is the array with the data
    // generate list of place holders
    $placeholders = join(',', array_fill(0, count($node), "'%s'"));
    
    // construct full query using array_map applied to the escaping function
    $query = vsprintf("INSERT INTO save_array (ModuleCode,
            Homepage,
            International,
            Undergraduate,
            Postgraduate,
            CreditWeighting,
            TeachingPeriod,
            NoofStudents,
            Prerequisite,
            Corequisite,
            TeachingMethods,
            ModuleCoordinator,
            Lecturer,
            ModuleObjective,
            ModuleContent,
            LearningOutcomes,
            Assessment,
            CompulsoryElements,
            Penalties,
            PassStandard,
            EndofYearWrittenExamination,
            RequirementsforExamination) VALUES ($placeholders)", 
                array_map('mysql_real_escape_string', $node)
    );
    

    顺便说一句,不要使用mysql_ 函数!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-08
      • 2019-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-29
      • 1970-01-01
      相关资源
      最近更新 更多