Skip to content
PHP Logo

In what ways can PHP code be structured to facilitate the creation and retrieval of user-generated content within a web application?

To facilitate the creation and retrieval of user-generated content within a web application, PHP code can be structured using functions to handle database operations, such as inserting new content and fetching existing content. By separating these database operations into reusable functions, the code becomes more organized and easier to maintain. Additionally, using prepared statements with parameterized queries can help prevent SQL injection attacks and ensure data security.

php
// Function to insert new user-generated content into the database
function insertContent($content) {
    $conn = new mysqli('localhost', 'username', 'password', 'database');

    $stmt = $conn->prepare("INSERT INTO user_content (content) VALUES (?)");
    $stmt->bind_param("s", $content);
    $stmt->execute();

    $stmt->close();
    $conn->close();
}

// Function to retrieve user-generated content from the database
function getContent() {
    $conn = new mysqli('localhost', 'username', 'password', 'database');

    $result = $conn->query("SELECT content FROM user_content");
    $content = [];
    while ($row = $result->fetch_assoc()) {
        $content[] = $row['content'];
    }

    $result->close();
    $conn->close();

    return $content;
}

// Example usage
insertContent("New user-generated content");
$content = getContent();
foreach ($content as $item) {
    echo $item . "<br>";
}