多个数据库查询串在一起

时间:2013-03-23 15:39:42

标签: php mysql database

我试图使用以下逻辑将一些表单数据放入两个数据库表中

  • INSERT'watchlists'
  • 的监视列表 来自SELECT watchlist_id'watchlists'的新关注列表的
  • WHERE watchlist_name = $watchlist_name(刚刚创建的新关注列表的名称)和user_id = $user_id
  • INSERT watchlist_id(从上一个查询中选择)和film_id'watchlist_films'

我正在使用以下代码,但在运行SELECT查询时,该过程似乎已中断。在数据库中创建了新的监视列表,但它不会选择新监视列表的ID,也不会运行代码的最后一部分。

if ($db_server) {
        // Add new Watchlisth
        if (!empty($watchlist_name)) {
            $watchlist_name = clean_string($watchlist_name);
            $watchlist_description = clean_string($watchlist_description);
            mysql_select_db($db_database);

            // Create new Watchlist
            $insert_new_watchlist = "INSERT INTO watchlists (user_id, name, description, category) VALUES ('$user_id', '$watchlist_name', '$watchlist_description', '$watchlist_category')";
            mysql_query($insert_new_watchlist) or die("Insert failed. " . mysql_error() . "<br />" . $insert_new_watchlist);

            // Select new Watchlist's ID
            $select_new_watchlist_query = "SELECT watchlist_id FROM watchlists WHERE name = " . $watchlist_name;
            $new_watchlist_id = mysql_query($select_new_watchlist_query);

            // Insert film into new Watchlist
            $add_new_film = "INSERT INTO watchlist_films (watchlist_id, film_id) VALUES ('$new_watchlist_id', '$rt_id')";
            mysql_query($add_new_film) or die("Insert failed. " . mysql_error() . "<br />" . $add_new_film);
            $addWatchlist_good_message = '<div class="alert alert-success">Watchlist created successfully, and film added!</div>';?>
            <script>
                $('a.add-watchlist').trigger('click');
            </script><?php
        }
    } else {
        $addWatchlist_bad_message = '<div class="alert alert-error">Error: could not connect to the database.</div.';?>
        <script>
            $('a.add-watchlist').trigger('click');
        </script><?php
    }
    require_once("db_close.php");
}

我使用以下字符串在phpMyAdmin中运行查询:SELECT watchlist_id FROM watchlists where name = "LotR"(其中LotR是新创建的监视列表的名称)并且完美无缺,因为它将我带回了监视列表的ID,这是什么我想传入两个INSERT查询中的第二个。

1 个答案:

答案 0 :(得分:1)

mysql_query()会返回资源数据类型,而不是字段值,因此请替换

$new_watchlist_id = mysql_query($select_new_watchlist_query);

$result=mysql_query($select_new_watchlist_query);
$new_watchlist_id=mysql_result($result,0)