I was looking through some code on a project of mine and thinking about all the php pages that I call with ajax that just run a simple update or insert query and it made me think. What if I could essentially run an insert or update sql query from javascript.
assuming I am using the prototype javascript framework for ajax and php on the server side.
would this work?
js:
<script type="text/javascript">
// table is string containing table name
// fields is an array of field names
// values is an array of values
function mysql_insert(table,fields,values) {
var sql = "INSERT INTO " + table + "(";
for(i=0; i<fields.length; i++) {
sql = sql + "`"+fields[i]+"`";
}
sql = sql + ") VALUES (";
// purposefully used fields array in for loop so we get matching number of values
for(i=0; i < fields.length; i++) {
sql = sql + "'"+values[i]+"'";
}
sql = sql + ");";
var par = 'query='+sql;
var ajax = new Ajax.Request('sql.php',{method:'post',parameters:par,onComplete:function(res) { }});
}
</script>
php:
<?php
include('db.php'); // connect to the mysql server and select database
mysql_query($_POST['query']);
?>
Obviously this is a simple example, just interested to know if this would work and I could replace the lot of small php pages that are each running a separate query?