I am using the w3schools.com tutorial for PHP mysqli to learn how to use PHP to send information between a database and server. However the tutorial does not go into much depth in what the code is actually doing. I am unsure as to why it seems that I need to run a conditional 'if' statement to actually send the query.
I took the code below from the website and played around with commenting out code to try to figure out myself how it behaved and noticed that I got an error if I just had $conn->query($sql) instead of the if else statements that contained it.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
I received this error:
Parse error: syntax error, unexpected '$conn' (T_VARIABLE)
Clearly I am not grasping something basic about how these database connections work. Is it possible to send queries without a conditional statement? Also can somebody please explain the little details about how this works and why as this if statement seems a little confusing.