Last active
May 4, 2020 08:19
-
-
Save domantasg/58f84e1a0485a33b8bc0acd9b7b5180c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$servername = "mysql.hostinger.com"; | |
$database = "uXXXXXXXXXX_name"; | |
$username = "uXXXXXXXXXX_user"; | |
$password = "buystuffpwd"; | |
$sql = "mysql:host=$servername;dbname=$database;"; | |
$dsn_Options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]; | |
// Create a new connection to the MySQL database using PDO, $my_Db_Connection is an object | |
try { | |
$my_Db_Connection = new PDO($sql, $username, $password, $dsn_Options); | |
echo "Connected successfully"; | |
} catch (PDOException $error) { | |
echo 'Connection error: ' . $error->getMessage(); | |
} | |
// Set the variables for the person we want to add to the database | |
$first_Name = "Thom"; | |
$last_Name = "Vial"; | |
$email = "thom.v@some.com"; | |
// Here we create a variable that calls the prepare() method of the database object | |
// The SQL query you want to run is entered as the parameter, and placeholders are written like this :placeholder_name | |
$my_Insert_Statement = $my_Db_Connection->prepare("INSERT INTO Students (name, lastname, email) VALUES (:first_name, :last_name, :email)"); | |
// Now we tell the script which variable each placeholder actually refers to using the bindParam() method | |
// First parameter is the placeholder in the statement above - the second parameter is a variable that it should refer to | |
$my_Insert_Statement->bindParam(:first_name, $first_Name); | |
$my_Insert_Statement->bindParam(:last_name, $last_Name); | |
$my_Insert_Statement->bindParam(:email, $email); | |
// Execute the query using the data we just defined | |
// The execute() method returns TRUE if it is successful and FALSE if it is not, allowing you to write your own messages here | |
if ($my_Insert_Statement->execute()) { | |
echo "New record created successfully"; | |
} else { | |
echo "Unable to create record"; | |
} | |
// At this point you can change the data of the variables and execute again to add more data to the database | |
$first_Name = "John"; | |
$last_Name = "Smith"; | |
$email = "john.smith@email.com"; | |
$my_Insert_Statement->execute(); | |
// Execute again now that the variables have changed | |
if ($my_Insert_Statement->execute()) { | |
echo "New record created successfully"; | |
} else { | |
echo "Unable to create record"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I believe the bindparam section (shown here and here) should be:
Without the quotes, the example was giving error:
More info here.