How to insert php ajax textbox value into mysql database table?

90

I have ajax call in my index page, when the user enter a username into the text box it's need to insert into a mysql db table,can't find a way to do it?

This is my code

$(document).ready(function () {
$('#enter_email_id').change(function () {  
var str = $('#enter_email_id').val();
var webFormURL = "get_acc_info.php?q=" + str;
    $.ajax({
    url: webFormURL,
    async: false,
   success: function (response) {
    $('.test_acc').html(response);
}   
}); 

This is insert db php page

<?php
session_start();

$_SESSION["username"];

function insert_Details(){
    include 'Db_Connection.php';

    $sql="INSERT INTO search(searcher,searched_time,searched_email)
    VALUES('$_SESSION[username]',".NOW().",'$_POST[searched_email]')";
} 
?>
277

Answer

Solution:

for security reasons you should usemysqli_real_escape_string() for input values. I've got to fix your code, but you should replace$_SESSION["username"] value with what you want, use this code:

JavaScript:

$(document).ready(function () {
$('#enter_email_id').change(function () {  
var str = $('#enter_email_id').val();
var webFormURL = "get_acc_info.php?q=" + str;
    $.ajax({
    type: 'post',
    url: webFormURL,
    async: false,
   success: function (response) {
    $('.test_acc').html(response);
}   
}); 

PHP:

$_SESSION["username"] = 'test_username';

function insert_Details(){
    //create mysqli connection
    include 'Db_Connection.php';

    $string = mysqli_real_escape_string($mysqli_link,$_POST[searched_email]);
    $session = mysqli_real_escape_string($mysqli_link,$_SESSION[username]);
    $sql="INSERT INTO search(searcher,searched_time,searched_email)
    VALUES('$session',NOW(),'$string')";

  if(mysqli_query($mysqli_link,$sql) ) {
   echo "OK";
  }
} 
?>

People are also looking for solutions to the problem: php - MySQL Fields alternative to 'is_active', 'is_banned' flags?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.