Development

PHP Making an easy way for MySQL inserts

A MySQL insert in PHP can be easily done however they can be long and tedious. Frustrating to essentially make a table and then repeat it again with an insert query in the code whilst ensuring your variables match up with the correct column.

An example table from here

CREATE TABLE IF NOT EXISTS test (
    task_id INT AUTO_INCREMENT,
    title VARCHAR(255) NOT NULL,
    start_date DATE,
    due_date DATE,
    status TINYINT NOT NULL,
    priority TINYINT NOT NULL,
    description TEXT,
    PRIMARY KEY (task_id)
)  ENGINE=INNODB;

There is only 7 columns in this table and one is an auto increment INT so I don’t need to insert into that column.

If I needed to do a MySQL insert with PHP

$MYSQL_insert = "INSERT INTO `test` (`title`, `start_date`, `due_date`, `status`, `priority`, `description`) VALUES ('$title', '$start', '$due', '$status', '$priority', '$desc')";

Thats easy and small but had I need to build an insert query on a table with 20 or more columns even with PHPStorm auto complete and MySQL sync it would be a brain-dead task.

A way to almost automatically compile this insert query can be done as follows:

Using MySQL show columns we can return every column in the table by specifying the Field had i need the type of column id use Type and so forth. Using this in PHP with loops to ensure the last column and variable don’t have a , I can echo out the statement:

 

$connect = mysqli_connect("127.0.0.1", "root", "", "dev");
$table = 'test';
$sql = "SHOW COLUMNS FROM $table";
$result = mysqli_query($connect, $sql);
echo '$MYSQL_insert = "INSERT INTO `' . $table . '` (';
while ($row1 = mysqli_fetch_assoc($result)) {
    $db_array[] = $row1;
}
$length = count($db_array);
$i = 0;
$result = mysqli_query($connect, $sql);
while ($row2 = mysqli_fetch_array($result)) {
    $col = $row2['Field'];
    if ($i == $length - 1) {
        echo "`$col`";
    } else {
        echo "`$col`, ";
    }
    $i++;
}
echo ') VALUES (';
$i = 0;
$result = mysqli_query($connect, $sql);
while ($row3 = mysqli_fetch_array($result)) {
    $col = $row3['Field'];
    if ($i == $length - 1) {
        echo "'$" . $col . "'";
    } else {
        echo "'$" . $col . "', ";
    }
    $i++;
}
echo ')";';

will echo out

$MYSQL_insert = "INSERT INTO `test` (`task_id`, `title`, `start_date`, `due_date`, `status`, `priority`, `description`) VALUES ('$task_id', '$title', '$start_date', '$due_date', '$status', '$priority', '$description')";

obviously i would remove parts I don’t need (task_id) and rename variables were needed, as variable renaming and unassigned detection is quick with PHPStorm.

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago