DeveloperBreeze

MySQLi Database Connection and Query

// Database connection parameters
$servername = 'localhost';
$username = 'username';
$password = 'password';
$dbname = 'database';

// Create a MySQLi connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die('Connection failed: ' . $conn->connect_error);
}

// SQL query to select all rows from the 'users' table
$sql = 'SELECT * FROM users';
$result = $conn->query($sql);

// Check if there are results
if ($result->num_rows > 0) {
    // Loop through the results and display 'name' field
    while ($row = $result->fetch_assoc()) {
        echo 'Name: ' . $row['name'];
    }
} else {
    echo 'No results found.';
}

// Close the database connection
$conn->close();

Related Posts

More content you might like

Code
python

Configuring SQLAlchemy with PostgreSQL on Heroku: A Quick Guide

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os

app = Flask(__name__)

# Adjust the DATABASE_URL format for SQLAlchemy compatibility
database_url = os.getenv("DATABASE_URL", "")
if database_url.startswith("postgres://"):
    database_url = database_url.replace("postgres://", "postgresql+psycopg2://")

app.config["SQLALCHEMY_DATABASE_URI"] = database_url

# Initialize the SQLAlchemy object
db = SQLAlchemy(app)

# Sample route to test the setup
@app.route("/")
def index():
    return "Database URI setup complete!"

if __name__ == "__main__":
    app.run()
  • This code retrieves the DATABASE_URL from the environment.
  • If DATABASE_URL starts with postgres://, it replaces it with postgresql+psycopg2://.
  • The db instance is initialized with SQLAlchemy(app) for use with SQLAlchemy ORM.
  • The replacement of "postgres://" with "postgresql+psycopg2://" is necessary because of a compatibility issue between the URI format provided by Heroku and the URI format expected by SQLAlchemy.

Nov 08, 2024
Read More
Tutorial

Connecting a Node.js Application to an SQLite Database Using sqlite3

To interact with SQLite databases, install the sqlite3 package using npm:

npm install sqlite3

Oct 24, 2024
Read More
Code
php

MySQL Database Query and Result Processing

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Be the first to share your thoughts!