PHP - Why should I put an IF in mysqli_prepare()

Asked

Viewed 243 times

3

In the example in Manual PHP was made use of the if before the execution of the instructions. I know that the if is used for comparisons, what comparison is being made here? Follow the example of the website below:

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {

    /* bind parameters for markers */
    $stmt->bind_param("s", $city);

    /* execute query */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($district);

    /* fetch value */
    $stmt->fetch();

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>
  • The first if, if the function mysqli_connect_errno return 1 (amounts to true), means there’s been an error and the code will stop right there.

  • Yes, but I mean the if of the question, mysqli_prepare

  • The second is pretty much the same. If it worked, execute the commands. Otherwise, just close the connection. Pig tutorials. If you are not to do anything with the error, or use the if. in a real application you will stop and log the error to be able to fix.

  • $stmt is a variable that is being created at the time of comparison, the prepare will bring a result boleanus, what the same condition of the first if.

  • As well as "worked out", check if the query is valid?

  • 2

    If the "prepare" was successful, the "inside" of the if runs. If the query contains an error, or any other problem occurs, the $stmt expression will be false, so only close will be executed.

Show 1 more comment

1 answer

7


if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {

This if checks if the query does not have any syntax error or 'execution' as constraints violation, if I succeed does the assignment in $stmt. His absence may lead to error in bind_param() for prepare() have returned false in place of an object mysqli_stmt then the mistake Call to a member function

  • 1

    Thanks for the reply, now I understand.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.