MYSQLI多表不会起作用

时间:2015-07-08 18:48:33

标签: php variables mysqli

我正在尝试创建一个从其他表中获取变量的查询,

SQL table1

-- ----------------------------
-- Table structure for `table1`
-- ----------------------------
DROP TABLE IF EXISTS `table1`;
CREATE TABLE `table1` 
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `naam` varchar(255) DEFAULT NULL,
  `time` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=44145 DEFAULT CHARSET=utf8

SQL Table2

-- ----------------------------
-- Table structure for `table2`
-- ----------------------------
DROP TABLE IF EXISTS `table2`;
CREATE TABLE `table2` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `txt` text,
  `naam` varchar(255) DEFAULT NULL,
  `time` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=44145 DEFAULT CHARSET=utf8;

<?PHP
    $sql = "SELECT * FROM table1 LIMIT 10";
    $result = $mysqli->query($sql);
    while($row = $result->fetch_assoc()) {
        $naam = $row["naam"];   
    }
    $sql2 = "SELECT * FROM table2 WHERE naam = '$naam'";
    $result2 = $mysqli->query($sql2);
    while($row2 = $result2->fetch_assoc()) {
        $txt = $row2["txt"];        
        echo''. $txt.' ';

    }
?>

但是不工作怎么解决这个问题?

编辑:从MYSQL数据库添加表。

2 个答案:

答案 0 :(得分:1)

此查询可以帮助您。当table2.naam = table1.naam条件满足时,它将从table2返回text列。

$sql = "SELECT * FROM komunikaty";
$result = mysql_query($sql);

$rows = array();
while ($rows[] = mysql_fetch_assoc($result)) {}
$smarty->assign('komunikaty', $rows);

希望它会对你有所帮助。快乐的编码

答案 1 :(得分:0)

为什么不喜欢这样:

<?PHP
    $sql = "SELECT t2.txt FROM table2 AS t2 WHERE t2.naam IN (SELECT t1.naam FROM table1 as t1 LIMIT 10)";
    $result = $mysqli->query($sql);
    while($row = $result->fetch_assoc()) {
        $txt = " " . $row["txt"]. " ";        
        echo $txt;
    }
    $result->free();
?>

你可以避免要求2次数据库查询...循环无效..