dousi2029 2016-01-31 17:35
浏览 86
已采纳

INTRO-LVL编程器:在PHP / MySQL中验证和执行指导

I'm a non-CIS major taking an intro programming classes for a minor through my university. I've been able to successfully code most of the PHP files I need but have been getting hung up over how to perform two functions within the same document. Hopefully you can help.

Within the website, I want to be able to first use MySQL to check a table, called User (where a user is initially registered by the site) to verify that they are in fact registered and that the credentials they provided are correct, and then execute an query to add them to another table.

I've tried mysqli_multi_query to no avail and am just generally inexperienced and unsure of my options as far as functions go.

I have included the code below but be aware that it is a mess as I've attempted several different things before I decided to get some help

<?php
    session_start(); 
    require_once("config.php");

    $GroupDesc = $_GET["GroupDesc"]; 
    $LeaderID = $_GET["LeaderID"];
    $URL = $_GET["URL"];
    $Email=$_GET["Email"];

    $con = mysqli_connect("$SERVER","$USERID","$DBPASSWORD","$DATABASE");

    $query2= "INSERT INTO FA15_1052_tuf02984.WebsiteGroups (ID, Description, LeaderID, URL, LeaderEmail) VALUES ('$GroupDesc', '$LeaderID', '$URL', '$Email');";

    /* Here I want to perform the first query or $query1 which checks if the 
    user exists in MySQL and the info submitted in form is same */

    $query1= "SELECT * from USER where LeaderID = '$ID' and Email = '$Email';";
    if ($status = mysqli_query($con, $query1)) {
        } else {
            print "Some of the data you provided didn't match our records. Please contact the webmaster.".mysqli_error($con)." <br>"; 
            $_SESSION["RegState"]= -11;
            $_SESSION["ErrorMsg"]= "Database insertion failed due to inconsistent data: ".mysqli_error($con);
            header("Location:../index.php");
            die();
        }

    /* How do I tell the file to move onto the next query, which is $query2?

    if ($query2) {
      $query = "INSERT INTO FA15_1052_tuf02984.WebsiteGroups (ID, Description, LeaderID, URL, LeaderEmail)
      VALUES ('$GroupDesc', '$LeaderUID', '$URL', '$Email');";
    }       */

        } else { 
            print "Membership update failed. Please contact webmaster.".mysqli_error($con)." <br>"; 
            $_SESSION["RegState"]= -11; // 0: Not Registered, 1: Register, -1: Error 
            $_SESSION["ErrorMsg"]= "Database Insert failed: ".mysqli_error($con);
            header("Location:../index.php");
            die();
        }
  • 写回答

1条回答 默认 最新

  • dongou3286 2016-01-31 18:45
    关注

    There are a few points where your code can be rearranged to make the logic easier to follow. (Don't worry; this is just stuff that comes with experience.) I'll include some comments within the following code to explain what I've done.

    <?php
        session_start(); 
        require_once("config.php");
    
        $GroupDesc = $_GET["GroupDesc"]; 
        $LeaderID = $_GET["LeaderID"];
        $URL = $_GET["URL"];
        $Email=$_GET["Email"];
    
        // mysqli_connect is deprecated; the preferred syntax is
        $con = new mysqli("$SERVER","$USERID","$DBPASSWORD","$DATABASE");
    
        $query1= "SELECT * from USER where LeaderID = '$ID' and Email = '$Email';";
        $result = mysqli_query($con, $query1);
    
        // I personally prefer the following opening-brace style; I just find it
        //  easier to read. You can use the other style if you want; just do it 
        //  consistently.
        if ($result)
        {
            $row = mysqli_fetch_assoc($result);
            if($row)
            {
                if (($row['ID'] != $LeaderID) or ($row['Email'] != $Email))
                {
                    // Handle the error first, and exit immediately
                    print "Some of the data you provided didn't match our records. Please contact the webmaster.".mysqli_error($con)." <br>"; 
                    $_SESSION["RegState"]= -11;
                    $_SESSION["ErrorMsg"]= "Database Insert failed due to inconsistent data: ".mysqli_error($con);
                    header("Location:../index.php");
                    die();
                }
                else
                {
                    // If the query succeeded, fall through to the code that processes it
                    $query = "INSERT INTO FA15_1052_tuf02984.WebsiteGroups (ID, Description, LeaderID, URL, LeaderEmail)
                                 VALUES ('$GroupDesc', '$LeaderUID', '$URL', '$Email');";
    
                    $status = mysqli_query($con, $query);
    
                    if ($status)
                    { 
                        // membership has been updated  
                        $_SESSION["RegState"]=9.5; // 0: Not Registered, 1: Register, -1: Error 
                        $message="This is confirmation that you the group you lead has been added to our database.
                            Your group's ID in our database is "$GID". Please keep this in your records as you will need it to make changes.
                            If this was done in error, please contact the webmaster at tuf02984webmaster@website.com";
                        $headers = 'From: tuf02984webmaster@example.com'."
    ".
                            'Reply-To: tuf02984webmaster@example.com'. "
    ".
                             'X-Mailer: PHP/' . phpversion();
                        mail($Email, "You are a group leader!", $message, $headers);
                        header("Location:../index.php"); 
                        // die();
                        // You only use die() to return from an error state.
                        // Calling die() creates an entry in the server's error log file.
                        // For a successful completion, use
                        return;
                    }
                }
            }
        }
    
        // If we get here, then something has gone wrong which we haven't already handled
        print "Membership update failed. Please contact webmaster.".mysqli_error($con)." <br>"; 
        $_SESSION["RegState"]= -11; // 0: Not Registered, 1: Register, -1: Error 
        $_SESSION["ErrorMsg"]= "Database Insert failed: ".mysqli_error($con);
        header("Location:../index.php");
        die();
    
    ?>
    

    The basic idiom is: Do something, handle the specific error, handle success, do something else, etc., and finally handle any errors that can come from multiple points. If anything is unclear, just ask and I'll edit into my answer.

    I haven't covered prepared statements here. Prepared statements are the preferred way to perform non-trivial queries; they help to resist SQL injection attacks as well as simplify type-matching, quoting and escaping of special characters.

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

报告相同问题?

悬赏问题

  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出