Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用PDO prepared语句从映射在数据库中动态创建表_Php_Sqlite_Pdo - Fatal编程技术网

Php 使用PDO prepared语句从映射在数据库中动态创建表

Php 使用PDO prepared语句从映射在数据库中动态创建表,php,sqlite,pdo,Php,Sqlite,Pdo,我需要帮助解决这个问题。我有一张价值观地图: $table = "tableName" $columns = "col1", "col2", ... "coln" $types = "col1type" .... "colntype" 是否可以使用PDO准备的语句来构建类似以下的SQLITE查询(示例): 当然,我事先不知道需要使用多少bind参数,我需要一个准备好的语句模板

我需要帮助解决这个问题。我有一张价值观地图:

$table = "tableName"
$columns = "col1", "col2", ... "coln"
$types = "col1type" .... "colntype"
是否可以使用PDO准备的语句来构建类似以下的SQLITE查询(示例):

当然,我事先不知道需要使用多少bind参数,我需要一个准备好的语句模板,如下所示:

create table if not EXISTS ':tableName' (':col1Name' :col1Type, ':col2Name' :col2Type, ... , 'colnName' :colnType);
我正在考虑通过首先连接准备好的语句来构建查询:

$query = " create table if not EXISTS ':tableName' (";

for($i=0; i<count($columns); i++){
$query = $query . " ':col$iName' " . " :col$iType ";

if($i != count($columns) - 1){
$query = $query . ",";
}else {
$query = $query . ")";
}
}
$query=“如果不存在创建表”:tableName'(”;

对于($i=0;i而不输入查询结构,请使用以下代码

<?php
$table = "tableName";
$columns = ['col1', 'col2', 'col3', 'col4'];
$types = ['TEXT', 'TEXT', 'TEXT', 'TEXT'];

$buffer = [];
foreach ($columns as $i => $colName){
    $colType = $types[$i] ?? null;
    $buffer[] = "'{$colName}' {$colType}";
}
$output = implode(', ', $buffer);

$query = "create table if not EXISTS '{$table}' ({$output})";

你试过运行这段代码吗?当然,效果很好。SQLITE查询本身不在范围之内。如果它只是在模仿,或者你的逻辑真的有缺陷,那就不知道了,但不管怎样,它都会使你的答案偏离主题。这段代码创建了一个无效的查询,因此基本上是无用的。以防万一,问题是“如何创建表”,不是一个查询。我想我能够进入提问者的头脑,即使问题有点悬而未决。你从哪里得到这个映射?我没有代码,但我打算从json推断这个信息。这个json来自哪里?它来自数据库,我需要将一些键和值映射为tablename和columns,并确定每个基本情况下的类型。无论如何,我认为它来自何处以及为什么不重要,我需要使用JSON并使用一些参数创建一个表。您不能将参数与create table一起使用。
<?php
$table = "tableName";
$columns = ['col1', 'col2', 'col3', 'col4'];
$types = ['TEXT', 'TEXT', 'TEXT', 'TEXT'];

$buffer = [];
foreach ($columns as $i => $colName){
    $colType = $types[$i] ?? null;
    $buffer[] = "'{$colName}' {$colType}";
}
$output = implode(', ', $buffer);

$query = "create table if not EXISTS '{$table}' ({$output})";