加入字符串和数组元素不起作用

时间:2017-03-24 20:56:15

标签: php mysqli concatenation

这是我的PHP代码:

$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD);

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$statecodes = array(0=>"test1","test2");
while($i<sizeof($statecodes)) {
  $ini = "users_";
  $var = sprintf("%s%s", $ini, $statecodes[$i]);
  print $var;
  $query = "CREATE DATABASE IF NOT EXISTS" . $var;
  $stmt = $mysqli->prepare($query);
  /* Execute the statement */
  $stmt->execute();
  $i=$i+1;
  /* close statement */
  $stmt->close();
}

我得到的输出是

users_

我想创建名为 user_test1 user_test2

的数据库

1 个答案:

答案 0 :(得分:1)

试一试。您在printf()之后错过了一个空格,由于未初始化您的计数器而导致您的循环中断。 PHP提供了很多方便的方法来处理数组遍历和字符串连接;看着你的代码我猜你的经验是用一种低得多的语言?像<?php $conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $statecodes = array("test1","test2"); foreach ($statecodes as $state) { $var = "users_$state"; // remove dangerous characters! $var = preg_replace("/[^\w]/", "", $var); $query = "CREATE DATABASE IF NOT EXISTS $var"; $result = $conn->query($query); if (!$result) { //do something! } } 之类的东西在某些任务中派上用场,但是如果你想把两个字符串组合在一起就太过分了!

最后,如果查询不是带有占位符的预准备语句,则无需准备和执行查询。但是,您需要清理输入并检查查询结果是否有错误。

SELECT DISTINCT
  [client_id]
  ,[auto_study_configuration_id]
  ,[study_type_id]
  ,CAST(DATEPART(YEAR,DATEADD(DAY,[start_time_id],'1999-12-31')) AS VARCHAR) + 
   '-Q' + 
   CAST(DATEPART(QUARTER,DATEADD(DAY,[start_time_id],'1999-12-31')) AS VARCHAR) AS quarter_name
  FROM [adeffx_system].[info].[mid_family_app_map]