Add data to a Mysql table with PHP. What’s wrong?

Asked

Viewed 174 times

5

Initially, I’m new to PHP and SQL, so take it easy if you have shaving in the code. I’m just testing the PHP and Mysql integration, I took an example table from a book and made a quick html page to pass the parameters.

HTML: (index.html)

    <html>
     <body>
      <form action="add.php">
        <p>Nome<input name="nome" type="text"/>
        <p>Principal Ingrediente<input name="principal" type="text"/>
        <p>Quantidade<input name="quant1" type="number"/>
        <p>Ingrediente Secundário<input name="segundo" type="text"/>
        <p>Quantidade<input name="quant2" type="number"/>
        <p>Instrução<input name="instrucao" type="text"/>
        <p><input type="submit"/>
      </form>
     </body>
    </html>

PHP: (add.php)

<html>
    <body>
        <?php 
        $nome = $_GET['nome'];
        $principal = $_GET['principal'];
        $quant1 = $_GET['quant1'];
        $segundo = $_GET['segundo'];
        $quant2 = $_GET['quant2'];
        $instrucao = $_GET['instrucao'];
        $db = new mysqli('localhost', 'root', 'Another2/', 'drinks');

        $sql = "INSERT INTO drinkfaceis(nome, principal, quant1, segundo, quant2, instrucoes) 
                VALUES(?, ?, ?, ?, ?, ?);";

        $stmt = $db->prepare($sql);
        if(!$stmt){
            echo 'erro na consulta: '. $db->errno .' - '. $db->error;
        }

        echo $nome;
        echo $principal;
        echo $quant1;
        echo $segundo;
        echo $quant2;
        echo $instrucao;

        $stmt->bind_param('ssisib', $nome, $principal, $quant1, $segundo, $quant2, $instrucao);
        $stmt->execute();
        ?>
    </body>
</html>

SQL script:

CREATE DATABASE drinks;
USE drinks;
CREATE TABLE drinkfaceis
(
    nome        VARCHAR(20),
    principal   VARCHAR(20),
    quant1      INT(10),
    segundo     VARCHAR(20),
    quant2      INT(10),
    instrucoes  BLOB
);

When testing does not give any error, he writes the value of the variables (which I put only to test), but when I go to phpMyAdmin and look at the table the data was not inserted.

1 answer

7


And once again the code was correct, the problem was the autocommit deactivated.

When it is off you are required to tell the database that that command (an Insert/update/delete DML) must be executed permanently, this can be done in several ways via php, with the commit() for success and rollback() to cancel the instruction.


Recommended reading:

Mysql Transaction When? How? Why?

What is a Mysql Transaction for?


To connect the bank’s autocommit with the workbanch access the menu:

Server>Option file in the guide General, look for the option transaction and mark autocommit

inserir a descrição da imagem aqui

Phpmyadmin

inserir a descrição da imagem aqui

Browser other questions tagged

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