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?
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"]
)
Within that while
loop, you can use the variable $row
and it will represent the contents of the current row. So, you can create an array before the loop and assign each row to a new index in the array within that loop. Once the loop is done executing, your array will be populated.
$arrayVar = array();
while ($row = mysqli_fetch_array($result, MYSQLI_NUM))
{
$arrayVar[] = $row[];
}