简体   繁体   English

使用ajax和php更新数据库行

[英]Updating database rows using ajax and php

I'm pretty new to php and jQuery. 我是php和jQuery的新手。 I've searched the net hi and low for an answer to no avail. 我已经在网上查询了高低价,但都无济于事。 I'm attempting to "post" an edit form that submits to itself using ajax and php. 我正在尝试“发布”使用ajax和php提交给自己的编辑表单。 I'm able to return the values back to my form from the ajax.php. 我可以从ajax.php返回值回到我的表单。 I'm also able to see them once they've posted, but the UPDATE query doesn't seem to be working. 将它们发布后,我也可以看到它们,但是UPDATE查询似乎不起作用。 I'm not using ajax for anything other than getting values from a select. 除了从选择中获取值外,我没有将ajax用于其他任何事情。 Something is hairy somewhere and I can't quite figure out where. 某处有些毛毛,我不知道该在哪里。 I'm not too sure about my code either, but what I have seems to work up to/around the update query. 我也不是很确定我的代码,但是我似乎可以解决更新查询。 Any help is much appreciated. 任何帮助深表感谢。

Here's my html, ajax call is at the bottom: 这是我的html,ajax调用位于底部:

<?php //require_once("_includes/session.php"); ?>
<?php require_once("_includes/connection.php"); ?>
<?php require_once("_includes/functions.php"); ?>
<?php //confirm_logged_in(); ?>
<?php include("_includes/header.php"); ?>
<?php
if(isset($_POST['submit'])) {
    //$id = $_POST['postid'];
    //$title = $_POST['title'];
    //$content = $_POST['content'];
    //printf($id);
    //printf($title);
    //printf($content);
    $errors = array();

    // Form Validation
    $required_fields = array('title', 'content');
    foreach($required_fields as $fieldname) {
        if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && !is_numeric($_POST[$fieldname]))) {
            $errors[] = $fieldname;
        }
    }

    $fields_with_lengths = array('title' => 50);
    foreach($fields_with_lengths as $fieldname => $maxlength ) {
        if (strlen(trim(mysql_prep($_POST[$fieldname]))) > $maxlength) { $errors[] = $fieldname; }
    }

    if (empty($errors)) {
        // Perform Update
        $id = mysql_prep($_POST['postid']);
        $title = mysql_prep($_POST['title']); 
        $content = mysql_prep($_POST['content']);

        $query = "UPDATE posts SET
                    title = '{$title}',
                    content = '{$content}',
                WHERE id = {$id}";
        $result = mysqli_query($connection, $query);
        if (mysqli_affected_rows($connection) == 1) {
            // Success
            $message = "The post was successfully updated.";
        } else {
            // Failed
            $message = "The subject update failed.";
            $message .= "<br>" . mysqli_error($connection);
        }

    } else {
        // Errors occurred
        if (count($errors) == 1) {
            $message = "There was " . count($errors) . " error in the form.";
        } else {
            $message = "There were " . count($errors) . " errors in the form.";
        }
    }

} // End: if(isset($_POST['submit']))
?>

<section id="manageContent">
<a href="manage.php">&lt&lt Back</a>

<h2>Edit Blog Post</h2>

<form id="newPost" name="newpost" action="edit_post.php" method="post">

<label for="posttitle">Select post title to edit:</label>

<select id="titleName" name="titleName">
    <?php
    $post_set = get_all_posts();
    while ($post = mysqli_fetch_array($post_set)) {
        echo '<option value="' . htmlspecialchars($post['id']) . '">'
            . htmlspecialchars($post['title'])
            . "</option>";
    }
    ?>
</select>

<p><label for="id">id:</label> <input id="postid" name="postid" type="text"></p>

<p><label for="title">Title:</label> <input id="title" name="title" type="text" required> (max length: 50 characters)</p>

<p><b>IMPORTANT!! things to remember so content is displayed how you would like:</b></p>
<ul>
    <li>You can use &ltp&gt, &ltdiv&gt, &ltul&gt, &ltol&gt, &ltli&gt tags in your blog posts.</li>
    <li>Insert the <b>&ltjumpbreak&gt</b> tag where you would like content to stop displaying on the main blog page.</li>
    <li>Enclose all remaining content after the <b>&ltjumpbreak&gt</b> in a <b>&ltdiv class="hideAfterJumpBreak"&gt&lt/div&gt</b> tag pair. This will keep all content after the <b>&ltjumpbreak&gt</b> from displaying on the main blog page until the topic is displayed on the topic.php page.</li>
    <li>Double check that every opening tag has a closing tag.</li>
</ul>

<p><label for="content">Content:</label></p>

<p><textarea id="content" name="content"></textarea></p>

<!--<p><button type="submit" name="submit">Edit Post</button></p> -->
<input id="submit" type="submit" name="submit" value="Edit Post">

<a href="edit_post.php"><button name="cancel">Cancel</button></a>
<a href="delete_post.php"><button name="delete">Delete</button></a>
</form>

<script>
(function() {

$("select#titleName").prop("selectedIndex", -1);

// returns a single item from php
/*
$("select#title").on("change", function() {
    var post_id = this.value;
    console.log(this);
    $.ajax ({
        url: "_includes/ajax.php",
        type: "POST",
        data: {post_id : post_id},
        dataType: "text",
        success: function(response) {
            $( "input#title" ).val(response);
        },
        failure: function() {
            alert("fail");
        }
    }); 
});
*/

$("select#titleName").on("change", function() {
    var post_id = this.value;
    console.log(this);
    $.ajax ({
        url: "_includes/ajax.php",
        type: "POST",
        data: {post_id : post_id},
        dataType: "json",
        success: function(response) {
            $( "input#postid" ).val(response.post_id);
            $( "input#title" ).val(response.post_title);
            $( "textarea#content" ).val(response.post_content);
        },
        failure: function() {
            alert("fail");
        }
    }); 
});

})();
</script>
</section>

<?php include("_includes/footer.php"); ?>

And here is my ajax.php: 这是我的ajax.php:

<?php require_once("connection.php"); ?>
<?php require_once("functions.php"); ?>
<?php include_once("form_functions.php"); ?>
<?php
//if(isset($_POST['title'])) {
    //$post_id = $_POST['post_id'];
    //$query = "SELECT title, content
    //       FROM posts 
    //       WHERE id = '$post_id'";
    //$result = mysqli_query($connection, $query);
    //$row = mysqli_fetch_array($result);
    //echo $row['title'], $row['content'];
//}
    $post_id = $_POST['post_id'];
    $query = "SELECT *
             FROM posts 
             WHERE id = '$post_id'";
    $result = mysqli_query($connection, $query);
    $row = mysqli_fetch_array($result);
    echo json_encode(
        array("post_id" => $row['id'], 
        "post_title" => $row['title'],
        "post_content" => $row['content'])
    )

    //echo $row['title'], $row['content'];
?>


<?php mysqli_close($connection); ?>

Figured it out, in my UPDATE posts SET I had a comma after my second row update. 弄清楚了,在我的UPDATE帖子集中,第二行更新后出现了逗号。 Thank you all for the suggested readings as well. 谢谢大家的建议阅读。

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

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