嗨,我被困在这个回声阵列部分。只获得第一项。 请帮忙!所有帮助将不胜感激!
session_start();
$session = $_SESSION['sessionId'];
$link = mysqli_connect("localhost", "ideajackpot", "random!", "ideajackpot");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$result = "SELECT title FROM title WHERE session_id LIKE $session";
$flickrItems = mysqli_query($link, $result);
$flickrArray = mysqli_fetch_array($flickrItems);
mysqli_close($link);
foreach($flickrArray as $result) {
echo $result.' ';
}
答案 0 :(得分:4)
您只获得SQL查询的第一行,因为您只调用mysqli_fetch_array()
一次。您需要遍历结果以获取所有返回的行:
while ($flickrArray = mysqli_fetch_array($flickrItems);
echo $flickrArray['title'].' ';
}
答案 1 :(得分:1)
您也可以尝试面向对象的方法:
$link = new mysqli("localhost", "ideajackpot", "random!", "ideajackpot")
$flickrItems = $link->query("SELECT title FROM title WHERE session_id LIKE $session");
while ($flickrItem = $flickrItems->fetch_assoc() ){
$result[] = $flickrItem;
}
var_dump($result);
答案 2 :(得分:1)
如果您只想获取数组中的第一个或最后一个项目,为什么不为此创建一些小函数。
/**
* Return first element in array.
*
* @param array $array
* @return mixed
*/
function array_first(array $array)
{
reset($array);
return current($array);
}
/**
* Return last element in array.
*
* @param array $array
* @return mixed
*/
function array_last(array $array)
{
reset($array);
return end($array);
}
用法:
$foo = [1, 2, 3];
var_dump(array_last($foo));