What best practices should be followed when handling database queries in PHP for generating graphs?

When handling database queries in PHP for generating graphs, it is important to sanitize user inputs to prevent SQL injection attacks. Additionally, use prepared statements to securely execute queries and bind parameters. Finally, limit the amount of data retrieved from the database to improve performance when generating graphs.

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Sanitize user input
$user_input = $_POST['user_input'];
$sanitized_input = $conn->real_escape_string($user_input);

// Prepare and execute query
$stmt = $conn->prepare("SELECT * FROM table WHERE column = ?");
$stmt->bind_param("s", $sanitized_input);
$stmt->execute();

// Bind result variables
$stmt->bind_result($result);

// Fetch results and generate graph
while ($stmt->fetch()) {
    // Generate graph using fetched data
}

// Close statement and connection
$stmt->close();
$conn->close();