DatabasePHPSnippets
Database-related PHP snippets
Issue 135016.
Two templates will be available under the Generate Code action (Alt+Insert):
Connect to Database... Display Database Table...
The templates only work for MySQL connections. For other connections, the UI is disabled with a meaningful message (or non-MySQL connections are not displayed at all).
Connect to Database:
This template generates code to connect to a given database connection from in the DB Explorer. When invoked, the following dialog is displayed.
+-------------------------------------------------+ | Connect to Database | +-------------------------------------------------+ | | | Database Connection: | | [[V| jdbc:mysql://localhost:3306/test ]] | | | | Connection variable: | | [Conn ] | | | | [[OK | OK ]] [Cancel ] | | | +-------------------------------------------------+
Generated code:
$conn = mysqli_connect('localhost', 'user', 'password', 'database');
if (!$conn) {
die('Could not connect to MySQL: ' . mysqli_connect_error());
}
mysqli_query($conn, 'SET NAMES \'UTF-8\'');
// TODO: Insert your code here.
mysqli_close($conn);
Display Database Table:
This snippet generates code to display the data a HTML table. When invoked, the following dialog is displayed:
+-------------------------------------------------+ | Display Database Table | +-------------------------------------------------+ | | | Database Connection: | | [[V| jdbc:mysql://localhost:3306/test ]] | | | | Table: | | [[V| CUSTOMER ]] | | | | Columns: | | +---------------------------------------------+ | | | [X] CUSTOMER_ID | | | | [X] DISCOUNT_CODE | | | | ... | | | +---------------------------------------------+ | | | | Connection variable: | | [Conn ] | | | | [[OK | OK ]] [Cancel ] | | | +-------------------------------------------------+
Generated code:
echo '<table>';
echo '<tr>';
echo '<th>CUSTOMER_ID</th>';
echo '<th>DISCOUNT_CODE</th>';
echo '</tr>';
$result = mysqli_query($conn, 'SELECT CUSTOMER_ID, DISCOUNT_CODE, ... FROM CUSTOMER');
while (($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) != NULL) {
echo '<tr>';
echo '<td>' . $row[CUSTOMER_ID] . '</td>';
echo '<td>' . $row[DISCOUNT_CODE] . '</td>';
echo '</tr>';
}
mysqli_free_result($result);
echo '</table>';

