I have been cracking my head on this mater in the past couple of days. I am faced with a situaton where i need to write a MySQL equivalent of PHP code to loop through sql select results. The Php code looks like this

$query = "SELECT pubid, author FROM refs";

    while ($row=$sql->fetch()){
        $id= $row['pubid'];
        $author = $row['author'];
        $name = explode('., ', $author);


How can one write sql/mysql query that does the same?

Recommended Answers

All 6 Replies

You can write a stored procedure that uses a cursor to loop through your query result. Is that what you are looking for? What exactly is your requirement?

Yes, that is what i am looking for...here is the snippet

CREATE PROCEDURE getDistinctAuthors()


DECLARE pubid INT(11);
DECLARE author VARCHAR(255);

-- cursor

DECLARE authorlist_cursor CURSOR FOR

SELECT pubid, author FROM refs;


OPEN authorlist_cursor;

get_authors: LOOP

Thank you @pritaeas for this wonderful link. However, what i want is to loop through the returned strings a loop similar to PHP's foreach loop.

When i call this procedure i get the following results:

mysql> SET @author_list = "";
Query OK, 0 rows affected (0.00 sec)

mysql> CALL unitpublications.build_author_list(@author_list);
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> SELECT @author_list;
| @author_list                                                                                          |
| Elliott, A. M., Luo, N., Tembo, G., Halwiindi, B., Steenbergen, G., Machiels, L., Pobee, J., Nunn, P; |
1 row in set (0.00 sec)

My question is what is the mysql equivalent of a foreach loop that can loop each string delimited by '., ' ?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.