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.– ThRnk
Our big mistake, thank you very much!
– MiSCapu
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 blockcatch
, it must be declared in a scope above the blocktry
.– Lucas Samuel
and how would this be done in this case @Lucassamuel? Could you help me?
– MiSCapu
I answered your question.
– Lucas Samuel