Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- bash# cat PHPpdoClient.php
- <?php
- $dsn='mysql:host=localhost;port=3306;dbname=test';
- $user='root';
- $pass='admin';
- try {
- /* obtain a database connection handle */
- $dbh = new PDO($dsn, $user, $pass);
- } catch (PDOException $exception) {
- printf("Failed to connect to the database. Error: %s", $exception->getMessage());
- }
- $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- $dbh->setAttribute(PDO::ATTR_AUTOCOMMIT, false);
- $sql = "SELECT * FROM City";
- /* execute the query */
- $rs = $dbh->query($sql);
- print "\nRetrieved " . $rs->rowCount() . " row(s).\n";
- print "\nCityName\n--------\n";
- /* retrieve the data from the result set */
- $rs->setFetchMode(PDO::FETCH_ASSOC);
- while ($row = $rs->fetch()) {
- $data = $row["CityName"];
- print "$data\n";
- }
- /* close the result set */
- $rs->closeCursor();
- try {
- /* create a prepared statement */
- $query = "INSERT INTO City VALUES (?)";
- $stmt = $dbh->prepare($query);
- $city = 'London, UK';
- /* bind the parameter */
- $stmt->bindParam(1, $city);
- $dbh->beginTransaction();
- /* execute the SQL */
- if ($stmt->execute()) {
- $dbh->commit();
- echo "\nSuccessfuly inserted " . $city . " into the table, City.";
- } else {
- print_r($dbh->errorInfo());
- }
- $city = 'Paris, France';
- /* bind the parameter with another value */
- $stmt->bindParam(1, $city);
- $dbh->beginTransaction();
- /* execute the SQL again */
- if ($stmt->execute()) {
- $dbh->commit();
- echo "\nSuccessfuly inserted " . $city . " into the table, City.\n";
- } else {
- print_r($dbh->errorInfo());
- }
- $sql = "SELECT * FROM City";
- /* execute the query */
- $rs = $dbh->query($sql);
- print "\nRetrieved " . $rs->rowCount() . " row(s).\n";
- print "\nCityName\n--------\n";
- /* retrieve the data from the result set */
- $rs->setFetchMode(PDO::FETCH_OBJ);
- while ($row = $rs->fetch()) {
- $data = $row->CityName;
- print "$data\n";
- }
- /* close the result set */
- $rs->closeCursor();
- } catch (PDOException $exception) {
- print "\nException: " . $exception->getMessage();
- $dbh->rollBack();
- }
- /* close the database connection */
- $dbh = null;
- ?>
- bash# php PHPpdoClient.php
- Retrieved 3 row(s).
- CityName
- --------
- Hyderabad, India
- San Francisco, USA
- Sydney, Australia
- Successfuly inserted London, UK into the table, City.
- Successfuly inserted Paris, France into the table, City.
- Retrieved 5 row(s).
- CityName
- --------
- Hyderabad, India
- San Francisco, USA
- Sydney, Australia
- London, UK
- Paris, France
Add Comment
Please, Sign In to add comment