ATTENTION! You should really be using parameterized queries along with prepared statements, using either MySQLi or PDO! Otherwise, you're opening yourself up to SQL Injection (SQLI) attacks! Another good reason, is that you don't have to worry about escaping your input(s) anymore. The MySQLi/PDO implementation will handle this for you.
I will move forward with MySQLi in my example. Whichever you end up choosing is completely up to what you prefer at the end of the day.
<?php
// Error handling
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
/*!
* MySQLI Server Connection
* The DBHOST, DBUSEr, DBPASS, DBNAME,
* are define variables. Make your own.
!*/
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
// Language of the server
mysqli_query($conn, "SET character_set_results=utf8");
mb_language('uni');
mb_internal_encoding('UTF-8');
mysqli_query($conn, "set names 'utf8'");
// Function to check if connection is alive
function checkConnection($conn) {
if ($conn->ping()) {
printf ("Our connection is ok!\n");
} else {
printf ("Error: %s\n", $conn->error);
}
}
/*!
* Prevents the statement from auto commiting.
* For this particular use case, you can ignore it.
* You don't have to use it.
* However, in case you're going to work with multiple statements,
* parsing data over etc., I wanted to showcase it.
* It's one of the simple steps to try and negate incomplete datasets
* and loss.
!*/
$conn->autocommit(FALSE);
/*!
* table is your table name,
* column is the column name.
!*/
$sql = "INSERT INTO table SET column = ?";
$stmt = $conn->prepare($sql);
/*!
* the 's' argument here indicates that
* the insert variable is a string type.
* There are of course multiple types,
* and you can look them up.
* You chain them like so:
* $stmt->bind_param('iss', $value1, $value2, $value3);
* In the example above, we are expecting int, string, string.
* so $value1 is an int, $value2 is a string, $value3 is another string.
* The params are handled chronologically!
* Back to the actual example again:
* $value is is your post variable
* (i.e. the string you want to insert).
!*/
// bind the param(s), there's only one in this case.
$stmt->bind_param('s', $value);
// execute the query.
$stmt->execute();
// only include this if you set the auto commit to be false.
$conn->commit();
// closing the connection again.
$stmt->close();
$conn->close();
?>
Ideally, you'll split the database and connection setup into another file called maybe dbconnect.php and have the SQL logic be in a function, or handled in some other, separate logic, using include to include the datbase connection logic.