Cassandra is a high-performance, scalable distributed database system, widely used in big data scenarios. Compared to traditional relational databases, Cassandra offers superior horizontal scalability and resilience. In PHP projects, you can use the PDO (PHP Data Objects) extension to interact with Cassandra through a unified interface. This article walks you through the process of connecting and operating Cassandra with PDO in PHP.
To work with Cassandra through PDO, ensure your environment has the necessary extensions installed. On a Linux system, use the following commands:
sudo apt-get install php-pdo
sudo apt-get install php-cassandra
Once installed, verify that the modules are loaded using:
php -m | grep pdo
php -m | grep cassandra
To connect to Cassandra, you'll need to specify the host, port, and optionally, authentication details. Below is a basic example of a connection using PDO:
try {
$pdoCassandra = new PDO('cassandra:host=127.0.0.1,port=9042');
// Optional: set default fetch mode and error handling
$pdoCassandra->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$pdoCassandra->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected to Cassandra database.";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
Adjust the host and port values based on your deployment environment.
Once connected, you can execute queries or insert operations using PDO methods. Below are some practical examples:
try {
$stmt = $pdoCassandra->query('SELECT * FROM my_table');
while ($row = $stmt->fetch()) {
// Output result
echo $row['column1'] . ' ' . $row['column2'];
}
} catch (PDOException $e) {
echo "Query failed: " . $e->getMessage();
}
try {
$stmt = $pdoCassandra->prepare('INSERT INTO my_table (column1, column2) VALUES (?, ?)');
$stmt->execute(['value1', 'value2']);
echo "Data inserted successfully.";
} catch (PDOException $e) {
echo "Insertion failed: " . $e->getMessage();
}
Update the table name and column names based on your database schema.
After completing database operations, it is recommended to release resources by closing the connection:
$pdoCassandra = null;
This guide demonstrated how to connect to and operate on a Cassandra database using PHP’s PDO extension. By leveraging PDO, developers gain a consistent interface for database operations, improving maintainability and scalability.
Security Tip: For production use, avoid hardcoding sensitive information like usernames and passwords. Store them securely in environment variables or configuration files with restricted access.