user1788736
user1788736

Reputation: 2845

how to write values of an array to mysql table inside for each loop?

i have recived some data via post method i wrote the data to array now how i can write da data to mysql table ? sample of data recive is shown below. i keep getting this error:Error, query failed

if (isset($_POST['submit'])) {
    $data = [];
    foreach($_POST['checkbox'] as $rowNum) {
        $data[] = explode("::", $_POST['opt'][$rowNum]);
    }
    var_dump($data);

    $sku =$data[$rowNum][0];
    $description =$data[$rowNum][1];
    $location =$data[$rowNum][2];
    $quantitydate =$data[$rowNum][3];

    $link = mysqli_connect("somesite", "****", "*******", "******");
    // Check connection
    if($link === false){
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }

    $query ="SELECT * FROM Test WHERE sku = '$sku'";
    $testResult = mysqli_query($link, $query) or die('Error, query failed');    

    if(mysqli_fetch_array($testResult) == NULL){
        $sql = "INSERT INTO test (ID, sku, description, location, quantitydate) VALUES ('$ID','$sku', '$description','$location', '$quantitydate',NOW())";
        if(mysqli_query($link, $sql)){
            echo "Records added successfully.<br /><br />";
        } else{
            echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
        }

        // close connection
        mysqli_close($link);
    }else
        {
            echo "Record Already Exist<br /><br />";
        }
}

output sample:

// Output sample (selected row 2 and 4):
array (size=2)
  0 => 
    array (size=4)
      0 => string 'SKU2' (length=4)
      1 => string 'DESC2' (length=5)
      2 => string 'LOC2' (length=4)
      3 => string 'QUAN2' (length=5)
  1 => 
    array (size=4)
      0 => string 'SKU4' (length=4)
      1 => string 'DESC4' (length=5)
      2 => string 'LOC4' (length=4)
      3 => string 'QUAN4' (length=5)

Upvotes: 0

Views: 43

Answers (1)

Barmar
Barmar

Reputation: 782166

Use a prepared statement:

$stmt = mysqli_prepare($link, "INSERT IGNORE INTO tableName (sku, description, location, quantitydate) VALUES (?, ?, ?, ?)";
mysqli_stmt_bind_param($stmt, "ssss", $sku, $desc, $location, $quantitydate);
foreach ($_POST['checkbox' as $rowNum) {
    $row = explode('::', $_POST['opt'][$rowNum]);
    $sku = $row[0];
    $description = $row[1];
    $location = $row[2];
    $quantitydate = $row[3];
    mysqli_stmt_execute($stmt);
    if (mysqli_affected_rows($stmt) == 0) {
        echo "SKU $sku already exists <br/><br/>";
    }
}

If you have a unique index on the sku column, you don't need to perform the SELECT query first. INSERT IGNORE will simply ignore the attempt to add a duplicate row, and mysqli_affected_rows will return 0 to indicate that nothing was inserted.

Upvotes: 2

Related Questions