PHP技术求助:如何通过提交按钮传输入值调用函数创建数据库
Fixing Your Database Creation Workflow in PHP
Let's walk through your code issues and get your database creation feature working smoothly. Here are the key problems in your current setup, plus fully corrected code versions:
Key Issues in Your Current Code
- index.php: Your input field doesn’t have a
nameattribute—this means the server can’t access the value you type in. Also, the form’s action path might be incorrect depending on your file structure. - createDB.php:
- You call the
createDB()function without passing its required$pdoconnection and$nameparameters. - You used backticks
`for the SQL query (these are for shell commands, not SQL strings). - No database connection setup—you forgot to include your credential file (
secret.php). - No input sanitization, which leaves you open to SQL injection risks.
- No error handling to catch issues like duplicate database names.
- You call the
Corrected Code
1. Updated index.php
<?php require("secret.php"); require("getDatabases.php"); $conn = new PDO($servername, $username, $password); $databases = getDatabases($conn); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Custom Database Manager</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"/> </head> <body> <!-- List existing databases --> <div class="list-group mt-3"> <?php foreach($databases as $data): ?> <button type="button" class="list-group-item list-group-item-action"> <?= htmlspecialchars($data) ?> </button> <?php endforeach; ?> </div> <!-- Create new database form --> <form method="post" action="createDB.php" class="mt-4"> <!-- Added name attribute to let the server read the input value --> <input type="text" name="db_name" placeholder="Enter database name" required class="form-control mb-2"> <input type="submit" name="submit" value="Create my DB" class="btn btn-primary"> </form> </body> </html>
2. Updated createDB.php
<?php // Include credentials to connect to the database server require("secret.php"); function createDB($pdo, $name) { // Use backticks around the database name to handle special characters $sql = "CREATE DATABASE IF NOT EXISTS `$name`"; try { $pdo->exec($sql); // Redirect back to index to show the updated database list header("Location: index.php"); exit; } catch(PDOException $e) { die("Database creation failed: " . $e->getMessage()); } } // Check if form was submitted and a database name was provided if(isset($_POST['submit']) && !empty($_POST['db_name'])) { // Initialize PDO connection with error handling enabled $conn = new PDO($servername, $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Sanitize input to only allow valid database name characters $dbName = preg_replace('/[^a-zA-Z0-9_]/', '', $_POST['db_name']); // Call the function with the required parameters createDB($conn, $dbName); } else { die("Please enter a valid database name."); } ?>
What We Fixed
- Added
nameattribute: The input field now hasname="db_name"so we can retrieve its value via$_POST['db_name']. - Fixed function parameters: We now pass the PDO connection and sanitized database name to
createDB(). - SQL injection protection: We use a regex to strip invalid characters from the input, plus backticks around the database name for safety.
- Error handling: Added try/catch blocks to catch PDO errors and display clear messages.
- Connection setup: Included
secret.phpincreateDB.phpto establish a valid server connection. - Redirect on success: After creating the database, we send users back to
index.phpto see the updated list.
Ensure your secret.php has valid credentials in this format:
<?php $servername = "localhost"; $username = "your_db_username"; $password = "your_db_password"; ?>
内容的提问来源于stack exchange,提问作者nalmo
相关产品推荐
相关产品推荐

