dongqin6926 2014-12-15 20:34
浏览 31
已采纳

如何使用php创建mysql表

i need to make application installation and need to make this tables in installation like wordpress. i have not error in php but this codes doesnt make any tables...

$conn = new mysqli('localhost', 'root', '', 'billboard');
if (mysqli_connect_errno()) {
    exit('Connection lost');
};
for($i=1;$i<=21;$i++){
    $table= "city".$i ;
    echo ($table . "<br>");
    $sql='CREATE TABLE $table
      ( id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id),
        test0 VARCHAR(30),
        test1 VARCHAR(30),
        test2 VARCHAR(30))';
    if ($conn->query($sql) === TRUE) {
        echo 'tables created';
    }
    else {
        echo 'Cant create tables';
    };
};
  • 写回答

1条回答 默认 最新

  • doudilin1225 2014-12-15 20:40
    关注

    PHP evaluates variables in strings that are "wrapped with double quotes", but does not evaluate variables when strings are 'wrapped in single quotes'. In other words, single-quoted strings are literal.

    In this case, you're attempting to create a table called $table 20 times. Instead, you can concatenate the variable into the loop like so:

    $sql= 'CREATE TABLE ' . $table . '
        ( id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id),
        //etc...
    

    OR

    $sql= "CREATE TABLE $table 
        ( id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id),
        //etc...
    

    I find it's more convenient to use double quotes for SQL queries anyway, since you will often need to put SQL values into single quotes (e.g. WHERE ID = '5').

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分