dongningce9075 2012-04-10 18:51
浏览 14
已采纳

使用PHP插入MySQL DB时排除空记录

I have a page that contains the allows a user to enter up to 10 records in a database. The problem I'm having is that in many (most) cases, the user will only enter one or two records in, but the database insert is processing all of the blank records and inserting them as well. I've configured the DB to not accept NULL values, but I suspect the blank values are not quite equivalent to NULL and that's why the records are still being inserted. How can I code this so that blank records are not inserted into the database.

Current Insert Code:

    <?php
if (isset($_POST['submit'])) {  

for($i = 0; $i < 10; $i++)
{

$indtypeid = $_POST['indtype'][$i];
$indicator = $_POST['indicator'][$i];
$actorid = $_POST['actor'][$i];
$reportid = $_POST['report'][$i];

print 'Row ' . $i . ': '  . $indtypeid . '-' . $indicator . '-' . $actorid . '<br/>';

$qry_digestreport = "INSERT INTO indicator (indtypeid,indicator,actorid,reportid) VALUES ('$indtypeid', '$indicator', '$actorid', '$reportid')";


if (!mysql_query($qry_digestreport,$connection))
  {
  die('Error: ' . mysql_error());
  }
echo "<br/>Records added!<br/>";
  • 写回答

1条回答 默认 最新

  • douxin2003 2012-04-10 18:53
    关注

    A simple if() check would do:

    if (empty($indtypeid) || empty($indicator) || ....) {
       continue; // jump to next loop iteration
    }
    

    right after your $_POST assignments.

    Note that your code is utterly vulnerable to SQL injection attacks, so you might want to read a bit about that on http://bobby-tables.com

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥15 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题