PHP - Several functions with SQL queries

So, I have a PHP file with several functions that execute different requests, for example:

function getUserEmail($name)
{
    $link=getLink();
    $name=mysqli_real_escape_string($link, $name);
    $output=mysqli_fetch_array(mysqli_query($link, "SELECT email FROM users WHERE name='$name';"));
    mysqli_close($link);
    return $output[0];
}

function getUserName($id)
{
    $link=getLink();
    $id=mysqli_real_escape_string($link, $id);
    $output=mysqli_fetch_array(mysqli_query($link, "SELECT name FROM users WHERE id='$id';"));
    mysqli_close($link);
    return $output[0];
}

function getLink()
{
    $link = mysqli_connect('localhost', 'myUser', 'myPass');
    mysqli_select_db($link, 'myDB');
    if (!$link) die(mysqli_error($link));
    return $link;
}

(this code may not work, this is just an example)

I did this similarly to the example above, but I think because many functions are called when the page is reloaded, creating and closing several databases is not the most efficient way to continue (and it starts to lag because of several functions added to my project).

Ny thought: creating a $ link for the database in the PHP header and saving it in $ _POST var (for example $ _POST ['link']), and then using it through the code and closing its footer.

This will prevent the creation and closing of multiple links, and I think it will improve performance.

Any thoughts?

+4
2

__construct() '__destruct() `, . :

<?php
  class account {
    protected $link;

    function __construct() {
      $link=getLink();
    }

    function __destruct() {
      mysqli_close($link);
    }

    function getUserEmail($name)
    {
      $name=mysqli_real_escape_string($link, $name);
      $output=mysqli_fetch_array(mysqli_query($link, "SELECT email FROM users WHERE name='$name';"));
      return $output[0];
    }

    function getUserName($id)
    {
      $id=mysqli_real_escape_string($link, $id);
      $output=mysqli_fetch_array(mysqli_query($link, "SELECT name FROM users WHERE id='$id';"));
      return $output[0];
    }

    function getLink()
    {
      $link = mysqli_connect('localhost', 'myUser', 'myPass');
      mysqli_select_db($link, 'myDB');
      if (!$link) die(mysqli_error($link));
      return $link;
    }
  }

, . , .

.

, , getUser(), . , , . :

function getUser($id)
{
  $id=mysqli_real_escape_string($link, $id);
  $output=mysqli_fetch_array(mysqli_query($link, "SELECT * FROM users WHERE id='$id';"));
  return $output;
}
+1

$link=false;
function getLink()
    {
      global $link;
      if (!$link) {
      $link = mysqli_connect('localhost', 'myUser', 'myPass');
      mysqli_select_db($link, 'myDB');
      if (!$link) die(mysqli_error($link));
      }
      return $link;
    }

, getLink() , , . , . , , mysqli over mysql, , .

+1
source

Source: https://habr.com/ru/post/1570378/


All Articles