Question

I've searched a lot of basically the same questions on SO which haven't seemed to help. Been a while since i've touched php so i'm guessing there's a simple solution but really can't figure it out.

config.php: (included into admin.php)

$mysqli = new mysqli($mHost, $mUser, $mPass, $db);

admin.php:

$sqlQuery = "INSERT INTO `category` (`id`, `name`) VALUES ('', '$_POST[name]')";
$result = $mysqli->query($sqlQuery);

var_dump($result) returns:

NULL

and gives error:

Fatal error: Call to a member function query() on a non-object in

Was it helpful?

Solution

You are not checking the result of the call to new mysqli. If that fails, then $mysqli will be null and not a valid object you can query against.

Also, by building SQL statements with outside variables, you are leaving yourself open to SQL injection attacks. Also, any input data with single quotes in it, like a name of "O'Malley", will blow up your SQL query. Please learn about using parametrized queries, preferably with the PDO module, to protect your web app. My site http://bobby-tables.com/php has examples to get you started, and this question has many examples in detail.

OTHER TIPS

At the setout, you should call

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

This enables you don't have to check any return values, just put try { ... } catch { ... } blocks.

try {

    if (
        !isset($_POST['name'])     ||
        !is_string($_POST['name']) ||
        $_POST['name'] === ''
    ) {
        throw new UnexpectedValueException('$_POST[\'name\'] is empty');
    }

    $mysqli = new mysqli($mHost, $mUser, $mPass, $db);
    $stmt = $mysqli->prepare("INSERT INTO `category` (`name`) VALUES (?)");
    $stmt->bind_param('s', $_POST['name']);
    $stmt->execute();

    echo 'Success';

} catch (Exception $e) {

    echo $e->getMessage();

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top