将utf8mb4更改为utf8

时间:2016-07-15 12:49:35

标签: php mysql mysqli utf-8 utf8mb4

我正在尝试创建一个脚本,将我的编码从utf8mb4更改为utf8。

我的PHP知识有点过时,我无法使脚本与mysqli一起使用。

这是我的基本脚本:

<?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!";
  ?>

它不起作用所以我试图将它更新为mysqli,现在我有了这个:

<?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!";
  ?>

我认为问题出在最后一部分,我得到的错误是:

php errors

感谢您的帮助! :)

1 个答案:

答案 0 :(得分:1)

mysqli_query()需要第一个参数作为您的连接。将其用作

$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");
    }
}