skip to Main Content

The code below displays a message after typing a value into the field

Poprawnie zapisano: - but without this value

Also does not write anything to the database. Did I make a mistake somewhere?

HTML file

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>

        <input type="text" id="wartosc" placeholder="Wartość do zapisania">
        <button id="zapiszBtn">Zapisz do bazy danych</button>


        <script>
            $(document).ready(function(){
                $("#zapiszBtn").click(function(){
                    var wartosc = $("#wartosc").val();
                    $.ajax({
                        url: "zapisz.php",
                        type: "POST",
                        data: wartosc,
                        success: function(wartosc){
                            alert("Poprawnie zapisano: " + wartosc);
                        }
                    });
                });
            });
        </script>
</body>

ZAPISZ.php

<?php

$sname= "localhost";
$unmae= "root";
$password = "root";

$db_name = "vote2";

$conn = mysqli_connect($sname, $unmae, $password, $db_name);

if (!$conn) {
    echo "Połączenie się nie powiodło!";
}

// Uzyskanie wartości z AJAX
if(isset($_POST['wartosc'])){

    $wartosc = $_POST['wartosc'];

    // Wstawienie wartości do bazy danych
    $stmt = $pdo->prepare("INSERT INTO 'test' ('r1') VALUES ('$wartosc')");
    $result = mysql_query($stmt);


    if($result) {
        echo "Wartość została pomyślnie zapisana do bazy danych.";
        } else {
            echo "Wystąpił błąd podczas zapisywania wartości do bazy danych.";
        }
}

?>

I would like the value I enter in the field to be saved in the database

2

Answers


  1. You’re using mysqli_connect() to establish a connection, but then you’re trying to prepare a statement using $pdo->prepare(). You should use either mysqli functions throughout or PDO functions throughout, but not mix them.

    <input type="text" id="wartosc" placeholder="Wartość do zapisania"/>
    <button id="zapiszBtn">Zapisz do bazy danych</button>
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
    $(document).ready(function(){
        $("#zapiszBtn").click(function(){
            var wartosc = $("#wartosc").val();
            $.ajax({
                url: "zapisz.php",
                type: "POST",
                data: { wartosc: wartosc }, // Send data as an object
                success: function(response){
                    alert(response);
                }
            });
        });
    });
    </script>
    

    PHP (zapisz.php):

    <?php
    $sname= "localhost";
    $unmae= "root";
    $password = "root";
    $db_name = "vote2";
    
    $conn = mysqli_connect($sname, $unmae, $password, $db_name);
    
    if (!$conn) {
    echo "Połączenie się nie powiodło!";
    }
    
    if(isset($_POST['wartosc'])){
    $wartosc = $_POST['wartosc'];
    
    // Prepare and execute statement
    $stmt = $conn->prepare("INSERT INTO test (r1) VALUES (?)");
    $stmt->bind_param("s", $wartosc);
    if ($stmt->execute()) {
        echo "Wartość została pomyślnie zapisana do bazy danych.";
    } else {
        echo "Wystąpił błąd podczas zapisywania wartości do bazy danych.";
    }
    $stmt->close();
    }
    $conn->close();
    ?>
    

    This code should properly insert the value into your database and display the appropriate success or error message.

    Login or Signup to reply.
  2. You are not sending the data correctly. You need data: { wartosc: wartosc } otherwise $_POST["wartosc"] won’t find anything – the parameter you send must have a name, not just a value.

    Also you’re using mysqli_connect() to establish a connection database with a variable called $conn, but then you’re trying to prepare a statement using a variable $pdo which doesn’t exist, and then finally executing the query using mysql_query which ia function that (since PHP 7) also doesn’t exist (and never accepted a statement object as input when it did excist). I suggest you go back and look at tutorials and examples of this process a bit more carefully.

    All of this should have produced errors and warnings in your PHP code, which ought to be visible in the response you are viewing with alert – if they’re not, you should enable PHP error reporting while doing development. And you don’t need to check for mysqli errors manually – mysqli report mode should be enabled, to allow it to throw them automatically.

    Here’s an improved version of the code:

    <input type="text" id="wartosc" placeholder="Wartość do zapisania"/>
    <button id="zapiszBtn">Zapisz do bazy danych</button>
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
    $(document).ready(function(){
        $("#zapiszBtn").click(function(){
            var wartosc = $("#wartosc").val();
            $.ajax({
                url: "zapisz.php",
                type: "POST",
                data: { wartosc: wartosc }, // Send data as an object
                success: function(response){
                    alert(response);
                }
            });
        });
    });
    </script>
    

    PHP (zapisz.php):

    <?php
    $sname= "localhost";
    $unmae= "root";
    $password = "root";
    $db_name = "vote2";
    
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $conn = mysqli_connect($sname, $unmae, $password, $db_name);
    
    if(isset($_POST['wartosc']))
    {
      $wartosc = $_POST['wartosc'];
    
      // Prepare and execute statement
      $stmt = $conn->prepare("INSERT INTO test (r1) VALUES (?)");
      $stmt->execute([$wartosc]);
    
      echo "Wartość została pomyślnie zapisana do bazy danych.";
      $stmt->close();
    }
    ?>
    

    This code should properly insert the value into your database and display the appropriate success or error message.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search