mvasco mvasco - 1 year ago 124
PHP Question

Call to a member function prepare() on null at CRUD system

I am using a CRUD system in a web site.
I show a table with all existing records (avisos.php).
When the user clicks on the ADD NEW RECORD button, following script is launched:

$(".content-loader").fadeOut('slow', function()

nuevo_aviso.php includes a HTML form to add a new record. This is its content:

<div id="dis">
<!-- here message will be displayed -->

<form method='post' id='emp-SaveForm' action="#">

<table class='table table-bordered'>

<td><input type='text' name='titulo_anuncio' class='form-control' placeholder='EX : P.M.I. DUCTO DE JUAREZ' required /></td>

<td><input type='text' name='texto_anuncio' class='form-control' placeholder='EX : Mantenimiento preventivo el dia 17 de agosto' required></td>

<td colspan="2">
<button type="submit" class="btn btn-primary" name="btn-save" id="btn-save">
<span class="glyphicon glyphicon-plus"></span> Guardar Aviso/Anuncio


From here a JS file (crud.js) called from avisos.php should pass the form data to create_aviso.php:
this is the function at crud.js:

/* Data Insert Starts Here */
$(document).on('submit', '#emp-SaveForm', function() {

$.post("create_aviso.php", $(this).serialize())
$("#dis").fadeIn('slow', function(){
$("#dis").html('<div class="alert alert-info">'+data+'</div>');
return false;

And then, at create_aviso.php the received data should be inserted in the database:

require_once 'dbconfig.php';

$titulo_anuncio = $_POST['titulo_anuncio'];
$texto_anuncio = $_POST['texto_anuncio'];


$stmt = $db_con->prepare("INSERT INTO tbAnuncios(titulo_anuncio,texto_anuncio) VALUES(:etitulo, :etexto)");
$stmt->bindParam(":etitulo", $titulo_anuncio);
$stmt->bindParam(":etexto", $texto_anuncio);

echo "Registro aƱadido";
echo "Error";
catch(PDOException $e){
echo $e->getMessage();


The problem is that at line 12 from create_aviso.php the browser throws an error:

Fatal error: Call to a member function prepare() on null in /../create_aviso.php on line 12. THis is line 12:

$stmt = $db_con->prepare("INSERT INTO tbAnuncios(titulo_anuncio,texto_anuncio) VALUES(:etitulo, :etexto)");

I have checked the data and found that only the value from
is given to
is not received. That should be the reason for the exception, but I don't find the error at the code.

Answer Source

The content of dbconfig.php is missing, but I think your problem it's because $db_con must be acessible in line 12.

In your case, $db_con can be not defined, or it is in a different scope.

Try to use

global $db_con;

In line 11 of create_aviso.php

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download