change collation in database in php

To change the collation of a MySQL database in PHP, follow the steps below:

  1. Connect to the MySQL database using PHP mysqli_connect() function.

    main.php
    $conn = mysqli_connect("localhost", "username", "password", "database");
    
    73 chars
    2 lines
  2. Run the SQL query to change the collation of the database.

    main.php
    mysqli_query($conn, "ALTER DATABASE database_name CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
    
    102 chars
    2 lines

    Replace database_name with the name of the database that you want to change the collation for.

    The above query changes the collation of the database to utf8mb4 with utf8mb4_unicode_ci which is a general-purpose collation that is case-insensitive and accent-insensitive.

  3. Close the database connection using mysqli_close() function.

    main.php
    mysqli_close($conn);
    
    21 chars
    2 lines

That's it! The collation of the database has been changed using PHP.

gistlibby LogSnag