简体   繁体   中英

sql query only putting in one record not multiple?

Hi I'm just trying to do this php/sql query, I'm attempting to enter more than one record at a time using this code but it's only entering one, not the others...

CODE:

    <?php
        $results=$_POST['results'];
        $day=$_POST['day'];
        $lmID=$_POST['lmID'];
        $cID=$_POST['cID'];
        $count_cID = count($_POST['cID']);

        for($i=0;$i<$count_cID ;$i++){
        $_results = mysql_escape_string($results[$i]);
        $_day = mysql_escape_string($day[$i]);
        $_lmID = mysql_escape_string($lmID[$i]);
        $_cID = mysql_escape_string($cID[$i]);

        $sql = mysql_query("INSERT INTO Club (results, day, lmID, cID) VALUES ('$_results', '$_day', '$_lmID', '$_cID')");
        $result = mysql_query($sql);
    }

    ?>

HTML FORM:

            League Match ID:
            <?php echo $lmID;?> <input type="hidden" name="lmID[]" value="<?php echo $lmID; ?>" >
            Competitor ID:
            <?php echo $cID;?> <input type="hidden" name="cID[]" value="<?php echo $cID; ?>" >
            Result:
            <input type="text" name="results[]">
            Day:
            <input type="text" name="day[]">

            <input type="submit" name="submit">
        </form>
$sql = mysql_query("INSERT INTO Club (results, day, lmID, cID) VALUES ('$_results', '$_day', '$_lmID', '$_cID')");
$result = mysql_query($sql);

Should be:

$sql = <<<EOF
INSERT INTO Club (results, day, lmID, cID) 
VALUES ('{$_results}', '{$_day}', '{$_lmID}', '{$_cID}')
EOF;
$result = mysql_query($sql);

As mentioned in other comments, please do not use mysql_ database functions - use PDO or mysqli_ functions. mysql_query is deprecated (for good reason). With the other libraries, it seems your statement would also be a candidate for PREPARE followed by EXECUTE. eg using PDO....

$sql = <<<EOF
INSERT INTO Club (results, day, lmID, cID) 
VALUES (?, ?, ?, ?)
EOF;
$stmt = $db->prepare( $sql);

for($i=0;$i<$count_cID ;$i++){
    // escape your data here - you might not need to with PDO
    $result = $stmt->execute( array( $_results, $day, $_lmID, $_cID));
}

Make sure $count_cID is more than 1 (one). Which it is not, looks like. The reason I'm referring to this variable is you are comparing $i to it, and in your for loop, if it's not greater than 1, then the loop contents will be executed once only, as on the second try the condition will not validate anymore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM