What are some recommended approaches for creating a PHP script to prepare data for import into another MySQL table using form input fields?
When creating a PHP script to prepare data for import into another MySQL table using form input fields, it is recommended to first sanitize and validate the input data to prevent SQL injection and ensure data integrity. Next, you can use PHP variables to store the form input values and construct the SQL query to insert the data into the target MySQL table.
<?php
// Sanitize and validate form input data
$input_data = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Prepare data for import into MySQL table
$data1 = $mysqli->real_escape_string($input_data['field1']);
$data2 = $mysqli->real_escape_string($input_data['field2']);
$data3 = $mysqli->real_escape_string($input_data['field3']);
// Construct SQL query to insert data into target MySQL table
$sql = "INSERT INTO target_table (column1, column2, column3) VALUES ('$data1', '$data2', '$data3')";
// Execute SQL query
if ($mysqli->query($sql) === TRUE) {
echo "Data imported successfully";
} else {
echo "Error: " . $sql . "<br>" . $mysqli->error;
}
// Close MySQL connection
$mysqli->close();
?>
Keywords
Related Questions
- What are the potential pitfalls of setting default values in dropdown lists and radio buttons using PHP?
- How do you handle notices in your PHP scripts? Are they always caught or left as is?
- What are the recommended steps for establishing a database connection, selecting a database, and executing SQL statements in PHP?