I am just learning about databases and I want to be able to store user inputs. What would be a basic example on how to get form data and save it to a database using PHP?
Also making the form secure from SQL attacks.
You must always use prepared statements for any SQL query that would contain a PHP variable. To do so, always follow the below steps: Create a correct SQL SELECT statement. Test it in mysql console/phpmyadmin if needed.
Do I still need to used mysqli_real_escape_string when used prepared statements in PHP? The simple answer is no. The way it used to work is that you would take form input data, put that into a variable, and inject that data into your MySQL query in order to add that data to the database.
In order to use MySQL prepared statement, you use three following statements: PREPARE – prepare a statement for execution. EXECUTE – execute a prepared statement prepared by the PREPARE statement. DEALLOCATE PREPARE – release a prepared statement.
Definition and Usage The fetch_row() / mysqli_fetch_row() function fetches one row from a result-set and returns it as an enumerated array.
<form action="sample.php" method="POST"> <input name="sample" type="text"> <input name="submit" type="submit" value="Submit"> </form>
<?php if (isset($_POST['submit'])) { $mysqli = new mysqli('localhost', 'user', 'password', 'mysampledb'); /* Check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $stmt = $mysqli->prepare("INSERT INTO SampleTable VALUES (?)"); $stmt->bind_param('s', $sample); // Bind $sample to the parameter $sample = isset($_POST['sample']) ? $_POST['sample'] : ''; /* Execute prepared statement */ $stmt->execute(); printf("%d Row inserted.\n", $stmt->affected_rows); /* Close statement and connection */ $stmt->close(); /* Close connection */ $mysqli->close(); } ?>
This is a very basic example. Many PHP developers today are turning to PDO. Mysqli isn’t obsolete, but PDO is much easier, IMHO.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With