简体   繁体   中英

save text fields into MySQL database

@Edit 2 ,

I think the problem stems from passing arguments.

<br />
<b>Warning</b>:  mysqli_connect(): (HY000/2002): Connection refused in <b>/opt/lampp/htdocs/ch1/saveEmail.php</b> on line <b>12</b><br />
Failed to connect to MySQL: Connection refused<br />
<b>Warning</b>:  mysqli_query() expects parameter 1 to be mysqli, bool given in <b>/opt/lampp/htdocs/ch1/saveEmail.php</b> on line <b>30</b><br />
<br />
<b>Warning</b>:  mysqli_close() expects parameter 1 to be mysqli, bool given in <b>/opt/lampp/htdocs/ch1/saveEmail.php</b> on line <b>41</b><br />

@Edit , if I disable doRecord method and assign a random number to $retVal , I can see its value from the console. I think the problem is about the function's body.


I'm trying to save information which is put by the fields into MySQL database. But I cannot see even what the result is by exit(json_encode(array("response" => $response))); or exit(json_encode(array("response" => "not entered"))); . I'm sure database works, I tested. Also, button onclick works, but no more. What's the wrong?

saveEmail.php

<?php


function doRecord($host, $username, $password, $dbName,
                  $senderName, $senderMail, $senderSubject, $senderBody, $cronInput) {

    $retVal = 0;
    /* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
    $link = new mysqli($host, $username, $password, $dbName);

// Check connection
    if($link === false){
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }

    $date = gmdate('Y-m-d h:i:s', time());
    /*$htmlBody =
        "bodyy <p><a href=\"http://sdfdsf.com/\" target=\"_blank\" rel=\"noopener\">link burada</a>&nbsp;</p>
    <p>&nbsp;</p>
    <p>fdgfd</p>";
    */


// Attempt insert query execution
    $sql = "INSERT INTO  staj.info(name, email, subject, body, progressTime, cronInput)
            VALUES
    ('$senderName', '$senderMail', '$senderSubject', '$senderBody', '$date', '$cronInput');";


    if(mysqli_query($link, $sql)){
        //echo "Records inserted successfully.";
        $retVal = 1;
    } else{
        //echo "\n\nERROR: Could not able to execute $sql. " . mysqli_error($link);
        $retVal = 0;
    }



// Close connection
    mysqli_close($link);
    return $retVal;
}

if (isset($_POST['cron'])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $subject = $_POST['subject'];
    $body = $_POST['body'];
    $cron = $_POST['cron'];



    $retVal = doRecord("127.0.0.1", "root", "12345678", "staj",
        $name, $email, $subject, $body, $cron);



    if ($retVal == 1) {
        $response = "Mail is put into database";
    } else {
        $response = "SQL error.";
    }
    exit(json_encode(array("response" => $response)));
} else {
    exit(json_encode(array("response" => "not entered")));
}


?>

index.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
    <link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.12/summernote.css" rel="stylesheet">

    <style type="text/css">
        textarea, input {
            margin-bottom: 10px;
        }

    </style>

</head>
<body>
    <div class="container" style="margin-top:100px;">
        <div class="row justify-content-center">
            <div class="col-md-6 col-md-offset-3">
                <label for="name">Name:</label>
                <input id="name" placeholder="Name" class="form-control" required>

                <label for="email">E-mail:</label>
                <input id="email" placeholder="E-mail" class="form-control" required>

                <label for="subject">Subject:</label>
                <input id="subject" placeholder="Name" class="form-control" required>

                <!--<label for="body">Body:</label>-->
                <textarea id="summernote" placeholder="Email body" name="editordata"></textarea>


                <label for="cron">Crontab:</label>
                <input id="cron" placeholder="CronTab Input" class="form-control">

                <input type="button" onclick="saveMail()" value="Save it to Database" class="btn btn-success btn-info">
            </div>
        </div>
    </div>


<script
        src="https://code.jquery.com/jquery-3.4.1.js"
        integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
        crossorigin="anonymous"></script>

<script type="text/javascript">
    function isNotEmpty(caller) {
        if (caller.val() == "") {
            caller.css('border', '1px solid red');
            return false;
        } else {
            caller.css('border', '');
            return true;
        }
    }

    function saveMail() {
        console.log("SaVinG Attempt...");
        var name = $("#name");
        var email = $("#email");
        var subject = $("#subject");
        var body = $("#summernote");
        var cron = $("#cron");

        if (isNotEmpty(cron)) {
            $.ajax({
                url: 'saveEmail.php',
                method: 'POST',
                dataType: 'json',
                data: {
                    name: name.val(),
                    email: email.val(),
                    subject: subject.val(),
                    body: body.val(),
                    cron: cron.val()
                }, success: function (response) {
                    console.log(response);
                }
            });
        }
    }   
</script>

<!-- WYSIWYG editor jses -->
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.12/summernote.js"></script>
<script>
    $(document).ready(function() {
        $('#summernote').summernote({
            height: 300,
            focus: true
        });
    });
</script>
</body>
</html>

It seems like you have an incorrect quotation mark in your saveEmail.php file. If you use code highlighting, it's easier to see. Instead of:

exit(json_encode(array("response" => "not entered”)));

Try:

exit(json_encode(array("response" => "not entered")));

EDIT:

To see what kind of error blocks your AJAX call, put these lines of call at the beginning of saveEmail.php:

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

Then temporarily change your ajax call to look like this:

$.ajax({
url: 'saveEmail.php',
method: 'POST',
data: {
    name: name.val(),
    email: email.val(),
    subject: subject.val(),
    body: body.val(),
    cron: cron.val()
}, success: function (response) {
   console.log(response);
} });

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