Website - Edit a contact (form)

Asked

Viewed 36 times

0

I am creating a website where every user has their contacts. If a contact is added, it can also be edited. But I’m getting two mistakes that say:

Undefined variable: con e Fatal error: Uncaught Error: Call to a Member Function close() on null.

They say it makes me miss the line where I make $con->close();

Code ligaDB.php

/* 
    Definição das constantes para acesso à base de dados. Pretende-se que estas informações não
    sejam alteradas por qualquer script deste site.
*/
define('DB_USER', 'wisegod');       // nome do utilizador com acesso à base de dados
define('DB_PASSWORD', 'rafaelguerra');  // password de acesso à base de dados       
define('DB_HOST', 'localhost');     // nome do servidor
define('DB_NAME', 'interarchive');      // nome da base de dados

// Ligação ao servidor MySQL
$con =  new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

if($con->connect_errno){
    echo "Falhou a conexão com a base de dados: " . $dbc->connect_errno;
}

$con->set_charset("utf8"); // permite corrigir os caracteres com cedilhas na visualização dos campos

?>

Code:

session_start();

// verifica se o utilizador fez login
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true){

}
else{
    header("location: index.php");
}

if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) ) { // From ver_utilizadores.php
        $id = $_GET['id'];

    } elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) ) { // Form submission.
        $id = $_POST['id'];

    } else { // O ID não é válido
        echo '<p class="erro">Esta página não é acessível.</p>';
        exit();
    }


    if (($_SERVER["REQUEST_METHOD"] == "POST") && isset($_POST['enviado'])) {


        require_once ('ligaDB.php');

        $nome       = $con->real_escape_string(trim($_POST['nome']));
        $email      = $con->real_escape_string(trim($_POST['email']));
        $tele      = $con->real_escape_string(trim($_POST['tele']));
        $morada     = $con->real_escape_string(trim($_POST['morada']));
        $idade     = $con->real_escape_string(trim($_POST['idade']));
        $genero      = $con->real_escape_string(trim($_POST['genero']));
        $user_id      = $_SESSION['user_id'];


        // atualiza o registo
        $q = "UPDATE contactos SET contacto_nome='?', contacto_email='?', contacto_tele='?', contacto_morada='?', contacto_idade='?', contacto_genero='?' WHERE contacto_id=? LIMIT 1";
        $r = $con->query ($q);

        if ($stmt = $con->prepare($sql))
        {
            $stmt->bind_param("ssssssi", $nome, $email, $tele, $morada, $idade, $genero,  $id);

            if($stmt->execute())
            {
                header("location: dashboard.php?erro=O utilizador foi atualizado");
                exit();
            }
            else 
            {

                header("location: dashboard.php?erro=O utilizador não foi alterado. As nossas desculpas.");
            }
        }

        $stmt->close();
    }   

    $con->close(); 


    // Mostra sempre o formulário
    $sql = "SELECT contacto_nome, contacto_email, contacto_tele, contacto_morada, contacto_idade, contacto_genero, FROM contactos WHERE user_id=$id";
    $r = $con->query ($sql);

Gives this error in the line below: Trying to get Property of non-object in

    if ($r->num_rows == 1) {
        $row = $r->fetch_array();

        echo '<div class="row">';
        echo '<div class="col-md-10">';
            if(isset($erro)){
                echo '<div class="alert alert-warning" role="alert">';
                echo "<strong>" . $erro . "</strong>"; 
            }
            echo '<form action="' . htmlspecialchars($_SERVER["PHP_SELF"]) . '" method="post">';
                echo '<div class="form-group">';
                    echo '<label>Nome</label>';
                    echo '<input type="text" class="form-control" id="InputNome" name="nome" value="' . $row[0] . '" required>';
                echo '</div>';
                echo '<div class="form-group">';
                    echo '<label>Número de Telemovel</label>';
                    echo '<input type="email" class="form-control" id="InputTele" name="tele" value="' . $row[1] . '" required>';
                echo '</div>';
                echo '<div class="form-group">';
                    echo '<label>Email</label>';
                    echo '<input type="email" class="form-control" id="InputEmail"  name="email" value="' . $row[2] . '" required>';
                echo '</div>';
                echo '<div class="form-group">';
                    echo '<label>Morada</label>';
                    echo '<textarea class="form-control" id="InputMorada" name="morada" placeholder="' . $row[3] . '" required>';
                echo '</div>';
                echo '<div class="form-group">';
                    echo '<label>Idade</label>';
                    echo '<input type="number" class="form-control" id="InputIdade"  name="idade" value="' . $row[4] . '" required>';
                echo '</div>';        
                echo '<center>';
                    echo '<input type="radio" name="genero" value="' . $row[5] . '"><i class="fa fa-male fa-3x"></i>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
                    echo '<input type="radio" name="genero" value="' . $row[5] . '"><i class="fa fa-female fa-3x"></i>';
                echo '</center>';    
                echo '<button type="submit" class="btn btn-success" name="submit">Enviar</button>';
                echo '<a class="btn btn-primary" href="login_index.php" role="button">Voltar</a>';
                echo '<input type="hidden" name="enviado" value="TRUE" />';
                echo '<input type="hidden" name="id" value="' . $id . '" />';
            echo "</form>";
        echo "</div>";
        echo "</div>";

    } else { // O ID do utilizador não existe
        echo '<p class="erro">Página não está acessível.</p>';
    }

    $con->close();
?>

I’ve tried to solve this problem but I’m struggling.

  • You seem to include the file ligaDB.php, which apparently creates the connection, within a conditional structure and closes the connection outside of it. If the condition is not met, the file will not be included and you will not have a connection to close.

  • @Andersoncarloswoss I put the ligaDB.php out and beyond the bugs I already have. I get 2 more that say, mysqli::query(): Couldn’t fetch mysqli in, Notice: Trying to get Property of non-object in, mysqli::close(): Couldn’t fetch mysqli

  • @Andersoncarloswoss How do I fix these mistakes?

  • First by adding to the question the contents of this file.

  • @Andersoncarloswoss Feito.

  • Erase the first $con->close();.. it seems that it has already been closed

  • Still making the same mistakes :/

  • Close everything at the end. Delete the close() that you have in the middle of the code and put everything at the end

  • Now just show me this error. Trying to get Property of non-object in .

Show 4 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.