【问题标题】:Confirm if it was inserted into MySql database确认是否插入MySql数据库
【发布时间】:2013-05-24 02:14:57
【问题描述】:

我在 PhP 中有一个注册表单,将各种条目提交到 MySQL 数据库中。

代码如下:

if($conn)
    {

    $sql = "INSERT INTO Participants
       (ID,
        title, 
        surname,
        name,
        organization1,
        organization2,
        address1,
        address2,
        country,
        email,
        phone,
        type_reg,
        abstract,
        bm1,
        bm2,
        bm3,
        bm4                 )

        VALUES         
       ('$auth_id',
        '$auth_title', 
        '$auth_sname',
        '$auth_name',
        '$auth_org_line1',
        '$auth_org_line2',
        '$auth_add_line1',
        '$auth_add_line2',
        '$auth_country',
        '$auth_email',
        '$auth_phonen',
        '$reg_type',
        '$new_file_name',
        '$bm1',
        '$bm2',
        '$bm3',
        '$bm4'          )";


    mysql_query($sql);
    if( mysql_errno() !== 1062) {
        print '<script type="text/javascript">'; 
        print 'alert("Your pre-registration has been submitted successfully. You will receive a confirmation e-mail soon.")';
        print '</script>';
        print '<script type="text/javascript">'; 
        print 'parent.location.href = "Success.html"';
        print '</script>';
mysql_close($conn);
    }
    else
    {
    echo 'Data base error. Try later.';
    }

因为我正在向我发送带有 cc 的确认电子邮件,所以我知道注册的人,当我检查数据库时,我发现其中一些人没有被插入到数据库中。

我正在寻找一种仅在条目被插入 MySQL 表时才验证注册的方法。

有简单的方法吗?

我是否应该验证查询是否成功?怎么样?

我是否应该在桌子上查找 ID 并验证它是否存在?如何? (入口ID设置为唯一)

【问题讨论】:

  • MySQL_Query 函数已弃用,您应该改用 PDO

标签: php mysql forms


【解决方案1】:

是的。 mysql_affected_rows() 将返回受您的查询影响的行数。如果为零,则不插入。如果 >= 1,那就是。

所以:

if ( mysql_affected_rows() &gt;= 1 ){ /* inserted! now do something... */ }

如果您使用自动递增列作为行 ID,您也可以使用 mysql_insert_id()

if ( mysql_insert_id() &gt; 0 ) { /* inserted! now do something... */ }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-02
    • 2014-07-09
    相关资源
    最近更新 更多