【问题标题】:How Would I Insert A String With Commas Into MYSQL如何将带逗号的字符串插入 MYSQL
【发布时间】:2012-10-22 14:53:23
【问题描述】:

我正在尝试将表单中的字符串变量插入 mysql,但它一直给我一个错误,并且在错误中它会切断部分语句,所以我认为这是一个问题,因为其中有逗号字符串...

这是一些示例代码:

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form")) {
  $startcode = $_POST['messagefield'];
  $replaced = preg_replace( '/\\\\(?="|\')/', '', $startcode );
  /* NEW CODE */
  /*selectleads[] is now an array of your database's ids. 
    You can now run a query to get whatever information you 
    need. In this case, you want the email addresses, so:
   */
  $collectedleads = $_POST['selectleads'];
  $emailaddylist = array();
  foreach ($collectedleads as $id) {

  $colname_rs_SelectedLeads = $id;

mysql_select_db($database_myBackOfficeConn, $myBackOfficeConn);
$query_rs_SelectedLeads = sprintf("SELECT * FROM Leads WHERE `Id` = %s", GetSQLValueString($colname_rs_SelectedLeads, "text"));
$rs_SelectedLeads = mysql_query($query_rs_SelectedLeads, $myBackOfficeConn) or die(mysql_error());
$row_rs_SelectedLeads = mysql_fetch_assoc($rs_SelectedLeads);
$totalRows_rs_SelectedLeads = mysql_num_rows($rs_SelectedLeads);

$emailaddylist[] = $row_rs_SelectedLeads['Email'];
$nameaddylist[] = $row_rs_SelectedLeads['FullName'];
  }
  /*Now you have an array of email addresses that correspond to 
    the ids you were sent via $_POST.
   */
  $emailaddystring = implode(", ", $emailaddylist);
  $nameaddystring = implode(", ", $nameaddylist);

  echo $emailaddystring . "</br>";
  echo $nameaddystring;

  $insertSQL = sprintf("INSERT INTO PendingEmails (to, NameTo, subject, message) VALUES ('%s', '%s', '%s', '%s')",
                       GetSQLValueString($emailaddystring, "text"),
                       GetSQLValueString($nameaddystring, "text"),
                       GetSQLValueString($_POST['subjectfield'], "text"),
                       GetSQLValueString($replaced, "text"));

  mysql_select_db($database_myBackOfficeConn, $myBackOfficeConn);
  $Result1 = mysql_query($insertSQL, $myBackOfficeConn) or die(mysql_error());

  /*$insertGoTo = "View Folder.php?Folder=" . $_POST['Folder'] . "";
  header(sprintf("Location: %s", $insertGoTo));*/

mysql_free_result($rs_SelectedLeads);

}

这是实际的形式:

<form action="<?php echo $editFormAction; ?>" method="POST" enctype="application/x-www-form-urlencoded" name="form" id="sendemailform">
          <fieldset>
          <div class="emailtablecontainer">
          <table width="525" border="0" cellspacing="10">
  <tr>
    <td><label>To:</label></td>
    <td><select data-placeholder="Select Lead(s) To Email..." multiple="true" class="chzn-container-multi" name="selectleads[]"style="width:505px;">
            <?php
do {  
?>
            <option value="<?php echo $row_rsAllLeads['Id']; ?>"><?php echo $row_rsAllLeads['FullName']?></option>
            <?php
} while ($row_rsAllLeads = mysql_fetch_assoc($rsAllLeads));
  $rows = mysql_num_rows($rsAllLeads);
  if($rows > 0) {
      mysql_data_seek($rsAllLeads, 0);
      $row_rsAllLeads = mysql_fetch_assoc($rsAllLeads);
  }
?>
          </select></td>
  </tr>
  <tr>
    <td><label>Subject:</label></td>
    <td><input class="inputs" name="subjectfield" type="text"></td>
  </tr>
  <tr>
    <td><label>Message:</label></td>
    <td><textarea id="sendemailtextarea" name="messagefield"></textarea></td>
    <script>
    CKEDITOR.replace( 'sendemailtextarea',
    {
        toolbar : 'SendEmailToolbar',
        uiColor: '#94B0C1',
        height : '62'
    });
    </script>
  </tr>
</table>
</div>
<input class="submitemailbuttonsprite submitemailbutton1" name="submitemail" type="submit" value="Send Email(s)">
          </fieldset>
          <input type="hidden" name="MM_insert" value="form">
          </form>

这是错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'to, NameTo, subject, message) VALUES (''Praesent.luctus.Curabitur@velturpis.edu,' at line 1

有什么建议吗?

【问题讨论】:

  • 请不要使用mysql_* 函数来编写新代码。它们不再维护,社区已经开始deprecation process。看到red box?相反,您应该了解prepared statements 并使用PDOMySQLi。如果你不能决定哪一个,this article 会帮助你。如果你选择 PDO,here is good tutorial。另见Why shouldn't I use mysql functions in PHP?
  • to 是一个关键词。反勾它(或改变它)。 dev.mysql.com/doc/refman/5.0/en/reserved-words.html
  • 报告的语法错误是由于使用了保留关键字TO。将其括在反引号中以用作列/表名称。
  • 我尝试回拨并得到了这个You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'daaghewi@gmail.com, eu.nibh@posuere.edu'', ''asdfqphgp, Jenette Smith'', ''asdf'' at line 1
  • 你到处都有报价。每个字符串的每一侧都需要一个。或使用准备好的语句。

标签: php mysql string insert mysqli


【解决方案1】:

您正在生成的 sql 中的单引号(')似乎太多了

(''Praesent.luctus.

【讨论】:

    【解决方案2】:

    您需要转义值之间的逗号:

    $string = 'string with commas\,string with more commas\,end of the string';
    
    $sql = "INSERT INTO table_name (row_name) VALUES (:string)";
    $q = $conn->prepare($sql);
    $q->execute(array(': row_name'=>$string);
    

    【讨论】:

    • 你不需要在字符串中转义逗号
    • 不是在字符串中,但他尝试插入一个逗号分隔的值,这可能会引发错误。请注意,他没有使用 PDO,这是一个建议
    • 不,字符串中的逗号不会引发错误。不在 PHP 中也不在 SQL 中。抱歉,这不是真的。
    • 你如何解释单引号和逗号作为 SQL 语句中的分隔符,如果使用不当会将语句分成几段?
    猜你喜欢
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 2014-05-12
    • 2014-12-18
    • 1970-01-01
    相关资源
    最近更新 更多