Building an array

I have a form for entering room information into a database. The information is Room Name, Room Width, Room Height, and Room Level. There are 12 sets of these fields for entering up to 12 rooms.

I am struggling to find a way to write each set as a record to the database. I am guessing that I create an array from the form information and then write each to the database but I am not sure how to do it. Any help would be greatly appreciated.

if you gave a field name like “width[1]”, you will get an array $_POST[‘width’] in your PHP script

Then there’s the problem of how to write the information to the database.
We do have some useful articles here about that.

For example: Build Your Own Database Driven Web Site Using PHP & MySQL

I don’t believe this helps me accomplish what I am trying to do.

My database has columns for RoomName, RoomWidth, RoomLength and RoomLevel. My form has fields for the same, repeated 12 times (to upload up to 12 different rooms).

I am thinking that I need to build a multi-dimensional array from the form data so that I can insert each row of data (RoomName, RoomWidth, RoomLength, RoomLevel) into the database, but I have no idea how to go about building the array from the data.

Any help is greatly appreciated.

Go backwards, build an array manually that posses the structure you require, then create your form to replicate this.


<?php
$rooms = array(
    1   => array(
        'name'      => '',
        'width'     => '',
        'length'    => '',
        'level'     => ''
    ),
    2   => array(
        'name'      => '',
        'width'     => '',
        'length'    => '',
        'level'     => ''
    ),
);
?>


<form>
    <input name="rooms[1][name]" />
    <input name="rooms[1][width]" />
    <input name="rooms[1][length]" />
    <input name="rooms[1][level]" />
    
    <input name="rooms[2][name]" />
    <input name="rooms[2][width]" />
    <input name="rooms[2][length]" />
    <input name="rooms[2][level]" />
    
    ......
    


<?php
foreach($_POST['rooms'] as $room){
    ....
}

Ok, thanks for the help with the array. Now I am trying to write those values to the database an individual rows, if anyone can help I would appreciate it. Thanks.

You need to iterate over the supplied ‘rooms’ and build an SQL query from the data supplied.

Barring validation, connection and insertion, you would be looking for something along the lines of…


$sql = 'INSERT INTO table (name, width, length, level)VALUES';

foreach($rooms as $room){
    $sql .= sprintf(
        "('&#37;s', '%s', '%s', '%s'),",
        mysql_real_escape_string($room['name']),
        mysql_real_escape_string($room['width']),
        mysql_real_escape_string($room['length']),
        mysql_real_escape_string($room['level'])
    );
}

$sql = rtrim($sql, ',');

This would build a suitable query.

That worked. Thanks, this was a great learning experience.