douhunkuang8955
douhunkuang8955
2013-08-28 14:46

功能不起作用[重复]

已采纳

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

</div>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • doufei3152 doufei3152 8年前

    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.

    点赞 评论 复制链接分享
  • dousong1926 dousong1926 8年前

    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

    点赞 评论 复制链接分享