0

I am trying to handle errors for faulty queries sent by mysqli_query to my database, but for some reason mysqli_query() does not return anything when a faulty query is passed through it. The function works fine when the query is valid, and returns what it is supposed to, but when a faulty query is executed the function returns nothing, and at this point I am not even sure it is returning anything because it does not execute any of the following lines when this occurs. Here is the code I am trying to run:

<?php
//Functions
function findTable($con, $tableName) {
    $query = "SELECT * FROM $tableName";
    if (!mysqli_query($con, $query)) {
        echo("Errorcode: " . mysqli_errno($con));
        exit();
    }
    
    echo "Table exists";
}

//Connect to DB
$con = mysqli_connect("localhost", "root", "pass", "db");

//Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    exit();
}

echo "Connected to DB;\r\n";

findTable($con, "");

mysqli_close($con);

?>

Output for this currently looks like this:

Connected to DB;

Anyone know what could be causing this issue? mysqli seems to be working fine on my system otherwise.

Dharman
  • 30,962
  • 25
  • 85
  • 135
brenno
  • 11
  • 1
  • Check out https://stackoverflow.com/a/22662582/2734189 for some good detailed info on diagnosing problems with mysqli queries. – Don't Panic Jun 03 '22 at 16:36
  • The behavior you're describing sounds like mysqli is throwing an exception, but your server is not configured to show php errors. – Don't Panic Jun 03 '22 at 16:38
  • Why are you trying to check for mysqli errors manually? Why are you even using mysqli? – Dharman Jun 03 '22 at 18:10
  • It looks like you are using some really bad tutorial. I highly encourage you to find something better. If you are only starting to learn PHP then you should learn PDO instead of mysqli. PDO is much easier and more suitable for beginners. Start here https://phpdelusions.net/pdo & https://websitebeaver.com/php-pdo-prepared-statements-to-prevent-sql-injection. Here are some good video tutorials https://youtu.be/2eebptXfEvw & https://www.youtube.com/watch?v=sVbEyFZKgqk&list=PLr3d3QYzkw2xabQRUpcZ_IBk9W50M9pe- – Dharman Jun 03 '22 at 18:10

0 Answers0