The PDO class is used to work with the database in PHP.
DB connection
To connect to MySQL, you need to write such code (taken from here ),
$host = '127.0.0.1'; $db = 'test'; $user = 'root'; $pass = ''; $charset = 'utf8mb4'; $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ]; $dsn = "mysql:host=$host;dbname=$db;charset=$charset"; try { $pdo = new PDO($dsn, $user, $pass, $options); } catch (\PDOException $e) { throw new \PDOException($e->getMessage(), (int)$e->getCode()); }
enter your own values for the connection parameters and place in the db.php file.
After that in your script write include 'db.php'; and after that, the $pdo variable will be available in it, which will be used for all database queries.
Request execution
Performing a SELECT query involves 3 stages:
- preparation of the request, with question marks being put in place of all variables. This creates the $ stmt variable.
- execution of the request, in which all the variables involved in the request are sent separately, as an array, to the
$stmt->execute() method. - getting the requested data. Data can be obtained in three different ways.
- single line as array or object,
$stmt->fetch() - an array of strings, if the query can return more than one string,
$stmt->fetchAll() . After that, the resulting array can be displayed via foreach() . - the only value is if we request a single column of a single row,
$stmt->fetchColumn() - in very rare cases, the acquisition can be performed in a fourth way - sampling one line at a time in the loop, but we will not consider it here.
This is a scheme for performing any queries in which variables are involved. In this case, the code will be as follows:
include 'db.php'; $stmt = $pdo->prepare('SELECT money FROM bot WHERE user_id=?'); // подготовка $stmt->execute([$id]); // выполнение $money = $stmt->fetchColumn(); // получение
moneyfield - n.osennijWHERE- n.osennij