我有这个问题:
"SELECT gs.id FROM table1 gs WHERE gs.external_id = " . $external_id . " ";
我想要一个包含所有返回ID的PHP数组,如下所示:
$arr_ids = array(1,2,34,14);
我知道我可以使用while,但我想知道是否有功能 或者更优雅的方式:
$result = array();
while ($row = mysql_fetch_array($rs))
{
$result[] = $row['id'];
}
unset($rs);
unset($row);
由于
答案 0 :(得分:0)
有一种更优雅的方式。您应该使用mysqli
函数(而不是mysql
)。 See this question and answer for more information about this topic.
您可以在不使用循环的情况下使用mysqli_result::fetch_all()
。下面是一个如何使用它的例子。
// Connect to database
$sqlConn = new mysqli($hostname, $username, $password, $database);
// Build SQL String
$sqlString = "SELECT * FROM my_table";
// Execute the query and put data into a result
$result = $this->sqlConn->query($sqlString);
// Copy result into a associative array
$resultArray = $result->fetch_all(MYSQLI_ASSOC);
// Copy result into a numeric array
$resultArray = $result->fetch_all(MYSQLI_NUM);
// Copy result into both a associative and numeric array
$resultArray = $result->fetch_all(MYSQLI_BOTH);