Relisora Relisora - 4 months ago 12
SQL Question

Change utf8mb4 to utf8

I'm trying to make a script that changes my encoding from utf8mb4 to utf8.

My PHP knowlege is a bit outdated and i can't make the script work with mysqli.

this is the base script i had :

<?php
$con = mysql_connect('localhost','user','password');
if(!$con) { echo "Cannot connect to the database ";die();}
mysql_select_db('dbname');
$result=mysql_query('show tables');
while($tables = mysql_fetch_array($result)) {
foreach ($tables as $key => $value) {
mysql_query("ALTER TABLE $value CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
}}
echo "The collation of your database has been successfully changed!";
?>


it does not work so i tried to update it to mysqli and now i have this :

<?php
$mysqli = new mysqli("localhost", "root", "", "test");

if (mysqli_connect_errno()) {
printf("connexion error : %s\n", mysqli_connect_error());
exit();
}

if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("The database is : %s.\n", $row[0]);
$result->close();
}

$result=mysqli_query('show tables');
while($tables = mysqli_fetch_array($result)) {
foreach ($tables as $key => $value) {
mysqli_query("ALTER TABLE $value CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
}}
echo "The collation of your database has been successfully changed!";
?>


I think the problem is in the last part, the errors i get are :

php errors

Thank you for your help ! :)

Answer

mysqli_query() need first parameter as your connection. Use it as

$result = mysqli_query($mysqli, 'show tables');
while ($tables = mysqli_fetch_array($result)) {
    foreach ($tables as $key => $value) {
        mysqli_query($mysqli, "ALTER TABLE $value CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
    }
}
Comments