I'm trying to build a custom query from Ajax
to PHP/MySQL
considering the following.
Javascript code:
var i=2;
fetchFromDBPHP("name", "tblperson", "id="+i);
function fetchFromDBPHP(column, table, condition) {
$.ajax({
type: "post",
url: "./php/fetchFromDB.php",
dataType: 'json',
data: { column: column, table: table, condition: condition },
success: function(data) {
console.log("Fetched data from PHP:" + data);
},
error:function(request, status, error) {
console.log("Reading PHP database went wrong. Error " + request.responseText);
}
});
}
PHP code:
<?php
$column = $_POST['column'];
$table = $_POST['table'];
$condition = $_POST['condition'];
if (isset($table)) {
$sql = "SELECT " . intval($_POST['column']) . " FROM " . intval($_POST['table']) . " WHERE " . intval($_POST['condition']);
$con = mysqli_connect("localhost", "root", "bloh", "blah");
if (!$con) {
die("Connection failed: " . mysqli_error($con));
}
$result = mysqli_query($con, $sql);
$to_encode = array();
while($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
$to_encode[] = $row;
}
echo json_encode($to_encode);
mysqli_close($con);
}
?>
My table may be similar as that:
Table tblperson
:
id name firstname tel
1 Dalton Jack 555-5555
2 Smith John 555-6666
3 Doe John 555-7777
What I would like to do is to send a query similar to
SELECT something FROM mytable WHERE condition=that
with Ajax. I have an error message, and nothing is retrieved.