how to add php data into mysql database?

  • Thread starter Thread starter vasiangv
  • Start date Start date
V

vasiangv

Guest
i'm trying to do a dynamic website but im utterly confused. for now, i'm trying to do an email subscription. i am able to have text boxes for users to enter name and email... and php is able to echo 'hi $name, thanks for subscribing.". but how can this info (name and email) be added into the SQL database automatically? what code should i put? will appreciate any help..thanks!!!
 
The beginners way is this:
===================
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("INSERT INTO Persons (namefield, emailfield) VALUES ($name, $email)");
===================
A better way, which will prevent SQL injection attacks (see the last link in my sources for a funny explaination of what SQL injection attacks are) is this:
===================
try {
$dbh = new PDO("mysql:host='localhost';dbname=mydatabase", 'username', 'password');
$count = $dbh->exec("INSERT INTO Persons (namefield, emailfield) VALUES ($name, $email)");
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
===================
 
Back
Top