Advertisement
Guest User

Untitled

a guest
Aug 4th, 2017
477
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. <?php
  2. $servername = "mysql.hostinger.com";
  3. $database = "u266072517_name";
  4. $username = "u266072517_user";
  5. $password = "buystuffpwd";
  6. $sql = "mysql:host=$servername;dbname=$database;";
  7. $dsn_Options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
  8.  
  9. // Create a new connection to the MySQL database using PDO, $my_Db_Connection is an object
  10. try {
  11. $my_Db_Connection = new PDO($sql, $username, $password, $dsn_Options);
  12. echo "Connected successfully";
  13. } catch (PDOException $error) {
  14. echo 'Connection error: ' . $error->getMessage();
  15. }
  16.  
  17. // Set the variables for the person we want to add to the database
  18. $first_Name = "Thom";
  19. $last_Name = "Vial";
  20. $email = "thom.v@some.com";
  21.  
  22. // Here we create a variable that calls the prepare() method of the database object
  23. // The SQL query you want to run is entered as the parameter, and placeholders are written like this :placeholder_name
  24. $my_Insert_Statement = $my_Db_Connection->prepare("INSERT INTO Students (name, lastname, email) VALUES (:first_name, :last_name, :email)");
  25.  
  26. // Now we tell the script which variable each placeholder actually refers to using the bindParam() method
  27. // First parameter is the placeholder in the statement above - the second parameter is a variable that it should refer to
  28. $my_Insert_Statement->bindParam(:first_name, $first_Name);
  29. $my_Insert_Statement->bindParam(:last_name, $last_Name);
  30. $my_Insert_Statement->bindParam(:email, $email);
  31.  
  32. // Execute the query using the data we just defined
  33. // The execute() method returns TRUE if it is successful and FALSE if it is not, allowing you to write your own messages here
  34. if ($my_Insert_Statement->execute()) {
  35. echo "New record created successfully";
  36. } else {
  37. echo "Unable to create record";
  38. }
  39.  
  40. // At this point you can change the data of the variables and execute again to add more data to the database
  41. $first_Name = "John";
  42. $last_Name = "Smith";
  43. $email = "john.smith@email.com";
  44. $my_Insert_Statement->execute();
  45.  
  46. // Execute again now that the variables have changed
  47. if ($my_Insert_Statement->execute()) {
  48. echo "New record created successfully";
  49. } else {
  50. echo "Unable to create record";
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement