【问题标题】:Insert and replace data php sql插入和替换数据 php sql
【发布时间】:2015-03-02 16:33:59
【问题描述】:
TABLE1: table1ID | studentnum | lname | fname | mname
TABLE2: table2ID | studentnum | remarks | others

//THIS IS MY FORM 1
$sql = "INSERT INTO TABLE1 (studentnum, lname, fname, mname)
VALUES ('$studentnum','$lname','$fname','$mname')";

$sql1 = $sql = "INSERT INTO TABLE2 (studentnum)
VALUES ('$studentnum')";



mysql_select_db('databasename');
    $retval = mysql_query($sql);          
    if(!$retval ) {
    die('Could not enter data: ' . mysql_error());
    }
    $retval = mysql_query($sql1);          
    if(!$retval ) {
    die('Could not enter data: ' . mysql_error());
    }

echo "Data added successfully!";
    mysql_close($conn);  


SAMPLE OUTPUT:

TABLE1: 

table1ID | studentnum | lname | fname | mname
1        |    1001    |  My   |   An  | Swer


TABLE2: 

table2ID | studentnum | remarks | others
1        |    1001    |         |  

表 2 现在具有表 1 中的 studentnum 编码数据。 我想要这个输出,我怎样才能从 FORM 2 中做到这一点

//sample output with form1 and form2 values
table2ID | studentnum | remarks | others
1        |    1001    |   good  |  N/A

我有 2 个表格和 2 个表格,请参阅上面的代码。任何人都可以帮助我如何做到这一点?

【问题讨论】:

  • 警告:如果您只是学习 PHP,请不要学习过时的 mysql_query 接口。这很糟糕,并且在 PHP 的未来版本中被删除。像PDO is not hard to learn 这样的现代替代品。像PHP The Right Way 这样的指南可以帮助解释最佳实践。始终绝对确定您的用户参数是properly escaped,否则您将遇到严重的SQL injection bugs
  • 为什么要在 table2 插入数据之前将部分记录输入到 table2 中?这是没有意义的。准备好要填充的表单数据后,只需在表 2 中创建记录即可。如果您在运行脚本时同时拥有 table1 和 table 2 数据,您还可以跨连接插入以一次将记录添加到两个表中。

标签: php html mysql sql sql-server


【解决方案1】:

检查您从数据库中返回的值,当它们为空时,您可以使用 php empty() 函数将值替换为保留其位置(良好或 N/A)的值。
看到这个page

此外,如果您需要的所有信息不在 TABLE2 中,请考虑使用SQL join.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-24
    • 1970-01-01
    • 1970-01-01
    • 2017-02-14
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多