【问题标题】:Can I create a table from another table that I have in a $var in PHP我可以从 PHP 中的 $var 中的另一个表创建一个表吗
【发布时间】:2013-11-24 23:34:19
【问题描述】:

如下所示,我正在从一个表中的一个变量中获取一些数据,并尝试在另一个数据库中创建一个新表(当然在同一主机中)。该表从未创建,我什至不知道它是否可能。

请注意,我只能用 user1 连接到 db1,用 user2 连接到 db2,这就是我尝试这些东西的原因。

有什么帮助吗?

mysql_connect("localhost:3036", "user1", "pass1")or die("cannot connect"); 
mysql_select_db("db1")or die("unable to select db1");// connect to db1 as user1

$takedata="SELECT ID, post_date, post_content, guid 
    FROM `db1`.`wp_posts`"; // in var $takedata , I save the query


$result_new=mysql_query($takedata); //execute the query 

if($result_new){
echo "data from db1 taken sucsessfully";
echo "<BR>";

}

else {
echo "ERROR taking data from db1";
echo "<BR>";
}


mysql_close(); // close connection with db1

mysql_connect("localhost:3036", "user2", "pass2")or die("cannot connect"); 
mysql_select_db("db2")or die("unable to select db2");// connect to db2 as user2

$sql="CREATE TABLE `db2`.`newtable`  AS (`$result_new`)"; //Here is the tricky part
            //I'm trying to create table in db2 with the data
                                   //I took from db1.

$result=mysql_query($sql);


if($result){
echo "Table newtable Created";
echo "<BR>";

}

else {
echo "ERROR Creating Table newtable";
echo "<BR>";
}

mysql_close(); // close connection with db2

【问题讨论】:

  • 是的,您可以先获取结果光标,然后从中创建一个数组。然后创建新表并将数组中的数据一一插入到该表中。

标签: php mysql sql


【解决方案1】:

您的代码没有意义,因为我不知道 $result_new 将包含什么。 create table 命令需要一定的语法。

不过,我可以回答你的问题:

该表从未创建,我什至不知道它是否可能。

不知道是否没有正确查询错误的原因。使用 mysql_error() 函数来执行此操作。

if($result){
   echo "Table newtable Created";
   echo "<BR>";

}

else {
   echo "ERROR Creating Table newtable : ";
   echo mysql_error();
   echo "<BR>";
}

【讨论】:

    猜你喜欢
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    • 2012-11-17
    • 2014-12-26
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多