Sunday, 8 October 2017

mysql - How to insert into MySQLusing a prepared statement with PHP





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
.


itemprop="text">
class="normal">Answer



File
sample.html



            action="sample.php" method="POST">
type="text">
value="Submit">




File
sample.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 href="http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html" rel="nofollow
noreferrer" title="Introduction to PHP PDO">PDO. Mysqli isn’t obsolete, but
PDO is much easier, IMHO.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...