0

The following function is not working and i cannot see why.

function nuevoContacto($_POST) {
    try {
        include('func/usarBases.php');
        $mensaje="INSERT INTO `t_contactos`(`id_c`, `nombre`, `telefono`, `telefono2`, `corto`, `celular1`, `celular2`, `email`, `puesto`, `id_a`) VALUES (NULL,'$_POST[nombre]','$_POST[tel1]','$_POST[tel2]','$_POST[corto]','$_POST[cel1]','$_POST[cel2]','$_POST[email]','$_POST[puesto]','$_POST[id_a]')";
        $hacerConsulta = $base->prepare($mensaje);
        $hacerConsulta->execute();
    }
    catch( PDOException $e) {
        echo "<p>Error Connection: " .$e->getMessage()."</p>";
    }   
    $hacerConsulta=null;
}

Once it is called the code breaks and nothing further is executed. but when you use it inside the main code it works

Sorry i reedited the source and then is still not working, in the include usarBases.php is the conector pdo called $base

2 Answers2

2

What it have to be

function nuevoContacto($base)
{
    $sql  = "INSERT INTO  t_contactos VALUES (NULL,?,?,?,?,?,?,?,?,?)";
    $data = array(
        $_POST['nombre'],
        $_POST['tel1'],
        $_POST['tel2'],
        $_POST['corto'],
        $_POST['cel1'],
        $_POST['cel2'],
        $_POST['email'],
        $_POST['puesto'],
        $_POST['id_a']
    );
    $stmt = $base->prepare($sql);
    $stmt->execute($data);
}

have to be called with $base as a parameter instead of $_POST

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
0

You're lacking a database connection in your function. Add the following to the very beginning of your function:

global $base;

When you add global $base to your function you'll be able to use it within your function without having to re-write the whole thing.

Unrelated note, but worth mentioning.

You are open to SQL injections and you're not using prepared statements as you should. You should be using placeholders and binding them later instead of passing they directly into your query.

And a tip for next time:
State in your question what isn't working. What your expectation is and what actually happens.

MisterBla
  • 2,355
  • 1
  • 18
  • 29