单击php,ajax,mysql创建一个新的表行/用户

The html, and clicking the create div would redirect to an identical page, but would add a new row and increment the [text_edit_id] in the database. This is my table: http://imgur.com/KoNg1ju

<div class="saveChange" onclick="saveEdits()"></div>
<div class="cancelChange" onclick="cancelEdits()"></div>
<div class="create"></div>

<div id="edit" class="title textEditor">
    <span contenteditable="true" class="pageTitle one editable" id="bodyTitle"><?php echo $row['text_title']; ?></span>
    <p id="bodyText" class="editable" contenteditable="true"><?php echo $row['text_text']; ?></p>
</div>

When you save a change

function saveEdits() {
var title = $('.pageTitle').html();
var text = $('#bodyText').html();
    console.log(title + text);
    $.ajax({
      type: "POST",
      url: "functions/functions.php",
      data: { title: title, text: text }
    }).done(function( msg ) {
        console.log(msg);
    });
};

the functions.php

<?php 
$host = "localhost";
$username = "root";
$password = "root";
$db = "textedit";

$connection = mysqli_connect($host,$username,$password,$db);
if (!$connection) {
    die("Database connection failed: " . mysql_error());
}

$text_title = $_POST['title'];
$text_text = $_POST['text'];

$stmt = $connection->prepare("UPDATE data SET text_title = ?, text_text = ? WHERE text_edit_id = 1");
$stmt->bind_param('ss', $text_title, $text_text);
$stmt->execute();
?>

If you managed to add new records in your mysql database, but the problem is that you want the field "text_edit_id" to increment automatically... then the solution is very simple:

In phpmyadmin define the "text_edit_id" as described:

  • type integer
  • autoincrement (flag the checkbox - this option must be selected)

Text_edit_id should be the "primary key" of the table.

You can modify all these parameters in the "structure" section of your table. It's very easy.

This way, when you save a new record into the database, the "text_edit_id" value will be generated automatically and will be equal to "last value +1".

text_edit_id    text_title    text_text
     1          First news   News content
     2          Second news  Other content

IMPORTANT Note that if you want to ADD a new row in your table (like shown above) your query is wrong.

  $stmt = $connection->prepare("UPDATE data SET text_title = ?, text_text = ? WHERE text_edit_id = 1");

This means: "Update the table record where "text_id_field" equlas to 1 with the new values for "text_title" and "text_text". Of course the text_edit_id isn't changed!!

What you are looking for is the INSERT STATMENT. This way, each time a NEW line (= a new record) will be created with an autoincrementing index.

$stmt = $connection->prepare("INSERT INTO data (text_title, text_text) VALUES (?,?) ");

Substitute this line to the one in your script.