0

I am implementing a script in php for a Wordpress blog. The script should be executed every five minutes. The script opens a mysql connection and I want to close it when I am finished. Can you check if it works?

$db = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_select_db("XY", $db);

//set data into $data

foreach ($data => $info) {
  //do stuff inserts
}

mysql_close(); 

Is the approach right? I am closing the connection used in this script or I am closing also other connections?

3
  • 4
    WARNING: Read up on how you can use WPDB with prepared statements that use placeholder values like %s to properly escape your data. DO NOT use the obsolete mysql_query family of functions. Those were removed in PHP 7 because they're exceptionally dangerous and fundamentally broken. Commented Jan 2, 2018 at 20:51
  • Do you mean this statement is dangerous? mysql_query("INSERT INTO table1 (column1) VALUES (\"$column1\");"); Commented Jan 2, 2018 at 21:01
  • 2
    Extremely. Commented Jan 2, 2018 at 21:01

2 Answers 2

3

Closing the connection explicitly is not mandatory. PHP cleans up all the resources when the script finishes, this includes database connections or sockets, filehandles, any internal resources like images and last but not least, memory blocks.

Sign up to request clarification or add additional context in comments.

Comments

1

You could pass your $db variable to the mysql_close() function call. Like mysql_close($db).

But be aware that the mysql_* are deprecated and will be removed in a future php version. You should look into the mysqli_* functions instead.

1 Comment

Not a future version, it's already happened in PHP 7.0. This is historical fact now. Wordpress also has WPDB, there's absolutely no need to use mysqli.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.