So i wanted to make a little "search engine" for my database.
my javascript is:
$(document).ready(function () {
$("#display").click(function () {
var zoeknaam = $("#zoeknaam").val();
var zoektype = $("#zoektype").text();
$.ajax({ //create an ajax request to load_page.php
type: "POST",
url: "display.php",
data: { name: zoeknaam, zoekt: "name" },
dataType: "html", //expect html to be returned
success: function (response) {
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
my html is the following:
<input type="text" name="inputtext" id="zoeknaam" />
<select name="searchtype" id="zoektype"><option value="name">name</option><option value="age">age</option></select>
<input type="button" id="display" value="Display All Data" />
and now i have my php
include("connection.php");
$dataget = $_POST["name"];
$datawaar = $_POST["zoekt"];
$stmt = $conn->prepare("SELECT * FROM student WHERE :waar=:postname");
$stmt->bindParam(':waar', $datawaar, PDO::PARAM_STR);
$stmt->bindParam(':postname', $dataget, PDO::PARAM_STR);
$stmt->execute();
echo "<table>";
while($data = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "<tr>";
echo "<td align=center>$data[name]</td>";
echo "<td align=center>$data[address]</td>";
echo "<td align=center>$data[age]</td>";
echo "</tr>";
}
echo "</table>";
When i remove the where condition and set the condition to name it works. Now when i retrieve it with the post and param it doesn't work.
The connection.php is correct since it works with the condition.
This is wrong:
... WHERE :waar=:postname
You can only bind values using placeholders in a prepared statement, not column- or table names.
If you want to accept and use client-provided column- or table names, the only way to secure that, is to check them against a white-list and then inject them directly in the query string.
Related
Good day to everyone. So I am trying to get the value of a select option and getting a set of rows in MySql depending on the column name in the database. So here is the HTML code:
<html>
<body>
<select name = "FilterDoc" onchange = "filterby(this);">
<option disabled>Filter By</option>
<option value="document_type">Document Type</option>
<option value="date">Date</option>
<option value="hei">HEI</option>
<option value="other">Other Govt.</option>
<option value="person">Person</option>
</select>
<div class="panel-body" id="container">
</div>
Here is code for Ajax:
<script type="text/javascript">
function filterby(sel){
$.ajax({ //create an ajax request to display.php
type: "POST",
data: {FilterDoc: $(sel).val()},
url: "filterdocu.php",
dataType: "html", //expect html to be returned
success: function(response)
{
$("#responsecontainer").html(response);
}
console.log(reply);
});} </script>
Now the value of the select option will pass to the PHP file. I dont know if "if statement" is the right one for this since I haven't had that much background about getting values on html and such and I'm trying to find a better way to get the rows from MySql and display them into the container.
Here's the PHP code:
<?php echo"<div class='panel panel-primary' id='container'>";
if($_POST["FilterDoc"]=="document_type")
{
echo "<script type='text/javascript'>$('container').html('""');</script>";
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY document_type ASC");
while($data = json_encode(mysql_fetch_assoc($result))
{
echo json_encode($data);
}
}
else if($_POST["FilterDoc"]=="date")
{
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY date_received DESC");
echo "<script type='text/javascript'>$('container').html('""');</script>";
while($data = json_encode(mysql_fetch_assoc($result))
{
echo json_encode($data);
}
}
else if($_POST["FilterDoc"]=="hei")
{
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY hei ASC");
echo "<script type='text/javascript'>$('container').html('""');</script>";
while($data = json_encode(mysql_fetch_assoc($result))
($result))
{
echo json_encode($data);
}
}
else if($_POST["FilterDoc"]=="Other")
{
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY other_govt ASC");
echo "<script type='text/javascript'>$('container').html('""');</script>";
while($data = json_encode(mysql_fetch_assoc($result))
{
echo json_encode($data);
}
}
else if($_POST["FilterDoc"]=="Person")
{
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY contact_person ASC");
echo "<script type='text/javascript'>$('container').html('""');</script>";
while($data = json_encode(mysql_fetch_assoc($result))
{
echo json_encode($data);
}
}echo"</div>"; ?>
I'm also not entirely sure if using javascript to clear the container is the proper way before putting contents into the div container.
I would really appreciate your help. Thank you!
At first i would simplify the code like :
<?php
echo "<div class='panel panel-primary' id='container'>";
// Set Variable
$filter = $_POST["FilterDoc"]; // This needs proper escaping
$result = mysqli_query($conn,"SELECT * FROM records ORDER BY $filter ASC");
while($data = json_encode(mysql_fetch_assoc($result)) {
echo json_encode($data);
}
echo "</div>";
Thats the PHP part, now i would rewrite the javascript.
function filterby(sel) {
$.ajax({ //create an ajax request to display.php
type: "POST",
data: {
FilterDoc: $(sel).val()
},
url: "filterdocu.php",
dataType: "html", //expect html to be returned
success: function(response) {
$("#container").empty().html(response);
}
});
}
But maybe your whole filtering process may be inefficient. You could fetch all the data with one SQL call and do the filtering with JS / data-attributes.
I have 2 multiple select drop box.. form one I want to inflate the other multiple select drop box.. can anyone help me with this?
When I get result from the jQuery or ajax i want that result to display in 2nd number multiple select drop box...
this is my ajax..
function demo1() {
var emp_id = document.getElementById("employeeName").value;
alert(emp_id);
var datastring = "emp_id=" + emp_id;
//alert (emp_id);
$.ajax({
type: "POST",
url: "search_emp.php",
data: datastring,
dataType: "text",
//async: false,
success: function (data) {
//$("#clname").append(data);
$('#clname').html(data);
//document.getElementById("clname").innerHTML=data;
}
});
}
This are 2 multiple drop box..
<label>Select Employee </label>
<select multiple="multiple" class="w300" name="employeeName[]" id="employeeName" >
<?php $result = $conn->query("SELECT id,first_name,last_name,employee_id FROM employees");
while ($row = $result->fetch_assoc()){ ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['id']; ?><?php echo $row['first_name']; ?>
<?php echo $row['last_name'] ?></option>
<?php } ?>
<!--<?php echo $option;?>-->
<!--<?php echo $option2;?>-->
</select>
</br>
<label>Select Client</label>
<select multiple="multiple" class="w300" name="clname[]" id="clname">
<!--<?php echo $c;?>-->
</select>
.html() will set the innerHTML content of a DOM element, you can't do that on a <select>. There are two ways to solve it:
1) Quick & dirty: replace HTML
Make your search_emp.php also return the HTML code for the <select>, like this:
echo '<select multiple="multiple" class="w300" name="clname[]" id="clname">';
while($row = mysqli_fetch_assoc($ress)) {
echo '<option value="'.$row['gn_id'].'">'.$row['gamename'].'</option>';
}
echo '</select>';
Then you can use jQuery.replaceWith() to replace the whole DOM element:
$('#clname').replaceWith(data);
2) Much nicer: Build DOM from JSON
Instead of returning HTML code, your search_emp.php should return JSON, something like
[
{
"gn_id": "123",
"gamename": "superduper client"
},
{
"gn_id": "234",
"gamename": "another client"
}
]
You can easily do this by passing the client array to PHP's json_encode() and add a JSON content type header (Note that you will have to change the dataType attribute of $.ajax to "json" or you could use the shortcut function $.json():
// identify the content as JSON
header('Content-Type: application/json');
// put your MySQL query here.
// if errors occur, send a HTTP 500 header and return a useful error message as JSON
// collect results in an array
$rows = array();
while($row = mysqli_fetch_assoc($ress)) {
$rows[] = $row;
}
// return the results as a JSON list
echo json_encode($rows);
Before you make the AJAX call, you would want to remove all existing options from the select. In the success function of the AJAX call, you can loop through the results and append them to the select:
// reset the select options
$('#clname').empty();
// make the ajax call
$.ajax({
type: "POST",
url: "search_emp.php",
data: datastring,
dataType: "json",
success: function (data) {
// build the options from the JSON data
for (let client of data) {
$('#clname').append('<option value="' + client.gn_id + '">' + client.gamename + '</option>');
}
},
// optional, but good to have: error handling
error: function (data) {
alert("An error occurred:\n" + data.error)
}
});
jsfiddle
Note: let client of data only works in modern browsers (ES2015 compatible). If you want to support older browsers, do an old-fashioned for (len=data.length, i=0; i<len; ++i) loop. Or use jQuery.each() (although this might be slower)
I am trying to create a very basic auction page on a site I am working on. I'm sort of working it out as I go along but I am now a bit stuck.
Data is stored in a MySQL table, this data has the image link, the ID, and the current bid.
I then retrieve the data in PHP/HTML, example here:
$result = mysqli_query($con,"SELECT * From auction WHERE category = 'Bathroom' ORDER BY ID DESC");
while($row = mysqli_fetch_array($result))
{
echo "<form name='auction' id='auction'><div class='auction-thumb'>
<div class='auction-name'>" . $row['Item'] . "</div>";
echo "<img class='auction' src='" . $row['ImagePath'] . "' />";
echo "<div class='auction-bid'>Current Bid: £" . $row['CurrentBid'] . "</div>";
echo "<div class='auction-bid'>Your Name: <input type='text' class='bidder' name='bidname'/></div>";
echo "<div class='auction-bid'>Your Bid: <input type='text' class='auction-text' name='bid'/></div>";
echo "<div class='auction-bid'><button name='submit' id='submit' value='" . $row['ID'] . "' type='submit'>Place Bid!</button></div>";
echo "</div></form>";
}
echo "</table>";
This code pulls through the items absolutely fine. Along with a textbox for a name and a bid (I am not doing anything with the name at the moment).
My jQuery then looks like this:
$(document).ready(function(){
$('#auction').submit(function(){
var id = $('#submit').val();
var bidname = $('input[name=bidname]').val();
var bid = $('input[name=bid]').val();
$.ajax({
type: "POST",
url: "auction-handler.php",
dataType: "json",
data: {bidname: bidname, bid: bid, id: id},
success: function(){
}
});
return true;
});
});
Again this is very basic and I am not concerned about validation just yet.
And finally here is a snippet of my PHP code:
$bidname = $_POST['bidname'];
$bid = $_POST['bid'];
$id = $_POST['id'];
$query = "UPDATE auction SET CurrentBid = '$bid' WHERE ID = '$id'";
mysqli_query($con, $query) or die(mysqli_error());
mysqli_close($con);
My problem is that when I click submit, nothing really happens. All the variable names and values get put into the browser address bar, and the page just seems to refresh.
The data does not get posted and when I debug with Firebug, I just get a red cross and it doesn't give me any errors.
I know from just looking at my code that best practices aren't followed, but I just want to get something working and then tidy it up later.
If anyone could point me in the right direction that would be a big help.
Thank you, and if you need anymore information please just let me know.
First of all: You need to rewrite your form element every element should have an unique id to differentiate the respective element.
<?php while($row = mysqli_fetch_array($result)){ ?>
<form name='auction' id='auction<?php echo $row['ID'] ?>'>
<input type='hidden' name='id' value='<?php echo $row['ID'] ?>'>
<div class='auction-thumb'>
<div class='auction-name'><?php echo $row['Item'] ?></div>
<img class='auction' src='<?php echo $row['ImagePath'] ?>' />
<div class='auction-bid'>Current Bid: £<?php echo row['CurrentBid'] ?></div>
<div class='auction-bid'>Your Name: <input type='text' class='bidder' name='bidname'/></div>
<div class='auction-bid'>Your Bid: <input type='text' class='auction-text' name='bid'/></div>
<div class='auction-bid'>
<input type='submit' name='submit' value='Place Bid!'>
</div>
</div>
</form>
and replace your jquery code to
$(document).ready(function(){
$('form[name="auction"]').submit(function(){
var id = $(this).find('input[name="id"]').val();
var bidname = $(this).find('input[name="bidname"]').val();
var bid = $(this).('input[name="bid"]').val();
$.ajax({
type: "POST",
url: "auction-handler.php",
dataType: "json",
data: {bidname: bidname, bid: bid, id: id},
success: function(){
}
});
return false;
});
});
You need to re-write this a bit: ID's have to be unique and when you loop through your items you assign the same IDs over and over to elements in different forms.
So when you try to get the values in your submit handler, jQuery does not know which value to get (it probably gets the value of the first element with that ID).
You should start with changing the IDs to for example classes and then serialize (for example...) the submitted form - $(this) in your submit handler - to get the correct data.
Add following keys in ajax to trace the errors.
$.ajax({
url: "auction-handler.php",
type: "POST",
dataType: "json",
data: {bidname: bidname, bid: bid, id: id},
crossDomain:true,
success: function(result){ console.log(result); }
error: function(httpReq,status,exception){
alert("error - " +status+" "+exception);
}
});
I have a PHP snippet that generates a table and fills it, and adds a delete button at the end of each row.
while($row = mysql_fetch_array($result)){
$num=$row['id'];
echo "<td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['adress']."</td>";
echo "<td>".$row['phonenumber']."</td>";
echo "<td><form action='delete.php' method='post'><button type='submit' value=$num name='deleteId'>delete</button></form></td>";
echo "</tr>";
}
The delete.php file is this one :
<?php
$host="localhost";
$username="root";
$password="";
$db_name="students";
mysql_connect("$host", "$username", "$password");
mysql_select_db("$db_name");
$id = $_POST['deleteId'];
$sql="DELETE FROM students WHERE id='$id'";
$result=mysql_query($sql);
?>
I want to do this using Ajax asynchronously, ie. I don't want my page to refresh. Tried a million ways, yet it fails each time. Thanks in advance.
Instead of using a form, you need to write your own JavaScript to handle the server call. Here's one way to do it. Make your PHP look something like this:
while($row = mysql_fetch_array($result)){
$num=$row['id'];
echo "<td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['adress']."</td>";
echo "<td>".$row['phonenumber']."</td>";
echo "<td><button onclick="deleteStudent($num)">delete</button></td>";
echo "</tr>";
}
And then have a JS function that looks something like this:
function deleteStudent(studentId) {
$.ajax({
url: "delete.php",
method: 'post',
data: {
deleteId: studentId
}
});
}
Another way:
Firstly, assign a unique ID for each of the delete button.
while($row = mysql_fetch_array($result)){
$num = $row['id'];
echo "<td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['adress']."</td>";
echo "<td>".$row['phonenumber']."</td>";
echo "<td><button id='delete-" . $row['id'] . "'>delete</button></td>";
echo "</tr>";
}
Then use jQuery:
$('button[id^="delete"]').click(function () {
var id = $(this).attr('id').substr(6);
$.ajax({
type: "POST",
url: "delete.php",
data: {deleteId: id}
});
});
I want to insert the record using json into mysql and the system could display the new record without refreshing the page.
My code is shown as below:
Part 1, the script get two values from form and convert it into json, passing them to action.php
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var name = $("#name").val();
var dataString = {'content': textcontent, 'name': name};
if (textcontent == '') {
alert("Enter some text..");
$("#content").focus();
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
dataType: 'json',
cache: true,
success: function(html){
$("#show").html(html);
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
<div>
<?php
$conn=mysqli_connect('localhost','Practical4','1234') or die('Not connected');
$database=mysqli_select_db($conn,'Practical4') or die('Database Not connected');
$id=$_GET['id'];
$query = "select * from hotel where name='$id'";
$data=mysqli_query($conn,$query);
while($rows=mysqli_fetch_array($data)){
$name=$rows['name'];
$price=$rows['price'];
$duetime=$rows['dueTime'];
$address=$rows['location'];
}
?>
<form method="post" name="form" action="">
<h3>Add Comment for <?php echo $name;?><h3>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="text" name="name" id="name" value="<?php echo $name;?>" hidden > <br>
<input type="submit" value="Add Comment" name="submit" class="submit_button"/>
</form>
</div>
<?php
$host="localhost";
$username="Practical4";
$password="1234";
$db_name="Practical4";
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from comment where name='$name'";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_row($result)){
$json[] = $row[1];
}
}
mysql_close($con);
echo implode('<br />', $json);
?>
<div class="space" ></div>
<div id="flash"></div>
<div id="show" ></div>
Part2, action.php, which insert the record into mysql database.
<?php
$DBServer = 'localhost'; // e.g 'localhost' or '192.168.1.100'
$DBUser = 'Practical4';
$DBPass = '1234';
$DBName = 'Practical4';
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
// check connection
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
$v1="'" . $conn->real_escape_string($_POST['content']) . "'";
$v2="'" . $conn->real_escape_string($_POST['name']) . "'";
$sql="INSERT INTO comment (content,name) VALUES ($v1,$v2)";
if($conn->query($sql) === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$last_inserted_id = $conn->insert_id;
$affected_rows = $conn->affected_rows;
echo '<div class="showbox">'.$v1.'</div>';
}
?>
So far the code can insert new data, but it won't display the new record dynamically without refreshing page. Any idea to fix that?
Change your dataType to html since this parameter tells the server what kind of response it will accept in return:
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
dataType: 'html',
cache: true,
success: function(data){
$("#show").html(data);
$("#flash").hide();
$("#content").focus();
}
});
In the above case the return value should be plain html:
print '<div class="showbox">' . $v1 . '</div>';
You then add it to your page using:
$('#show').html(data);
If you still would like to use json you could encode your response using something like this:
print json_encode(array('html' => '<div class="showbox">' . $v1 . '</div>'));
Then you would need to parse this value:
$("#show").html(data.html);
In the above example it seems clearer to name the success functions argument to something like data since it won't contain just html in the case.