doupo2157 2014-01-11 23:43
浏览 37
已采纳

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

I'm just starting to dab into MySQLi after using MySQL for a while. I found this little code snippet on a tutorial, and just had a question about it (since Google won't return any results for me on this...).

<?php 

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

if (!$link)
{
    $error = mysqli_connect_error();
    $errno = mysqli_connect_errno();
    print "$errno: $error
";
    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
";
}
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 "
";
        }
    }
}
mysqli_stmt_close($stmt);
mysqli_close($link);
?>

Courtesy of http://www.php.net/manual/en/mysqli-stmt.get-result.php

If I'm understanding this correctly then $r will now do an array of all of the results found in all of the rows called. How can I assign a variable to each row? Can I still do something similar like I did in MySQL?

$username = $row['username'];

Or is there something completely different now?

  • 写回答

2条回答 默认 最新

  • donglu9825 2014-01-11 23:57
    关注

    for example; we have Name, Population, Continent columns that we are selecting.

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

    and these are the rows returned as result of this query..

    in first iteration, you will get $row like this

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

    and in second iteration, you will get $row like this

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

    and so on. so, you can use it as you mentioned(like $row["Name"])

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能