Using mysql_fetch_assoc and mysql_result together?
I am having great trouble trying to use mysql_fetch_assoc
and mysql_result
together in the same PHP script.
Originally (when not utilizing the mysql_result
function) I was getting the required database values using a combination of mysql_query
and mysql_fetch_assoc
and everything was fine. Then i added 2 lines into my code to obtain certain ‘title’ f开发者_如何学Goield values using mysql_result
.
Now if i run my script as it is below i will only receive 1 result even though there are 2 result. Then if i move my do/while
loop up so that it is between the other 2 blocks of code (mysql_fetch_assoc
and mysql_result
lines) i will receive the desired 2 results.
I need my loop to come after the mysql_result
section so putting the loop before it is not an option.
// connect to DB and get values
mysql_select_db($database, $mywebsite);
$query_not_related_before = "SELECT * FROM table limit 2";
$not_related_before = mysql_query($query_not_related_before, $ mywebsite);
$row_not_related_before = mysql_fetch_assoc($not_related_before);
// Extract just the results from the title field (the problem area!)
$before_essayid4 = mysql_result($not_related_before,0, 'title');
$before_essayid5 = mysql_result($not_related_before,1, 'title');
// Display results etc
do {
echo "<br />".$row_not_related_before['title']."<br />";}
while ($row_not_related_before = mysql_fetch_assoc($not_related_before));
Plase help,
Many thanks,
David
I am unsure if this will solve your problem but I think you should "seek
" the result back.
mysql_data_seek ($not_related_before, 0)
Also, check out the warning on the mysql_result page:
Calls to mysql_result() should not be mixed with calls to other functions that deal with the result set.
Hope this helps ;)
You get one row because the first already requested here:
$row_not_related_before = mysql_fetch_assoc($not_related_before);
So I think you have to move result pointer to beginning:
mysql_data_seek($not_related_before, 0);
// Display results etc
do {
echo "<br />".$row_not_related_before['title']."<br />";}
while ($row_not_related_before = mysql_fetch_assoc($not_related_before));
A simpler solution would be to use 2D array's, i have always found the mysql functions to be a little cumbersome.
<?php
$result = mysqli_query(db_connect(),$query);
$result_out = array();
if(@mysqli_num_rows($result))
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))$result_out[]=$row;
foreach($result_out as $row)
{
echo "<br />".$row['title']."<br />";
}
?>
hth
精彩评论