我有一个简单的脚本,可以在正常情况下正常运行。我正在尝试使其抛出异常,以进行测试。这是一个PHP PDO插入。如果没有插入新行,我希望它引发异常。
这是我的代码:
$query = "INSERT INTO reservations (requestor, location)
VALUES (:requestor, :location)";
$statement = $pdo->prepare($query);
try {
$statement->execute([
'requestor' => $requestor_id,
'location' => $request_location
]);
echo "Success.";
}
catch(Exception $e) {
echo "Sorry, but your request was not completed properly.<br>";
echo "Message: " . $e->getMessage();
}
这很好用。但是,如果我通过修改表列名或绑定参数来使代码不起作用,它仍然会给出成功消息。我没有按预期插入新行。见下文:
$query = "INSERT INTO reservations (requestorzzz, locationzzz)
VALUES (:requestor, :location)";
$statement = $pdo->prepare($query);
try {
$statement->execute([
'requestorzzz' => $requestor_id,
'locationzzz' => $request_location
]);
echo "Thank you! Your request was received.";
}
catch(Exception $e) {
echo "Sorry, but your request was not completed properly.<br>";
echo "Message: " . $e->getMessage();
}
我确实收到php错误消息,但未引发异常。 (自然)不会创建新的列,但是我需要它去捕获以通知用户他们的请求没有发生。我做错了什么吗?
答案 0 :(得分:1)
2分。
首先由@Funk Forty Niner指出。默认情况下,PDO发送警告,也不例外。您必须设置错误模式:
public class Orders {
public static void main(String[] s) {
Orders jp = new Orders();
jp.method1();
List<OrderItems> lstOrdItms = jp.getListOrderItems();
jp.processOrderItems( lstOrdItms );
}
public void method1(List<OrderItem> lstOrderItem) {
.........
}
public List<OrderItem> getListOrderItems() {
............
}
public void processOrderItems() {
............
}
}
public class OrdersTest {
@Mocks
Orders orders;
.....
@Before
public void setUp() {
........
}
@Test
public void testMain() throws SQLException {
// Not sure how to test here
// This will actually execute the main method instead of mock.
orders.main(new String[]{});
}
}
第二:在您的execute方法中为数组使用“命名参数”而不是“列名”
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);