duanhui3759 2012-06-30 13:49
浏览 6

PHP没有将一些值插入MySQL数据库

I have an HTML form which submits values to the following PHP file, which inserts them into a MySQL database:

<?php
  $con = mysql_connect("*","*","*");
  if (!$con)
    {
    die('Could not connect: ' . mysql_error());
    }

  mysql_select_db("*", $con);

  $sql="INSERT INTO scores (hometeam, awayteam, result)
  VALUES
  ('" . mysql_real_escape_string($_POST['hometeam']) . "',
   '" . mysql_real_escape_string($_POST['awayteam']) . "',
   '" . mysql_real_escape_string($_POST['result']) . "')";

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

  mysql_close($con);
?>

Sometimes an input field in the HTML form will be left blank and in this case I do not want anything inserted into the database. I want the value to remain NULL. At the moment when I fill in my form like this:

Home team: Blue team
Away team: [blank]
Result: Won

The following is inserted into my database:

Home team: Blue team
Away team: ' '
Result: Won

What I want to be inserted/not inserted is:

Home team: Blue team
Away team: NULL
Result: Won

I've hunted hours for a solution. Can anyone help? Thank you.

  • 写回答

6条回答 默认 最新

  • dso0139 2012-06-30 14:02
    关注
    if (!empty($_POST['hometeam'])) {
      $sql="INSERT INTO scores (hometeam) VALUES ('" . $_POST['hometeam'] . "')";
    }
    

    Notice the single quotes around the 'hometeam' part. You should also clean that using mysql_real_escape_string($_POST['hometeam']).

    Bear in mind this will create upto 3 rows for each call, if you want to have a row like scores (hometeam, awayteam, result) you'll need to construct your query differently (i.e. a single query not 3 seperate ones).

    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c