PHP

I think I don’t need to write code anymore!

chatGPT

The first time, a week ago, I heard about the chatgpt from New York Times’s technology podcast. I haven’t got a chance to test it. Today I just asked chatgpt to write PHP code for an inventory system.

chatGPT wrote the code for less than thirty seconds, explained it, and show me the use cases.

Here is the code:

<?php

// Connect to the database
$host = "localhost";
$username = "username";
$password = "password";
$dbname = "inventory";

$conn = mysqli_connect($host, $username, $password, $dbname);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// Function to add a product to the inventory
function addProduct($conn, $name, $quantity, $price) {
    $sql = "INSERT INTO products (name, quantity, price)
            VALUES ('$name', '$quantity', '$price')";
    if (mysqli_query($conn, $sql)) {
        return true;
    } else {
        return false;
    }
}

// Function to update the quantity of a product in the inventory
function updateQuantity($conn, $name, $quantity) {
    $sql = "UPDATE products SET quantity = '$quantity' WHERE name = '$name'";
    if (mysqli_query($conn, $sql)) {
        return true;
    } else {
        return false;
    }
}

// Function to check if a product is in stock
function checkInStock($conn, $name) {
    $sql = "SELECT quantity FROM products WHERE name = '$name'";
    $result = mysqli_query($conn, $sql);
    if (mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        if ($row['quantity'] > 0) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

// Example usage:

// Add a new product to the inventory
if (addProduct($conn, "Product 1", 10, 20)) {
    echo "Product added successfully";
} else {
    echo "Error adding product";
}

// Update the quantity of a product in the inventory
if (updateQuantity($conn, "Product 1", 5)) {
    echo "Quantity updated successfully";
} else {
    echo "Error updating quantity";
}

// Check if a product is in stock
if (checkInStock($conn, "Product 1")) {
    echo "Product is in stock";
} else {
    echo "Product is out of stock";
}

mysqli_close($conn);

chatGPT’s explanation:

This code defines several functions for adding, updating, and checking the quantity of products in the inventory. It uses a MySQL database to store the product information, and connects to the database using the MySQLi extension in PHP.

The addProduct function takes three arguments: the connection to the database, the name of the product, the quantity of the product, and the price of the product. It then inserts a new row into the products table with this information.

The updateQuantity function takes three arguments: the connection to the database, the name of the product, and the new quantity. It updates the quantity column of the row with the matching name in the products table.

The checkInStock function takes two arguments: