how to insert data in multi dimension array into mysql database in php.

Dani AI

Generated

The posted snippet has several common problems that prevent rows from being inserted and make the code unsafe: the form values are treated as scalars (so the multidimensional array ends up with duplicate entries), the SQL uses incorrect quoting for identifiers, array keys are used without quotes, the query is never executed, and no parameterization or error handling is present. and correctly asked for the incoming array shape, and was right to push for prepared statements — the example below follows that advice and shows a safe, practical pattern.

<?php
// PDO connection (set DSN/credentials appropriately)
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'dbuser', 'dbpass', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);

// Expect form fields named txtnum[], txtname[], txtage[]
$nums  = $_POST['txtnum']  ?? [];
$names = $_POST['txtname'] ?? [];
$ages  = $_POST['txtage']  ?? [];

try {
    $pdo->beginTransaction();
    $stmt = $pdo->prepare(
        "INSERT INTO `students` (`student_number`, `name`, `age`) VALUES (:num, :name, :age)"
    );

    $rows = min(count($nums), count($names), count($ages));
    for ($i = 0; $i < $rows; $i++) {
        $num  = trim($nums[$i]);
        $name = trim($names[$i]);
        $age  = trim($ages[$i]);

        if ($num === '' && $name === '' && $age === '') {
            continue; // skip empty row
        }

        $stmt->execute([':num' => $num, ':name' => $name, ':age' => $age]);
    }
    $pdo->commit();
} catch (PDOException $e) {
    $pdo->rollBack();
    // log $e->getMessage() — don't echo raw errors to users
}

Notes and troubleshooting: HTML inputs intended as multiple rows must be named with square brackets (e.g. name="txtnum[]") so PHP receives arrays. Use backticks (or plain identifiers) for column names rather than single quotes. Avoid using table/column names from untrusted input (placeholders cannot bind identifiers). Wrap multi-row inserts in a transaction and catch exceptions to rollback on failure. Prefer PDO or mysqli with prepared statements — the old mysql_* functions are deprecated/removed in modern PHP. Finally, access associative array keys with quoted strings (for example $row['name']) to avoid PHP notices.

Recommended Answers

All 4 Replies

Can you show what you have, and how you want it inserted?

It would help if we could take a look at the array.

this is what I have done so far.I'm little bit new to this suff.please help...

    <?php

       require 'connection1.php';

     if(isset($_POST['btnsub'])){

        $num=$_POST['txtnum'];
        $name=$_POST['txtname'];
        $age=$_POST['txtage'];

        $stu=array(

            0=>array('number'=>$num,'name'=>$name,'age'=>$age),
            1=>array('number'=>$num,'name'=>$name,'age'=>$age),
            2=>array('number'=>$num,'name'=>$name,'age'=>$age),
        );

        foreach( $stu as $key =>$info){

            $in="INSERT INTO $tbl ('number','name','age') VALUES ('$key','$info[number]','$info[name]','$info[age]')";

        }

     }



    ?>
Member Avatar for Member #120589

THat won't work - as you probably know. WHy are you using a repeat of the data into a multidimensional array? THe loop won't work as you expect either. If you have a Primary Key field, just ignore this in the SQL - so no need for a $key - anyway you have different number of fields and values, so it'll throw an error. Also you need to sanitize your input (post) variables before using this type of query. If you use a bound, parameterized query (mysqli or PDO), then it's OK.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.