drfkl66684 2012-09-03 15:51
浏览 31
已采纳

如何在mysql insert语句中放入PHP'not null'条件?

I have a page with two forms on it (and two submit buttons), and the forms link the page back to itself with action="" for the INSERT INTO statements. One of the INSERT INTO statements is:

<?php
$sql="INSERT INTO panelProduct (length_mm, width_mm, aperture)

VALUES ('$_POST[p_length_mm]','$_POST[p_width_mm]','$_POST[p_aperture]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";
?>

One of the reasons I have put the form and the INSERT statements on the same page is that the form allows users to add products to an order, and there may be several products (so I thought the user could keep submitting until they're done...). The other reason was that I need to use a $_POST value sent from the previous page to do something else with the products they enter, and I don't know how to send it to more than one page.

Anyway, the problem I have found is that a new row is inserted into the database every time the page is refreshed, containing NULL values. This makes sense to me as the PHP will execute the statement above every time it encounters it. My question therefore is how I can make some sort of condition that will only execute the INSERT statement if the user enters something in the form and 'Submits'?

  • 写回答

3条回答 默认 最新

  • doulun1666 2012-09-03 16:02
    关注

    you could use the empty() method of PHP to check for null values in each of the variables.

    Something like:

    if(!empty($_POST['p_length_mm']) && !empty($_POST['p_width_mm']) && !empty($_POST['p_aperture']))
    {
    //execute your query here
    }
    else
    {
    //if there's an alternative you would like to happen if values are null, or just leave out.
    }
    

    Hope that does the trick.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'