How were the Sayings of the Prophet Preserved?

When one reads about the sayings of a historical person, like Jesus or Muhammad, peace be upon them, how do we know they actually said it? For instance, the authors of the Bible are largely unknown. While some books of the Bible, such as the Gospels of Matthew, Mark, [...]