Getting all email addresses from table
The code below shows one email address as a output but I want to get a list of all email addresses (seperated by comma) of customer table. How can I ge开发者_如何转开发t that?
<?php
$SQLstring = "SELECT email FROM customers";
$QueryResult = @mysqli_query($DBConnect, $SQLstring)
or die("<p>Unable to execute the query.</p>" .
"<p> Error code " . mysqli_errno($DBConnect) . ":" . mysqli_error ($DBConnect))."</p>";
$NumRows = mysqli_num_rows($QueryResult);
if ($NumRows == 0)
{
echo "<p>No email found.</p>";
}
else
{
for($i = 1; $i <= $NumRows; $i++)
{
$Row = mysqli_fetch_row($QueryResult);
$email = stripslashes($Row[0]);
echo $email;
}
}
?>
This is mysqli
not mysql
you're using so things work a little differently...
Assuming you've created your mysqli connection with something like $DBConnect = new msqli( ... );
It's probably better to store the result before you manipulate it; try something like:
$success = $DBConnect->real_query($SQLstring);
if($success) {
$result = $DBConnect->store_result();
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
echo $row['email'] . "<br />\n"; //for debugging purposes
}
}
$result->free();
Change:
$email = stripslashes($Row[0]);
To:
$email = stripslashes($Row[$i]);
And you should be set
The PHP docs say that mysqli_num_rows may not return the correct number of rows until you've retrieved all rows, so perhaps, instead of using a row count, just keep fetching rows until you run out:
while ($Row = mysqli_fetch_row($QueryResult))
{
$email = stripslashes($Row[0]);
echo $email;
}
EDIT: If you want to store the emails in an array rather than just echoing them, simply change it to this:
while ($Row = mysqli_fetch_row($QueryResult))
{
$email[] = stripslashes($Row[0]);
}
Now $email will be an array containing all of the emails.
use mysql_fetch_assoc in while loop
$NumRows = mysqli_num_rows($QueryResult);
if ($NumRows == 0)
{
echo "<p>No email found.</p>";
}
else
{
while($row = mysql_fetch_assoc($QueryResult)){
$email = stripslashes($row['email']);
echo $email;
}
}
精彩评论