Block catch shows as Undefined to a variable

Asked

Viewed 26 times

0

I have a problem showing the value of a variable inside the block catch. It simply doesn’t print the value of the variable on the screen $sql, here the code:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "meudb";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO minhaTabela (firstname)
VALUES ('John')";
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo "New record created successfully. Last inserted ID is: " . $last_id;
} catch(PDOException $e) {
echo $sql ."<br>".$e->getMessage();
}
$conn = null;

The error occurs exactly in the block catch when I try to print the variable value on the screen $sql, here in this part:

catch(PDOException $e){
echo $sql . "<br>". $e->getMessage();
}

On the screen appears the following:

When all goes well:

New record created successfully. Last inserted ID is: 1

When something goes wrong,

SQLSTATE[HY000] [1045] Access denied for user 'root'@?localhost' (using password: YES)

The value of $sql which would be the query to Mysql. And in the IDE it appears that $sql is Undefined

The point would be to show up like this:

INSERT INTO myTable (firstname) VALUES SQLSTATE[HY000] [1045] Access denied for user 'root'@?localhost' (using password: YES)

What mistake would you be making?

  • the variable $sql is not being globally created.

  • Our big mistake, thank you very much!

  • Although @thrnk is right, don’t think that variables should be created globally to be accessed in a block catch. What happens is: for a variable to be accessed in a block catch, it must be declared in a scope above the block try.

  • and how would this be done in this case @Lucassamuel? Could you help me?

  • I answered your question.

1 answer

0


Variables within the local scope of a block try cannot be accessed outside this scope, as in a block catch, for example. For this, you must declare this variable in a scope above the scope where the block is try/catch.

In your code, declare the variable $sql before the block try. Then you can access it inside the block catch.

  • That’s what I did. I declared it below the $dbname variable, like this: $servername = "localhost"; $username = "root"; $password = ""; $dbname = "meudb"; $sql = "INSERT INTO myTable (tname) VALUES ('John')";

  • Yes. I was just more specific about the scopes of the variables.

  • Got it @Lucassamuel, that’s right, now with your comment I don’t go wrong again because you were really more specific.

Browser other questions tagged

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