简体   繁体   中英

Data not being saved in DB via PHP form

I,ve trying to save some data in my DB, but it just don't save, no error thrown, i used the echo query_orcN; to see if the data that was input by the form is valid, and its all fine, the form can input up to 5 services ($servicoN), so the cod is kinda repetetive, as i am new with php and mySql, expect to see some newbie coding. I also verified and the logic to choose what if statement will be used is working fine too, so i will post just the case with one service: ...

<?php
   
    include('login/conexao.php'); 
    $nome_cli = $_POST['nome_cli'];
    $nome_orc = $_POST['nome_orc'];
    $obs_trab = $_POST['obs_orc'];
    
    $servico1 = $_POST['serv1'];
    $obs_serv1 = $_POST['obs_serv1'];
    $total1 = $_POST['total1'];
    
    $servico2 = $_POST['serv2'];
    $obs_serv2 = $_POST['obs_serv2'];
    $total2 = $_POST['total2'];
    
    $servico3 = $_POST['serv3'];
    $obs_serv3 = $_POST['obs_serv3'];
    $total3 = $_POST['total3'];
    
    $servico4 = $_POST['serv4'];
    $obs_serv4 = $_POST['obs_serv4'];
    $total4 = $_POST['total4'];
    
    $servico5 = $_POST['serv5'];
    $obs_serv5 = $_POST['obs_serv5'];
    $total5 = $_POST['total5'];
    
    //um serviço
    if($servico1 != '' && $servico2 == '' && $servico3 == '' && $servico4 == '' && $servico5 == ''){
              
            $query_orc1 = "START TRANSACTION;
                          SET @cod_cli = (SELECT cod_cliente
                                          FROM CLIENTE
                                          WHERE nome_cliente = '$nome_cli');
                          INSERT INTO TRABALHO(nome_trabalho, cod_cliente, obs_trabalho, statuspag_trabalho) 
                          VALUES ('$nome_orc', @cod_cli, '$obs_trab', 0);
                          SET @orc = LAST_INSERT_ID();     
                          SET @cod_serv1 = (SELECT cod_servicos
                                          FROM SERVICOS
                                          WHERE descri_servicos = '$servico1');
                          INSERT INTO SERV_TRAB(cod_trabalho, cod_servicos, qtt_serv_trab, obs_serv_trab) 
                          VALUES (@orc, @cod_serv1, $total1, '$obs_serv1');
                          COMMIT;";
            
            if($resultado_query_orc1 = mysqli_multi_query($conexao, $query_orc1))
            {
                    //echo $query_orc1;
                    header('Location: sucesso_orc.php');
                    exit();
            }
            else
            {
                    echo "<h3>Falha </h3>".$valid;
                    echo $result_msg_cliente;
                    

            }}

... I'm using myawardspace to host my project, and already set de engine of the tables to InnoDB as for what i,ve understood, it's one that can support the TRANSACTION.

Already thanks anyone in advance for any help and attention, its the first time a post a question here, hope it's well structered.

You have two problems. PROBLEM 1: failure of the script to produce expected results (ie, the question you asked). PROBLEM 2: Lack of diagnostic information.

To solve problem 2, put the following three lines at the start of your script:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

Running the script with this change might produce error messages that will lead to a solution for your script. If not, run simple php with a known error, such as:

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

echo '1' //no semi colon is an error
echo '2';

If this produces no error messages, it means there is something in the php or web server (such as Apache) configuration stopping them. Find error logs for php and and the web server (probably apache). Exact details for accessing logs are available myawardspace.

SOLVING PROBLEM 1 - Your Script

Whenever running sql through php, there are two major steps involved in getting it to work.

STEP 1: Verify the sql is valid.

The first shot at forming sql within a php script very often contains errors. That means an important milestone in the development of every php script interacting with a database is verifying the sql outside php. An easy way to do this is to put the following statement immediately after setting the value of query_orc1:

echo query_orc1;
exit;

This will put onto your screen the sql the script is attempting to running. Use copy/paste to run the sql using phpmyadmin or whatever interface you have for your database. If there are problems with the sql, you will see them here. If the sql runs as expected, then you know the part of your script creating the sql is working.

STEP 2: Fix php errors that are failing to submit sql correctly to the database.

Maybe someone can spot errors in this script without benefit of error messages. That is fantastic if someone can provide you that information. I would focus on getting your system to show you error message before trying to troubleshoot the php.

I have no experience with mysqli, therefore I use PDO.

At first: Maybe you should overthink the first part with servico1 to servico5. There is maybe a better solution.

My Changes:

  • Switch from mysqli to PDO
  • add prepare statements
  • replace two statements with subselects

I hope I have commented on every change.

The altered Code:

<?php

include('login/conexao.php');
// Build an PDO Instance (Documentation: https://www.php.net/manual/en/book.pdo.php)
// $db = new PDO("mysql:host=localhost;dbname=test;charset=UTF8", "username", "password", [
//     PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
// ]);

$nome_cli = $_POST['nome_cli'];
$nome_orc = $_POST['nome_orc'];
$obs_trab = $_POST['obs_orc'];

$servico1 = $_POST['serv1'];
$obs_serv1 = $_POST['obs_serv1'];
$total1 = $_POST['total1'];

$servico2 = $_POST['serv2'];
$obs_serv2 = $_POST['obs_serv2'];
$total2 = $_POST['total2'];

$servico3 = $_POST['serv3'];
$obs_serv3 = $_POST['obs_serv3'];
$total3 = $_POST['total3'];

$servico4 = $_POST['serv4'];
$obs_serv4 = $_POST['obs_serv4'];
$total4 = $_POST['total4'];

$servico5 = $_POST['serv5'];
$obs_serv5 = $_POST['obs_serv5'];
$total5 = $_POST['total5'];

// switch from
// ($servico1 != '') to !empty($servico1)
// optional, if you like the syntax more, you could use: ($servico1 !== '')
// tripple equals or !== prevents type juggeling
// @see https://www.php.net/manual/en/language.types.type-juggling.php
if (!empty($servico1) && empty($servico2) && empty($servico3) && empty($servico4) && empty($servico5)) {
    // Prepared statment to prevent sqlinjection
    $stmt = $db->prepare("INSERT INTO TRABALHO (
            nome_trabalho,
            cod_cliente,
            obs_trabalho,
            statuspag_trabalho
        ) VALUES (
            :nome_orc,
            (SELECT cod_cliente FROM CLIENTE WHERE nome_cliente = :nome_cli ), -- with subselects we can remove unnecessary sql statments
            :obs_trab,
            0
        )
    ");

    try {
        // Execute the query and bind the named paraments
        // All variables a treated as string
        $stmt->execute([
            'nome_orc' => $nome_orc,
            'nome_cli' => $nome_cli,
            'obs_trab' => $obs_trab
        ]);
    } catch (Exception $e) {
        // @todo handle exception 
        echo $e->getMessage();
        exit;
    }


    $stmt = $db->prepare("INSERT INTO SERV_TRAB (
            cod_trabalho,
            cod_servicos,
            qtt_serv_trab,
            obs_serv_trab
        ) VALUES (
            :orc,
            (SELECT cod_servicos FROM SERVICOS WHERE descri_servicos = :servico1),
            $total1,
            :obs_serv1
        )
    ");

    try {
        // get last inserted id with pdo: $db->lastInsertId()
        $stmt->execute([
            'orc' => $db->lastInsertId(),
            'servico1' => $servico1,
            'obs_serv1' => $obs_serv1
        ]);
    } catch (Exception $e) {
        // @todo handle exception 
        echo $e->getMessage();
        exit;
    }

    // we don't need an if at this point because if an error occures it will throw an exception
    // and the try / catch will catch and handle it
    header('Location: sucesso_orc.php');
    exit;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM