Database does not work

Asked

Viewed 378 times

1

I never made a form, so forgive me if I’m absurdly wrong.

Here is the bank with the table:

CREATE DATABASE db_formacao;
USE db_formacao;

CREATE TABLE  `db_formacao`.`formacoes` (
`ID` INT( 5 ) NOT NULL AUTO_INCREMENT ,
`NOME` VARCHAR( 255 ) NOT NULL ,
`OBJETIVO` TEXT NOT NULL ,
`CARGA` INT( 5 ) NOT NULL ,
`CONTEUDO` TEXT NOT NULL ,
PRIMARY KEY (  `ID` )
) ENGINE = MYISAM ;

Already here, on the page itself that the form is being built try to make the connection:

<?php
    $conn = new mysqli ("localhost", "root", "", "db_formacoes");

    $nome = $_POST['nome'];
    $objetivo = $_POST['objetivo'];
    $conteudo = $_POST['conteudo'];
    $carga = $_POST['carga'];

    $squery = "INSERT INTO formacoes (nome, objetivo, conteudo, carga) VALUES('$nome','$objetivo','$conteudo', '$carga' )";
    $resultado = mysqli_query($conn,$squery);


    if(!mysqli_query($conn, $squery)){  
        echo 'Opa! Não conseguimos nos conectar ao banco de dados. '. mysqli_error($conn);
    }else{
        echo 'Operação realizada com sucesso';
    }

    mysqli_close($conn);
?>

When I click on the save button of the form nothing happens to indicate that the information was saved or not and I am checking this by selecting in phpMyAdmin. Follow the found result: inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

  • Before you start, you named the database as db_formacao but used use formacao, without the prefix db_. Is this correct? The function mysqli_connect receives four parameters, including server path, user, password and database name. You passed only the first one. And you also did not correctly realize the values in $sql.

  • Oops, I don’t know. Let me change and see if it works.

  • Are you sure you can connect? In mysqli_connect there is no login, pass and bank name

  • missing define the database, login, and password, and the name of the created table was formacoes in the query you used db_formacao

  • @Marianaferreira there are several errors in the question, one of them the @Andersoncarloswoss already commented. Another thing: there in INSERT INTO, you are using db_formacao instead of db_formacao.formacoes and then right away, you do $sql = instead of doing $sql .= to concatenate the strings.

  • So the bank doesn’t have a password.

  • Yes but even not having a password have the root login and in place of the password enter ""

  • You can edit the question so I can see how exactly I should change my code?

  • I’ll edit the code for the changes I made.

  • Great is improving, doubt you’re getting the data in the post? already gave an echo to see? there where you have the $sql you can put together it is not necessary to separate, causing it to look like $sql = "INSERT INTO db_formacao.formacoes(NAME,OBJECTIVE,LOAD,CONTENTS) VALUES ('{$NAME}', '{$OBJECTIVE}', '{$LOAD}' ,'{$CONTENTS}')"; These keys are to determine that it is a variable

  • @Marianaferreira saw that he edited the code of the question, but did not edit the texts. Can you describe what is happening now when you run this code? Is there an error? The record is registered?

  • So nothing comes forward to confirm whether or not the form was registered. I am checking a select in the table by phpMyAdmin, but it says that the table is empty, so it was not registered.

  • @Marianaferreira I strongly recommend you read How to write values to the MYSQL database using PHP?

  • @Did you get it? Please make the changes I asked for if you did not follow and I’m sorry I forgot to put the name of the database in this line mysqli_connect('localhost', "root", "",db_formacao)

  • I made the changes you suggested and unfortunately it still doesn’t work. I am reading the link sent in the previous comment. Thank you. :)

  • Then, the message I had left to appear in case of this error in the database connection appears as soon as I enter my form page, even before I try to register something. That is, for some reason the bank does not connect.

  • @Andersonhenrique

  • Could you provide the code for how you are ? @Marianaferreira

  • Yeah, I’ll edit it out

Show 14 more comments

1 answer

3

To connect the bank using mysqli_query, according to the documentation of PHP, there are two ways:

  • Procedural: mysql_query
  • Object-Oriented: mysqli_query

Note: Only in procedural style uses the resource returned by mysqli_connect() or mysqli_init()

To connect procedural style:

$con = mysql_connect('host', 'usuario', 'senha')
or die('Erro ao conectar: ' . mysql_error());
mysql_select_db('banco') or die('Banco não encontrado');

/* Realiza um *SELECT* no banco */
$sql = "SELECT * FROM `usuario` LIMIT 5";
$result = mysql_query($sql) or die('Erro no SQL: ' . mysql_error());

//Exibe os dados
echo "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
    echo "\t<tr>\n";
    foreach ($line as $col_value) {
        echo "\t\t<td>$col_value</td>\n";
    }
    echo "\t</tr>\n";
}
echo "</table>\n";

// Libera um resultado da memória
mysql_free_result($result);

// Fecha conexão
mysql_close($result);

To connect the database using object-oriented style:

$con = new mysqli('host', 'usuario', 'senha', 'banco');

if (mysqli_connect_errno()) {
    printf("Falha na conexão ao banco: %s\n", mysqli_connect_error());
    exit();
}

$sql = "SELECT * FROM `usuario` LIMIT 5";
$query = mysqli_query($con, $sql);

if ($query) {
    // Pode fazer assim
    while ($usuario = mysqli_fetch_assoc($query)) {
        // Exibe um link com a notícia
        echo $usuario['nome'] . ' - ' . $usuario['email'];
        echo '<br/>';
    } // fim while

    // Ou assim
    while ($usuario = mysqli_fetch_object($query)) {
        // Exibe um link com a notícia
        echo $usuario->nome . ' - ' . $usuario->email;
        echo '<br/>';
    }
} 

echo 'Total de notícias: ' . mysqli_num_rows($query);

Here there is a tutorial on how to perform queries using both procedural and object oriented forms. Any questions just comment on the answer.

  • 2

    +1 Dijalma, good answer!

  • I’m sorry if this question was too layy, but then it would just be the connection and, on the form page, would have to do that php creating the variables that receive the form information to send to the bank?

  • @Mariana, yes. No form you point to the aquivo php through the action="processa_form.php". If you choose the method="POST", in the php you will capture the information like this: $nome = $_POST['nome'].

  • Like what I did there in the question?

  • 1

    Exactly. A suggestion. Separate the database connection into a separate file and add via include="conexao.php".

Browser other questions tagged

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