How in procedural php when adding information to the database errors are processed? There is a lot of controversial information on the Internet, I did not understand how to do it correctly.

$sql = "INSERT INTO users (login, email, password, datetime) VALUES (?, ?, ?, ?)"; $stmt = mysqli_prepare($db, $sql); mysqli_stmt_bind_param($stmt, 'ssss', $login, $email, $password, $datetime); mysqli_stmt_execute($stmt); mysqli_stmt_close($stmt); 

    1 answer 1

    The mysqli library is a kind of bridge between the procedural and object-oriented programming styles. Therefore, it supports two approaches to error handling: procedural and exceptions.

    The first procedural approach - you check the result of each function and if false returned, you get a message using the mysqli_error() function

     $db = mysqli_connect("localhost", "user", "...", "test"); if (mysqli_connect_errno()) { echo "Ошибка установки соСдинСния" . mysqli_connect_error(); exit(); } $sql = "INSERT INTO users (login, email, password, datetime) VALUES (?, ?, ?, ?)"; $stmt = mysqli_prepare($db, $sql); if(!$stmt) { echo "Ошибка ΠΏΠΎΠ΄Π³ΠΎΡ‚ΠΎΠ²ΠΊΠΈ запроса: " . mysqli_error($db); exit(); } if(!mysqli_stmt_bind_param($stmt, 'ssss', $login, $email, $password, $datetime)) { echo "Ошибка связывания ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€ΠΎΠ²: " . mysqli_error($db); exit(); } if(!mysqli_stmt_execute($stmt)) { echo "Ошибка выполнСния запроса: " . mysqli_error($db); exit(); } mysqli_stmt_close($stmt); mysqli_close($db); 

    Of course, this is not very convenient, especially in object-oriented code, so mysqli allows you to switch to the exception generation mode (there are several types, in debug mode it is most convenient to use MYSQLI_REPORT_ALL ). You can set the mode using the mysqli_report() function mysqli_report()

     mysqli_report(MYSQLI_REPORT_ALL); try { $db = mysqli_connect("localhost", "user", "...", "test"); $sql = "INSERT INTO users (login, email, password, datetime) VALUES (?, ?, ?, ?)"; $stmt = mysqli_prepare($db, $sql); mysqli_stmt_bind_param($stmt, 'ssss', $login, $email, $password, $datetime); mysqli_stmt_execute($stmt); mysqli_stmt_close($stmt); mysqli_close($db); } catch (Exception $e) { echo $e->getMessage(); } 

    Errors are intercepted by the standard exception mechanism. Despite the fact that you have chosen the procedural style, you can use exception catching, which is more often used in object-oriented code.

    • And mysqli_report - to install before each call to the database, or at the beginning of the whole script? - Vlad
    • one
      @Vlad, enough at the beginning of the whole script - cheops