select and update in a mysql db in php

To select and update data in a MySQL database using PHP, follow these steps:

  1. Connect to the database using the PDO or mysqli method in PHP.
main.php
// PDO Method
$host = 'localhost';
$dbname = 'mydatabase';
$username = 'myusername';
$password = 'mypassword';

try {
    $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

// MySQLi Method
$host = 'localhost';
$dbname = 'mydatabase';
$username = 'myusername';
$password = 'mypassword';

$conn = mysqli_connect($host, $username, $password, $dbname);

if (mysqli_connect_errno()) {
    die('Connection failed: ' . mysqli_connect_error());
}
612 chars
25 lines
  1. To select data, use the SELECT statement with the query() method in PDO or the query() or mysqli_query() method in mysqli.
main.php
// PDO Method
$stmt = $conn->query("SELECT * FROM mytable");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// MySQLi Method
$query = "SELECT * FROM mytable";
$results = mysqli_query($conn, $query);
199 chars
8 lines
  1. To update data, use the UPDATE statement with the exec() method in PDO or the query() or mysqli_query() method in mysqli.
main.php
// PDO Method
$stmt = $conn->prepare("UPDATE mytable SET column1 = :value1 WHERE column2 = :value2");
$stmt->bindParam(':value1', $value1);
$stmt->bindParam(':value2', $value2);
$stmt->execute();

// MySQLi Method
$query = "UPDATE mytable SET column1 = '$value1' WHERE column2 = '$value2'";
mysqli_query($conn, $query);
320 chars
10 lines

Note: PDO is recommended over mysqli as it is both more secure and versatile.

gistlibby LogSnag