使用MySQLi和PHP将行分配给变量

时间:2014-01-11 23:43:30

标签: php mysqli

在使用MySQL一段时间之后,我才开始尝试使用MySQLi。我在教程中找到了这个小代码片段,并且对它有一个疑问(因为Google不会在此返回任何结果......)。

<?php 

$link = mysqli_connect("127.0.0.1", "user", "password", "world"); 

if (!$link)
{
    $error = mysqli_connect_error();
    $errno = mysqli_connect_errno();
    print "$errno: $error\n";
    exit();
}

$query = "SELECT Name, Population, Continent FROM Country WHERE Continent=? ORDER BY Name LIMIT 1";

$stmt = mysqli_stmt_init($link);
if(!mysqli_stmt_prepare($stmt, $query))
{
    print "Failed to prepare statement\n";
}
else
{
    mysqli_stmt_bind_param($stmt, "s", $continent);

    $continent_array = array('Europe','Africa','Asia','North America');

    foreach($continent_array as $continent)
    {
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        while ($row = mysqli_fetch_array($result, MYSQLI_NUM))
        {
            foreach ($row as $r)
            {
                print "$r ";
            }
            print "\n";
        }
    }
}
mysqli_stmt_close($stmt);
mysqli_close($link);
?>

http://www.php.net/manual/en/mysqli-stmt.get-result.php提供

如果我正确理解了这一点,那么$r现在会在所有被调用的行中找到所有结果的数组。如何为每一行分配变量?我可以像在MySQL中那样做类似的事情吗?

$username = $row['username'];

或者现在有什么完全不同的东西吗?

2 个答案:

答案 0 :(得分:4)

while循环中,您可以使用变量$row,它将表示当前行的内容。因此,您可以在循环之前创建一个数组,并将每一行分配给该循环中数组中的新索引。循环完成后,将填充您的数组。

$arrayVar = array();
while ($row = mysqli_fetch_array($result, MYSQLI_NUM))
{
  $arrayVar[] = $row[];
}

答案 1 :(得分:0)

例如

; 我们选择了Name,Population,Continent列。

Name | Population | Continent
X    |  1         |  A
Y    |  2         |  B
Z    |  3         |  C

这些是作为此查询返回的行。

在第一次迭代中,您将获得$row这样的

array("Name"=> "X", "Population"=>"1", "Continent"=>"A");

在第二次迭代中,您将得到$row这样的

array("Name"=> "Y", "Population"=>"2", "Continent"=>"B");

等等。 所以,你可以像你提到的那样使用它(比如$row["Name"]