$_REQUEST无法正常工作,插入MySQL数据为空的问题求助
Hey there, let's work through this problem step by step to get your form inserting the correct data into the database:
1. The Root Cause: Incorrect Form Data Retrieval
The main reason you're getting empty strings is a mistake in how you're fetching the input value in PHP. Your code has:
$product = $_REQUEST['$product'];
The key inside $_REQUEST needs to exactly match the name attribute of your input field (product), but you added a $ which turns it into a literal string. PHP can't find a form field named $product, so it returns an empty value. Fix this line to:
$product = $_REQUEST['product'];
(Pro tip: Since your form uses method="POST", using $_POST['product'] is more specific and slightly safer than $_REQUEST.)
2. Fix Invalid Form HTML
Your form tag has a redundant form attribute that's causing invalid markup:
<form action="insert1.php" form method="POST">
Remove the extra form keyword to clean it up:
<form action="insert1.php" method="POST"> <p><input type="text" name="product" /></p> <input type="submit" value="Add"> </form>
3. Critical: Patch SQL Injection Vulnerability
Your current code directly inserts user input into an SQL query, which is a massive security risk (it leaves you open to SQL injection attacks). Always use prepared statements with parameter binding to avoid this. Here's the revised, secure PHP code:
$mysqli = configuration(); // Only run the insert if the form was submitted via POST if ($_SERVER['REQUEST_METHOD'] === 'POST') { $product = $_POST['product']; // Prepare the SQL statement with a placeholder $stmt = $mysqli->prepare("INSERT INTO Odiet (product) VALUES (?)"); // Bind the input value to the placeholder (s = string type) $stmt->bind_param("s", $product); if ($stmt->execute()) { echo "ok"; } else { echo "not ok: " . $stmt->error; // Include error message for debugging } $stmt->close(); $mysqli->close(); }
After making these changes, your form should correctly insert the text you input into the database instead of empty strings.
内容的提问来源于stack exchange,提问作者layvin

