简体   繁体   English

数据未通过 PHP 表单保存在数据库中

[英]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;我试图在我的数据库中保存一些数据,但它只是不保存,没有抛出错误,我使用了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.查看表单输入的数据是否有效,并且一切正常,表单最多可以输入 5 个服务($servicoN),所以 cod 有点重复,因为我是 php 和 mySql 的新手,希望看到一些新手编码。 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: ...我还验证了选择使用 if 语句的逻辑也工作正常,所以我将只发布一个服务的案例:...

<?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. ...我正在使用 myawardspace 来托管我的项目,并且已经将表的引擎设置为 InnoDB,据我所知,它可以支持 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).问题 1:脚本未能产生预期结果(即您提出的问题)。 PROBLEM 2: Lack of diagnostic information.问题 2:缺乏诊断信息。

To solve problem 2, put the following three lines at the start of your script:要解决问题 2,请将以下三行放在脚本的开头:

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,例如:

<?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.如果这不会产生任何错误消息,则意味着 php 或 Web 服务器(例如 Apache)配置中的某些内容阻止了它们。 Find error logs for php and and the web server (probably apache).查找 php 和 web 服务器(可能是 apache)的错误日志。 Exact details for accessing logs are available myawardspace.访问日志的确切详细信息可在 myawardspace 中获得。

SOLVING PROBLEM 1 - Your Script解决问题 1 - 您的脚本

Whenever running sql through php, there are two major steps involved in getting it to work.每当通过 php 运行 sql 时,需要两个主要步骤才能使其工作。

STEP 1: Verify the sql is valid. STEP 1:验证sql是否有效。

The first shot at forming sql within a php script very often contains errors.在 php 脚本中形成 sql 的第一个镜头经常包含错误。 That means an important milestone in the development of every php script interacting with a database is verifying the sql outside php.这意味着开发与数据库交互的每个 php 脚本的一个重要里程碑是在 php 之外验证 sql。 An easy way to do this is to put the following statement immediately after setting the value of query_orc1:一种简单的方法是在设置 query_orc1 的值后立即放置以下语句:

echo query_orc1;
exit;

This will put onto your screen the sql the script is attempting to running.这会将脚本试图运行的 sql 显示在您的屏幕上。 Use copy/paste to run the sql using phpmyadmin or whatever interface you have for your database.使用复制/粘贴使用 phpmyadmin 或您的数据库的任何接口运行 sql。 If there are problems with the sql, you will see them here.如果sql有问题,你会在这里看到它们。 If the sql runs as expected, then you know the part of your script creating the sql is working.如果 sql 按预期运行,那么您就知道创建 sql 的脚本部分正在运行。

STEP 2: Fix php errors that are failing to submit sql correctly to the database. STEP 2:修复无法正确提交sql到数据库的php错误。

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.在尝试对 php.ini 进行故障排除之前,我会专注于让您的系统向您显示错误消息。

I have no experience with mysqli, therefore I use PDO.我没有使用 mysqli 的经验,因此我使用 PDO。

At first: Maybe you should overthink the first part with servico1 to servico5.起初:也许你应该过度考虑 servico1 到 servico5 的第一部分。 There is maybe a better solution.也许有更好的解决方案。

My Changes:我的变化:

  • Switch from mysqli to PDO从 mysqli 切换到 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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