diff --git a/functions/mysql-php/README.md b/functions/mysql-php/README.md new file mode 100644 index 0000000..341113a --- /dev/null +++ b/functions/mysql-php/README.md @@ -0,0 +1,26 @@ +# MySQL RDB and PHP functions + +A small example of a PHP function that creates a table in a MySQL database and inserts a row into it. + +## Deploying + +1. Create a MySQL database from the Scaleway console. + 1. Make sure to create a user as well. +2. Create a new function namespace and a PHP function running using PHP 8.2 +3. Copy the contents of `handler.php` into the function code editor. +4. Add the following environment variables to the function: + - `MYSQL_HOST`: The hostname of the MySQL database + - `MYSQL_USER`: The username of the MySQL user + - `MYSQL_PASSWORD`: The password of the MySQL user + - `MYSQL_DB`: The name of the MySQL database +5. Deploy the function. +6. Grab the function URL and use it to call the function. + +## Usage + +Call the function with a body to insert a row into the table. + +```console +curl -X POST -d '{"email": "hello@acme.org"}' +Inserted hello@acme.org into the database +``` diff --git a/functions/mysql-php/handler.php b/functions/mysql-php/handler.php new file mode 100644 index 0000000..d8115c9 --- /dev/null +++ b/functions/mysql-php/handler.php @@ -0,0 +1,76 @@ +query($createTableSql) === FALSE) { + die("Error creating table: " . $mysqli->error); + } + + // Prepare SQL statement + $stmt = $mysqli->prepare("INSERT INTO $tableName (email, reg_date) VALUES (?, NOW())"); + if ($stmt === false) { + die("Error preparing statement: " . $mysqli->error); + } + + // Bind parameters + $stmt->bind_param("s", $data['email']); + + // Execute statement + if ($stmt->execute() === false) { + die("Error executing statement: " . $stmt->error); + } + + echo "Record inserted successfully"; + $stmt->close(); +} + +function handle($event, $context) { + $dbHost = getenv('MYSQL_HOST'); + $dbUsername = getenv('MYSQL_USER'); + $dbPassword = getenv('MYSQL_PASSWORD'); + $dbName = getenv('MYSQL_DB'); + + $mysqli = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); + $tableName = "users"; + + if ($mysqli === null) { + die("Database connection is not established."); + } + + if ($mysqli->connect_error) { + die("Connection failed: " . $mysqli->connect_error); + } + + // Extract user data from the request + $data = json_decode($event['body'], true); + if ($data === null || $data['email'] === null) { + return [ + "body" => "Email is required", + "statusCode" => 400, + ]; + } + + try { + insertRecord($mysqli, $tableName, $data); + } catch (Exception $e) { + return [ + "body" => "Error: " . $e->getMessage(), + "statusCode" => 500, + ]; + } + + return [ + "body" => "Inserted " . $data['email'] . " into the database", + "statusCode" => 200, + ]; +}