Reputation: 67
I want to add a column to a table inside MySQL. I am using MySQLi and in the code below, I wrote a code I saw from researching. Would it still execute if it was in the if statement? Also, Would I need to keep the $mysqli->query("ALTER TABLE tableName ADD ColumnName varchar(255) NOT NULL"
in the connect() function or would I just erase it after executing it one time?
function connect()
{
require_once 'Constants.php';
// Connecting to mysql database
$this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check for database connection error
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (!$mysqli->query("ALTER TABLE tableName ADD ColumnName varchar(255) NOT NULL")) {
echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
// returing connection resource
return $this->conn;
}
Upvotes: 0
Views: 656
Reputation: 744
Would it still execute if it was in the if statement?
There are two "if" statements shown. The first relates to a successful connect and does not have the ALTER TABLE query inside it, so I'm assuming you don't mean that one. However: If you did ... it would only execute if the connection succeeds, obviously.
The second statement executes as part of the if statement, in fact Before the if statement so the if statement can evaluate whether the output from the sql query is true or false. So yes, it will execute inside the if statement.
Would I need to keep the $mysqli->query("ALTER TABLE tableName ADD ColumnName varchar(255) NOT NULL" in the connect() function or would I just erase it after executing it one time?
If you are creating a fresh table each time and require that this column/field be added each time you run your application, then it will need to be there each time. That would be an unusual situation, however. If you are not creating a new table each time, and you have already created that column/field, this query will fail as you can not add the same field twice. That would be a way to test if the column/field has been created already, but there are other methods for that which do not result in a mysql error.
Upvotes: 1