var_dump()输出字符串(0)“”,这是为什么?

时间:2012-12-11 18:04:22

标签: php mysqli

下面是一个php / mysqli代码,它假设将courseid和模块id插入数据库,然后执行查询以选择课程详细信息以查找插入课程的课程详细信息然后最终运行最终查询以确保插入的courseid和moduleid在数据库中。

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
     // connect to the database
     include('connect.php');

      /* check connection */
      if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        die();
      }

    $courseid = (isset($_POST['courses'])) ? $_POST['courses'] : ''; 
    $moduleid = (isset($_POST['moduleid'])) ? $_POST['moduleid'] : '';  
    $moduleno = (isset($_POST['moduleno'])) ? $_POST['moduleno'] : '';  
    $modulename = (isset($_POST['modulename'])) ? $_POST['modulename'] : '';    

    var_dump($courseid);

    $insertsql = "
    INSERT INTO Course_Module
    (CourseId, ModuleId)
    VALUES
    (?, ?)
    ";
    if (!$insert = $mysqli->prepare($insertsql)) {
    // Handle errors with prepare operation here
    }                                           

    $insert->bind_param("ii", $courseid, $moduleid);

    $insert->execute();

    if ($insert->errno) {
    // Handle query error here
    }

    $insert->close();

    $coursequery = "
    SELECT DISTINCT CourseNo, CourseName 
    FROM Course c 
    INNER JOIN Course_Module cm 
    ON
    c.CourseId = cm.CourseId
    WHERE cm.CourseId = ?";
    // prepare query
    $coursestmt=$mysqli->prepare($coursequery);
    // You only need to call bind_param once
    $coursestmt->bind_param("i", $courseid);
    // execute query
    $coursestmt->execute(); 
    // get result and assign variables (prefix with db)
    $coursestmt->bind_result($dbCourseNo, $dbCourseName);

    $query = "SELECT CourseId, ModuleId FROM Course_Module WHERE CourseId = ? AND ModuleId = ?";
    // prepare query
    $stmt=$mysqli->prepare($query); //line 58 error
    // You only need to call bind_param once
    $stmt->bind_param("ii", $courseid, $moduleid); //line 60 error
    // execute query
    $stmt->execute(); 
    // get result and assign variables (prefix with db)
    $stmt->bind_result($dbCourseId, $dbModuleId);
    //get number of rows
    $stmt->store_result();
    $numrows = $stmt->num_rows();

    if ($numrows == 1){

    echo "<span style='color: green'>The following Module has been added into Course:" . $dbCourseNo . " - " . $dbCourseName . ":<br/>" . $moduleno . " - " . $modulename . "</span>";

    }else{

    echo "<span style='color: red'>An error has occured, Module has not been added into the Course</span>";

    }

            ?>

好的,上面的代码我得到的问题是它不会在CourseId和ModuleId字段中执行插入。它只是为两个字段插入值0。我的问题是为什么这样做:

以下是两种形式:

$addmodule = "
<form id='detailsForm'>

    <p><strong>Module Details</strong></p>
    <table>
    <tr>
    <th></th>
    <td><input type='hidden' id='idmodule' name='moduleid' value='' /> </td>
    </tr>
    <tr>
    <th>Module ID:</th>
    <td><input type='text' id='nomodule' name='moduleno' readonly='readonly' value='' /> </td>
    </tr>
    <tr>
    <th>Module Name:</th>
    <td><input type='text' id='namemodule' name='modulename' readonly='readonly' value='' /> </td>
    </tr>
    </table>

    </form>
";

$moduleForm = "
<form action='".htmlentities($_SERVER['PHP_SELF'])."' method='post' id='moduleForm'>
{$outputcourse}
{$hiddencourse}
<p><strong>Add Module</strong></p>
<p><strong>Module:</strong> {$moduleHTML} </p>   
</form>";

以下是使用ajax导航到UPDATE正上方的php代码以执行插入数据库的代码:

    function submitform() {    

    $.ajax({
        type: "POST",
        url: "insertmoduletocourse.php",
        data: { detailsForm: $('#detailsForm').serialize(), moduleForm : $('#moduleForm').serialize() },
        success: function(html){
            $("#targetdiv").html(html);
            $('#targetdiv').show();

        }
     });        
}

当我执行var_dump($courseid) and var_dump($moduleid)时,会输出:string(0) "" string(0) ""

以下是在各自的下拉菜单中显示课程和模块的代码:

$courseactive = 1;

    $sql = "SELECT CourseId, CourseNo, CourseName FROM Course WHERE CourseActive = ? ORDER BY CourseNo"; 

    $sqlstmt=$mysqli->prepare($sql);

    $sqlstmt->bind_param("i",$courseactive);

    $sqlstmt->execute(); 

    $sqlstmt->bind_result($dbCourseId, $dbCourseNo, $dbCourseName);

    $courses = array(); // easier if you don't use generic names for data 

    $courseHTML = "";  
    $courseHTML .= '<select name="courses" id="coursesDrop">'.PHP_EOL; 
    $courseHTML .= '<option value="">Please Select</option>'.PHP_EOL;  

    $outputcourse = ""; 
    $hiddencourse = ""; 

    while($sqlstmt->fetch()) 
    { 
    $course = $dbCourseId;
    $courseno = $dbCourseNo;
    $coursename = $dbCourseName; 
    $courseHTML .= "<option value='".$course."'>" . $courseno . " - " . $coursename . "</option>".PHP_EOL;  

    if (isset($_POST['courses']) && ($_POST['courses'] == $course)) {
    $outputcourse .= "<p><strong>Course:</strong> " . $courseno .  " - "  . $coursename . "</p>";
    $hiddencourse .= "<p><input type='hidden' id='hiddencourse' value='". $courseno . " - " . $coursename ."'></p>";
}

    } 

    $courseHTML .= '</select>';  

    $moduleInfo = array();


    //get the form data 
$coursesdrop = (isset($_POST['courses'])) ? $_POST['courses'] : ''; 
$moduleactive = 1;  

$modulequery = "
SELECT
m.ModuleId, m.ModuleNo, m.ModuleName, m.Credits
FROM
Module m
WHERE
m.ModuleId NOT IN (
SELECT cm.ModuleId
FROM Course_Module cm
WHERE cm.CourseId = ?
) AND m.ModuleActive = ?
ORDER BY m.ModuleNo
";

$moduleqrystmt=$mysqli->prepare($modulequery);
// You only need to call bind_param once
$moduleqrystmt->bind_param("ii",$coursesdrop, $moduleactive);
// get result and assign variables (prefix with db)

$moduleqrystmt->execute(); 

$moduleqrystmt->bind_result($dbModuleId,$dbModuleNo,$dbModuleName,$dbCredits);

$moduleqrystmt->store_result();

$modulenum = $moduleqrystmt->num_rows();     

$moduleHTML = '<select name="module" id="modulesDrop">'.PHP_EOL;
$moduleHTML .= '<option value="">Please Select</option>'.PHP_EOL;           

while ( $moduleqrystmt->fetch() ) {

$moduleHTML .= sprintf("<option value='%s'>%s - %s</option>", $dbModuleId, $dbModuleNo, $dbModuleName) . PHP_EOL;   

$moduleData = array();
$moduleData["ModuleId"] = $dbModuleId;
$moduleData["ModuleNo"] = $dbModuleNo;
$moduleData["ModuleName"] = $dbModuleName;
$moduleData["Credits"] = $dbCredits;

array_push($moduleInfo, $moduleData);

}


$moduleHTML .= '</select>';

- 更新:

下面的Ajax / jquery:

 function submitform() {    

        $.ajax({
            type: "POST",
            url: "insertmoduletocourse.php",
            data: { 
        courses:    $('#coursesDrop').val(),
        moduleid:   $('#idmodule').val(),
        moduleno:   $('#nomodule').val(),
        modulename: $('#namemodule').val()
    },
            success: function(html){
                $("#targetdiv").html(html);
                $('#targetdiv').show();

                var selectedOption = jQuery("#modulesDrop option:selected");
                selectedOption.appendTo($("#moduleselect"));

                    //Clear fields
                    jQuery("#idmodule").val("");
                    jQuery("#nomodule").val("");
                    jQuery("#namemodule").val("");
                    jQuery("#credits").val("");
            }
         });        
    }

以下是$ courseHTML echo:

<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" onsubmit="return validation();">
<table>
<tr>
<th>Course: <?php echo $courseHTML; ?></th>
</tr>
</table>
<p><input id="courseSubmit" type="submit" value="Submit Course" name="courseSubmit" /></p>
<div id="courseAlert"></div>
<div id="targetdiv"></div>
</form>

1 个答案:

答案 0 :(得分:1)

代替var_dump($courseid);print_r($_POST);并检查那里 1-如果您有课程的值,例如[courses] => 'theCoursesValue' 2-它不是在其他数组(键)下“缩进”

// this is a print_r($_POST) plus my comments
Array
(
    [courses] => theCoursesValue                // access this value by $_POST['courses']
                                                // in your case may be empty or inexistent
    [otherkey] => otherValue
    [indented] => Array
        (
            [internalKey] => internalValue
            [courses] => thisOneIsNotDirect     // access this value by $_POST['indented']['courses']
        )

)

<强>更新
你可以这样做:

$.ajax({
    type: "POST",
    url: "insertmoduletocourse.php",
    data: { 
        // an html field must exist for each one of this, with matching id='...blabla...'
        // may be textbox(text), textarea, hidden.
        // be sure that they were generated using "view source code" on the browser
        // again use print_r($_POST) to check
        courses:    $('#coursesDrop option:selected').val(),   // for selects
        moduleid:   $('#moduleid').val(),
        moduleno:   $('#moduleno').val(),
        modulename: $('#modulename').val()
    },
    success: function(html){
        $("#targetdiv").html(html);
        $('#targetdiv').show();
    }
 });