1

I have used this code on an autosuggest script to split the CSV created into 3 values in an array as such:

<?php if($_POST['category_submit']){ ?>
<script type="text/javascript">
$(document).ready(function() {
var arr = $(".as-values").val().split(",");
var category_1=arr[0];
var category_2=arr[1];
var category_3=arr[2];
});
</script>
<?php } ?>

I now want to add the 3 values within the 3 'var' into the MySQL database. What would be the steps necessary to do so?

1
  • 1
    Javascript does not run on the server side. It must send data to the server (to be parsed by PHP) using POST or GET (forms, AJAX, etc.). Commented Aug 5, 2011 at 18:42

3 Answers 3

2

You would have to use $.ajax to call a PHP insert script. Remember, if you're going to use PHP to insert, make sure you're using Prepared Statements

AJAX

$.post("phpscript.php", { 
    cat1: category_1,
    cat2: category_2,
    cat3: category_3,

});

PHP

$query = $mysqli->prepare("INSERT INTO table VALUES (?, ?, ?)");
$query->bind_param('sss', $val1, $val2, $val3); // get these from $_POST
$query->execute();
Sign up to request clarification or add additional context in comments.

5 Comments

Would $va1 not have to be $cat1?, would they not have to be binded before the query is executed also? and what is 'sss'.
Google prepared statements. 'sss' stands for strings. Meaning the values binding are going to be strings. I was thinking you would go $val1 = trim/stripslashes/etc $_POST['cat1']
Ah I see! Sorry I am new to all of this. I understand 'sss' now, how ever, they are going to be int(11) stored in the database, so would it be 'i', for int? with the code you put above, would this be advisable to go in the phpscript.php shown above? and preferably before the $query->bind_param?. Many thanks.
I also have other fields within the table I would like to update, with the code provided, (?, ?, ?) Can I use an update query instead? Many thanks.
Sorry, was off for the weekend. yes, iii would be your replacement. $.post has to be in the javascript and separate from the PHP and yes, (?,?,?) this works for everything. just replace the value with a ?
0

Use ajax to post these 3 values and write a code on the server side page to insert into DB.

Jquery AJAX

Comments

0
Array.prototype.sum = function(){
 for(var i=0,sum=0;i<this.length;sum+=this[i++]);
 return sum;
}

$(document).ready(function() {
 var arr = $(".as-values").val().split(",");
 $.post('something.php', {'sum':arr.sum()}, function() {
   //callback success code here
 });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.