I am trying to select multiple columns with concat an put the returned data into one textbox.
I think there is something wrong with my definition for the variables. But I could not figured out what is wrong. Here are the variables:
$id = isset($_POST['id'])?$_POST['id']:'';
$name = isset($_POST['firstname'])?$_POST['firstname']:'';
$name .= isset($_POST['insertion'])?$_POST['insertion']:'';
$name .= isset($_POST['lastname'])?$_POST['lastname']:'';
When I define just one variable for $name the script works. But that is not what I want.
Does someone know what is wrong?
Here is the other part of my script.
First I have a textbox. The data needs to be send to this textbox:
<input type="text" class="form-control" id="name" name="name" placeholder="Name">
The button calls sends '5' as the ID and runs the script getName():
<button type="button" rel="5" onclick="getName();"
<script type="text/javascript">
$('body').on('click', '.selectClass', function () {
var id = $(this).attr('rel');
$("#id").val(id);
modal.style.display = "none";
});
</script>
After clicking on the button the id is deployed here:
<input type="text" class="form-control" id="id" name="id">
The onClick event runs the following script:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getName(value) { // Do an Ajax request to retrieve the product price
console.log("getName before ajax", jQuery('#id').val());
jQuery.ajax({
url: './get/getname5.php',
method: 'POST',
data: {'id' : jQuery('#id').val()},
success: function(response){
console.log("getName after ajax", jQuery('#id').val());
jQuery('#name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
The jquery script calls the PHP, which is not working with the multiple variables for $name
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
$conn = new mysqli($servername, $username, $password, $dbname) ;
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error) ;
}else {
$id = isset($_POST['id'])?$_POST['id']:'';
$name = isset($_POST['firstname'])?$_POST['firstname']:'';
$name .= isset($_POST['insertion'])?$_POST['insertion']:'';
$name .= isset($_POST['lastname'])?$_POST['lastname']:'';
$query = 'SELECT concat(firstname, ' ', insertion, ' ', lastname) as name FROM users WHERE id="' . mysqli_real_escape_string($conn, $id) . '"';
$res = mysqli_query($conn, $query) ;
if (mysqli_num_rows($res) > 0) {
$result = mysqli_fetch_assoc($res) ;
echo $result['name'];
}else{
$result = mysqli_fetch_assoc($res) ;
echo $result['name'];
}
}
?>
Related
I m having a bit of trouble while validating value in database.
This is my html and js Code:
<input type="text" name="Unieke-voucher" value="" size="40" maxlength="8" minlength="8" id="voucher" aria-required="true" aria-invalid="false" placeholder="XYZ 1234">
var searchTimeout; //Timer to wait a little before fetching the data
jQuery("#voucher").keyup(function() {
vCode = this.value;
clearTimeout(searchTimeout);
searchTimeout = setTimeout(function() {
getUsers(vCode);
}, 400); //If the key isn't pressed 400 ms, we fetch the data
});
var searchTimeout; //Timer to wait a little before fetching the data
jQuery("#voucher").keyup(function() {
vCode = this.value;
clearTimeout(searchTimeout);
searchTimeout = setTimeout(function() {
getUsers(vCode);
}, 400); //If the key isn't pressed 400 ms, we fetch the data
});
function getUsers(vCode) {
jQuery.ajax({
url: 'voucher.php',
type: 'GET',
dataType: 'json',
data: {value: vCode},
success: function(data) {
if(data.status) {
jQuery("#codeError").html('');
console.log(data);
} else {
jQuery("#codeError").html('Value not found');
}
console.log(data);
}
});
}
With this getting value with keyup event and sending to php script till here working fine.
And this is php script:
$dbname = "voucher";
$dbuser = "root";
$dbpass = "root";
$dbhost = "localhost";
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$voucherCode = $_GET['VoucherCode'];
$voucherCode['status'] = false;
//echo $voucherCode;
$result = mysqli_query($conn, "SELECT * FROM VoucherCode WHERE `code` LIKE '$voucherCode' LIMIT 1");
if(mysqli_num_rows($result)) {
$userData = mysqli_fetch_assoc($result);
$voucherCode['code'] = $Code;
$voucherCode['status'] = true;
}
echo json_encode($voucherCode);
I am always getting status value even providing correct value.
When i print_r table like
$resultAll = mysqli_query($conn, "SELECT * FROM VoucherCode");
$data2 = mysqli_fetch_all($resultAll);
print_r($data2);
I am able to see all data is there.
I am not sure what i am doing wrong here. Can anyone help me with this please.
Thanks in advance.
I have created a html page that ask to enter quantity of items to buy and the total quantity will be calculated. I am able to send the values of the quantity of EACH item to the database since they are text field but I am not able to send the paragraph (innerHTML) value into database. How am I able to solve this please?
This is the HTML code.
<body>
<form id="Orders" method = "POST"/>
Shirts ($1 Each) :
<input id="Shirts" type="text" name="Shirts" value=""/>
Pants ($2 Each) :
<input id="Pants" type="text" name="Pants" value=""/>
Quantity:
<p id="quantity" name ="quantity" value=""/></p>
<input type="submit" class="button" id="submit" value="Order"/>
<script>
$('#submit').on('click',function(e){
$.ajax({
type: "POST",
url: 'orders.php',
data: $("#Orders").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
</script>
This is the javascript.
var Shirts = document.getElementById("Shirts").value;
var Pants = document.getElementById("Pants").value;
var Quantity = +Shirts + +Pants;
document.getElementById("quantity").innerHTML=Quantity;
This is the php code
<?php
$servername = "localhost";
$username = "Hello";
$password = "Test";
$dbname = "Test";
if(isset($_POST["Shirts"]) && isset($_POST["Pants"]) && isset($_POST ["quantity"]))
{
$shirts = $_POST["Shirts"];
$pants = $_POST["Pants"];
$quantity = $_POST["quantity"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Test (Shirts, Pants, Quantity) VALUES ('$shirts','$pants','$quantity')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Failed " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
After i searched for this solution on this site, nothing i found. Here is basic php code, just for testing.
index.php
<input type="checkbox" name="chk" id="chk" value="1" />
<button type="button" name="" id="submit">TEST</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var check = $('#chk').val();
$.ajax({
url:"qry.php",
method:"POST",
data: {check:check},
success:function(data)
{
//alert(data);
window.location.reload();
}
});
});
});
</script>
qry.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "check";
// Create connection
$connect = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
if($_REQUEST['chk'] == true){
$stok = '1';
}
elseif ($_REQUEST['chk'] == false) {
$stok = '0';
}
$query = "INSERT INTO test(checked) VALUES('$stok')";
$result = mysqli_query($connect, $query);
if ($result === TRUE) {
echo "Zahtev je uspešno poslat!";
} else {
echo "Error: " . $query . "<br>" . $connect->error;
}
?>
How to set checkbox checked true or false into mysql and then echo if in html? It's always set to 0 in mysql boolen.
<input type="hidden" name="chk" id="chk" value="1" <?php if ($checked == '1') {echo 'checked';} else {} ?>/>
I tried everything from this site and nothing works.
Try this Jquery. This will get rid of the always value 1 problem you're having. What this code does is when you click on the "submit" button it check the status of your check box. If the check box is checked then the code will take the checked check box value and send that in the ajax function if it's not checked then the value 0 get assigned and that will be sent using the ajax.
Doing this will reduce the work has to be done by the back end PHP. I also made some changes to your PHP code as well.
$(document).ready(function() {
$(document).on('click', '#submit', function() {
if ($("#chk").is(":checked")) {
var chk = $('#chk').val();
}else{
chk = 0;
}
$.ajax({
url: "qry.php",
method: "POST",
data: {
check: chk
},
success: function(data) {
//alert(data);
window.location.reload();
}
});
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="chk" id="chk" value="1" />
<button type="button" name="" id="submit">TEST</button>
You will see that the way I'm inserting the data is a bit different from the way you have done. I'm using mysqli_ prepared statements which makes SQL injection a hard to do.
$query = $connect -> prepare("INSERT INTO test(checked) VALUES (?)";
$query -> bind_param("i", $_REQUEST['check']);
if ($query -> execute()) {
echo "Zahtev je uspešno poslat!";
} else {
echo "Error: " . $query . "<br>" . $connect->error;
}
jsFiddle if you want to test it.
You write the value into check, but read it back from $_REQUEST['chk']. That won't work. Change that to $_REQUEST['check'].
You are using val() to get the state of the checkbox, you should use checked.
Also, you are possibly open to SQL injection, start using prepared statements.
Add another line while sending the AJAX request.
While sending the value of checkbox, send 1 or 0.
It will reduce our work at PHP end.
So, the code should be:
var check = $('#chk').is(":checked");
check = (check) ? 1 : 0;
Final code should be:
<input type="checkbox" name="chk" id="chk" value="1" />
<button type="button" name="" id="submit">TEST</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var check = $('#chk').val();
check = (check) ? 1 : 0;
$.ajax({
url:"qry.php",
method:"POST",
data: {check:check},
success:function(data) {
//alert(data);
window.location.reload();
}
});
});
});
</script>
And PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "check";
// Create connection
$connect = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
$stok = $_REQUEST['chk'];
$query = "INSERT INTO test(checked) VALUES('$stok')";
$result = mysqli_query($connect, $query);
if ($result === TRUE) {
echo "Zahtev je uspešno poslat!";
}
else {
echo "Error: " . $query . "<br>" . $connect->error;
}
?>
I am trying to show data from the database in my textbox. But when I start the script I am getting no results. I tested the script in different ways and i figured out that the variable: $product1 is empty. Does anybody know how I can fix this?
index.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM forms";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<select class='form-control select2' id='product1' name='product1' onChange='getPrice(this.value)' style='width: 100%;'>";
echo "<option selected disabled hidden value=''></option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["id"]. "'>" . $row["name"]. "</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$conn->close();
?>
<html>
<body>
<!-- Your text input -->
<input id="product_name" type="text">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getPrice() {
// getting the selected id in combo
var selectedItem = jQuery('.product1 option:selected').val();
// Do an Ajax request to retrieve the product price
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: 'id=' + selectedItem,
success: function(response){
// and put the price in text field
jQuery('#product_name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
</body>
</html>
get.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname) ;
// Check connection
if ($conn->connect_error)
{
die('Connection failed: ' . $conn->connect_error) ;
}
else
{
$product1 = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT) ;
$query = 'SELECT price FROM forms WHERE id=" . $product1 . " ' ;
$res = mysqli_query($conn, $query) ;
if (mysqli_num_rows($res) > 0)
{
$result = mysqli_fetch_assoc($res) ;
echo $result['price'];
}else{
echo 'no results';
}
}
?>
Change
var selectedItem = jQuery('.product1 option:selected').val();
To
var selectedItem = jQuery('#product1 option:selected').val();
You are selecting a class with name product1, but you set only an ID with this name. Id's are specified with # and classes with .
Update on your script, because you used getPrice(this.value);
<script>
function getPrice(selectedItem) {
// Do an Ajax request to retrieve the product price
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: 'id=' + selectedItem,
success: function(response){
// and put the price in text field
jQuery('#product_name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
TIP:
Did you know that you can use jQuery.ajax and jQuery('selector') also like this: $.ajax and $('selector') :-)
You have not a form tag in your HTML. The default form Method is GET.
In Your get.php you try to get a POST Variable with filter_input
The function filter_input returns null if the Variable is not set.
Two possible solutions:
1. Add a form to your html with method="post"
2. Change your php code to search for a GET variable
This is a weird problem and I'm not sure how to approach it.
At the moment I'm trying to have the user enter an ingredient - a list of ingredients appears as you type with buttons next to them to add them which should insert them into SQL database.
The list population ceases to function when I uncomment
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
In the .click function of the add button.
Which is strange because it's like the .keyup function just stops working.
<html>
<head>
<title>Cocktails</title>
<script src="http://assets.absolutdrinks.com/api/addb-0.5.2.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<form>
<input type="text" name="ingredientinput" id="ingredientinput"><br>
</form>
<div id="ingredientlist">
</div>
<script>
$(document).ready(function(){
//ajax call to query cokctail DB
//handleData is callback function that handles result
function get_ingredients(query,handleData){
var apikey = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
var rooturl = "http://addb.absolutdrinks.com/";
$.ajax({
type: "GET",
url: rooturl + "/quickSearch/ingredients/" + query + "/",
dataType: 'jsonp',
data: {apiKey:apikey},
success: function(data) {
handleData(data);
},
error: function(){
//error
}
});
}
//when text is entered - quicksearch the database
$("#ingredientinput").keyup(function(){
query = $(this).val(); //value of textbox
divlist = ""; //list of ingredients
objectlist = {};
if (query.length > 0){
//set loading image on keypress
$("#ingredientlist").html("<img src='images/spinner.gif' alt='loading' height='24' width='24'>");
//pass query to ajax call and handle result
get_ingredients(query,function(data){
console.log(data);
//build list of ingredients
$.each(data["result"], function(key, value){
divlist += "<div id='" + value["id"] + "'>" + value["name"] + "<button class='addbutton' type='button' id = '"+value["id"]+"'>+</button></div>";
objectlist[value["id"]] = value;
//clicking button dumps object to file?
});
$("#ingredientlist").html(divlist); //populate div ingredientlist with results
divlist = ""; //clear html builder
});
console.log("input query:" + query);
}
else{
$("#ingredientlist").html(""); //if no input clear list
}
});
$("#ingredientlist").on('click','button.addbutton',function(){
$("#ingredientlist").on('click','button.addbutton',function(){
current = objectlist[this.id];
sqlquery = current["description"] + "," + current["id"] + "," + current["isAlcoholid"] + "," + current["isBaseSpirit"] + "," + current["isCarbonated"] + "," + current["isJuice"] + "," + current["languageBranch"] + "," + current["name"] + "," + current["type"];
console.log(sqlquery);
<?php
$servername = "localhost";
$username = "root";
$password = "**";
$dbname = "ingredients";
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql = "INSERT INTO cocktails (description, id, isAlcoholic, isBaseSpirit, isCarbonated, isJuice, languageBranch, name, type)
VALUES ('test','test','test','test','test','test','test','test','test',)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysqli_close($conn);
?>
});
});
});
</script>
</body>
</html>
You can't just embed a save query from within javascript like you are doing. This is a server side function that needs to happen, and return a result (Almost like you're doing with your get_ingredients function.)
My suggestion, is create a save_ingredients function that works through ajax to pass the information (In this case, the ingredient to save) to the server.
in saveingredients.php:
<?php
$servername = "localhost";
$username = "root";
$password = "**";
$dbname = "ingredients";
$conn = new mysqli($servername, $username, $password, $dbname);
$description = filter_input(INPUT_GET, 'description', $_GET['description'], FILTER_SANITIZE_SPECIAL_CHARS);
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$isAlcoholic = filter_input(INPUT_GET, 'isAlcoholic', FILTER_VALIDATE_BOOLEAN);
$isBaseSpirit = filter_input(INPUT_GET, 'isBaseSpirit', FILTER_VALIDATE_BOOLEAN);
$isCarbonated = filter_input(INPUT_GET, 'isCarbonated', FILTER_VALIDATE_BOOLEAN);
$isJuice = filter_input(INPUT_GET, 'isJuice', FILTER_VALIDATE_BOOLEAN);
$languageBranch = filter_input(INPUT_GET, 'languageBranch', FILTER_SANITIZE_SPECIAL_CHARS);
$name = filter_input(INPUT_GET, 'name', FILTER_SANITIZE_SPECIAL_CHARS);
$type = filter_input(INPUT_GET, 'type', FILTER_SANITIZE_SPECIAL_CHARS);
$sql = "INSERT INTO cocktails (description, id, isAlcoholic, isBaseSpirit, isCarbonated, isJuice, languageBranch, name, type)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
if ( $stmt = $conn->prepare($sql) )
{
$stmt->bind_param('sdsssssss', $description, $id, $isAlcoholic, $isBaseSpirit, $isJuice, $languageBranch, $name, $type);
if ($stmt->execute($sql) === TRUE) {
echo json_encode('error' => false);
} else {
echo json_encode('error' => 'MySQL Error: ' . $conn->error);
}
}
$conn->close($conn);
?>
A sample AJAX function:
function saveingredients(current) {
$.ajax({
url: 'saveingredients.php',
data: {
description: current["description"],
id: current["id"],
isAlcoholid: current["isAlcoholid"],
isBaseSpirit: current["isBaseSpirit"],
isCarbonated: current["isCarbonated"],
isJuice: current["isJuice"],
languageBranch: current["languageBranch"],
name: current["name"],
type: current["type"]
},
success: function(res) {
if ( res.error )
{
console.log(res.error);
}
else
{
//Do something here because it inserted correctly.
}
},
failure: function(err) {
console.log(err);
}
});
}