我想用这段代码从数据库中获取一些数据

$mysql_hostname = "localhost";
$mysql_user     = "root";
$mysql_password = "";
$mysql_database = "test";

$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password);
mysql_select_db($mysql_database, $bd);

$result = mysql_query("SELECT author_id FROM user");
while($data = mysql_fetch_array($result)) {
    $sn=$data['author_id'];
}

$lastresult = mysql_query("SELECT * FROM post WHERE id='".$sn."'");

此代码只获取一个author_id
$sn=$data['author_id']$lastresult只对一个author_id起作用,而不获取所有的author_id
如何获取所有author_id的数据?

最佳答案

您正在覆盖每个循环。

$result = mysql_query("SELECT author_id FROM user");
$sn = [];
while($data = mysql_fetch_array($result)) {
    $sn[] = $data['author_id'];
}

$sn = implode(',',$sn);
$lastresult = mysql_query("SELECT * FROM post WHERE id IN (".$sn.")");

PS:mysql_u*函数已弃用,存在安全问题。考虑用mysqli_ux函数或PDO替换。

关于php - MySQL从外面获取数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48345972/

10-13 02:02