# PHP client guide

Learn how to create a PHP application that connects to the Memgraph database and executes simple queries.

Community-contributed library [PHP Bolt driver](https://github.com/stefanak-michal/php-bolt-driver) by Michal Štefaňák is the most commonly used to connect to Memgraph with PHP via Bolt protocol. 
Memgraph and Neo4j both support Bolt protocol and Cypher queries, which means that same client can be used to connect to both databases.
This is very convenient if switching between the two databases is needed. 

## Quickstart

The following guide will demonstrate how to start Memgraph, connect to it, seed the database with data, and run simple read and write queries with the PHP Bolt client.

The necessary prerequisites that should be installed in your local environment are:

- [PHP >= 8.1](https://www.php.net/manual/en/install.php)
- [Composer](https://getcomposer.org/doc/00-intro.md#installation-linux-unix-macos), a tool for dependency management in PHP.
- [Docker](https://docs.docker.com/get-docker/)

### Run Memgraph 

If you're new to Memgraph or you're in a developing stage, we
recommend using the Memgraph Platform. Besides the database, it also
includes all the tools you might need to analyze your data, such as command-line
interface [mgconsole](https://memgraph.com/docs/getting-started/cli), web interface [Memgraph
Lab](https://memgraph.com/docs/data-visualization) and a complete set of algorithms within a
[MAGE](https://memgraph.com/docs/advanced-algorithms) library.

Ensure [Docker](https://docs.docker.com/engine/install/) is running in the
background. Depending on your operating system, execute the appropriate command
in the console:

**For Linux and macOS:**

```bash
curl -sSf "https://install.memgraph.com" | sh
```

**For Windows:**

```bash
iwr https://install.memgraph.com/windows -useb | iex
```

The command above will start [Memgraph
Platform](https://memgraph.com/docs/getting-started/install-memgraph/docker#install-memgraph-platform),
which includes [Memgraph
database](https://memgraph.com/docs/getting-started/install-memgraph/docker#other-available-docker-images),
[Memgraph Lab](https://memgraph.com/docs/data-visualization#quick-start) and [Memgraph
MAGE](https://memgraph.com/docs/advanced-algorithms#quick-start). Memgraph uses Bolt protocol to
communicate with the client using the exposed 7687 port. Memgraph Lab is a web
application you can use to visualize the data. It's accessible at
[http://localhost:3000](http://localhost:3000) if Memgraph Platform is running
correctly. The 7444 port enables Memgraph Lab to access and preview the logs,
which is why both of these ports need to be exposed. 

For more information visit the getting started guide on [how to run Memgraph
with Docker](https://memgraph.com/docs/getting-started/install-memgraph/docker).

### Create a directory

Next, create a new directory for your application, for example `hello-memgraph` and
position yourself in it.

```bash
mkdir hello-memgraph
cd hello-memgraph
```

### Create PHP script

Create `index.php` file and add the following code to it:

```php
<?php
require_once(__DIR__."/vendor/autoload.php");

// Create a connection class and specify target host and port, default is localhost.
$conn = new \Bolt\connection\Socket();
// Create a new Bolt instance and provide connection object.
$bolt = new \Bolt\Bolt($conn);
// Set available Bolt versions for Memgraph.
$bolt->setProtocolVersions(5.2);
// Build and get protocol version instance which creates connection and executes handshake.
$protocol = $bolt->build();
// Login to database with credentials.
$protocol->hello()->getResponse();
$protocol->logon(['scheme' => 'none', 'principal' => '', 'credentials' => ''])->getResponse();
 
// Pipeline two messages. One to execute query with parameters and second to pull records.
$protocol
    ->run('CREATE (a:Greeting) SET a.message = $message RETURN id(a) AS nodeId, a.message AS message', ['message' => 'Hello, World!'])
    ->pull();
 
// Server responses are waiting to be fetched through iterator.
$rows = iterator_to_array($protocol->getResponses(), false);
// Get content from requested record.
$row = $rows[1]->content;
 
echo 'Node ' . $row[0] . ' says: ' . $row[1];
?>
```

> **Info**
>
> In the example above Bolt protocol version 5.2 is used. When you're connecting to Memgraph with lower versions of Bolt protocol, use arguments for authentication in the `hello()` procedure, instead of using `logon()`.
>
> ```php
$bolt = new \Bolt\Bolt($conn);
$bolt->setProtocolVersions(4.3, 4.1, 4.2);
$protocol->hello(['scheme' => 'none', 'principal' => '', 'credentials' => '']);
```

### Install the PHP library

Make sure you are located in the `hello-memgraph` folder in the terminal. 
Then, run a composer command to get the required library:

```sh
composer require stefanak-michal/bolt
```

That command will create `composer.json` file.

### Run the application

To run the application, run the following command in terminal:

```sh 
php -S localhost:4000
```

Open you browser, enter `localhost:4000` as URL and you should see an output similar to the following:

```
Node 0 says: Hello, World!
```

> **Info**
>
> Another way of running your application is by adding a script in the `composer.json` file:
>
> ```json
{
    "require": {
        "stefanak-michal/bolt": "^7"
    }, 
    "scripts": {
        "start": "php -S localhost:4000"
    },
    "config": {
        "allow-plugins": {
            "php-http/discovery": true
        }
    }
}
```
>
> With the above update of the `composer.json` file, it is enough to run `composer run start` to run the application.

### Visualize data

To visualize objects created in the database with the `index.php` script, head over to [http://localhost:3000/](http://localhost:3000/) and run `MATCH (n) RETURN n;` in the _Query Execution_ tab.
That query will visualize the created node. By clicking on a node, you can explore different properties.

![php-quick-start](https://memgraph.com/docs/pages/client-libraries/php/php-visualization.png)

### Next steps

This guide makes a good starting point when building PHP applications. Check out the [PHP Bolt driver repository](https://github.com/stefanak-michal/php-bolt-driver) to learn more about using the PHP Bolt library.

You can simplify the usage of this library with the [Memgraph Bolt wrapper](https://github.com/stefanak-michal/memgraph-bolt-wrapper).

> **Info**
>
> If you encounter serialization errors while using PHP client, we recommend
> referring to our [Serialization errors](https://memgraph.com/docs/help-center/errors/serialization) page
> for detailed guidance on troubleshooting and best practices.
